diff --git "a/fim_django.jsonl" "b/fim_django.jsonl" new file mode 100644--- /dev/null +++ "b/fim_django.jsonl" @@ -0,0 +1,1642 @@ +{"prefix": "one, env=None, dry_run=True):\n \"\"\"Run a command with optional dry-run behavior.\"\"\"\n environ = os.environ.copy()\n if env:\n environ.update(env)\n if dry_run:\n print(\"[DRY RUN]\", \" \".join(cmd))\n else:\n print(\"[EXECUTE]\", \" \".join(cmd))\n try:\n result = subprocess.check_output(\n cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT\n )\n except subprocess.CalledProcessError as e:\n result = e.output\n print(\" ", "suffix": "ctory not provided (--checkout-dir).\")\n if not os.path.exists(checkout_dir):\n sys.exit(f\"Error: checkout directory '{checkout_dir}' does not exist.\")\n if not os.path.isdir(checkout_dir):\n sys.exit(f\"Error: '{checkout_dir}' is not a dire", "middle": " [ERROR]\", result)\n raise\n else:\n print(\" [RESULT]\", result)\n return result.decode().strip()\n\n\ndef validate_env(checkout_dir):\n if not checkout_dir:\n sys.exit(\"Error: checkout dire", "meta": {"filepath": "scripts/archive_eol_stable_branches.py", "language": "python", "file_size": 4716, "cut_index": 614, "middle_length": 229}} +{"prefix": "rocess\nfrom datetime import date\n\nchecksum_file_text = \"\"\"This file contains MD5, SHA1, and SHA256 checksums for the\nsource-code tarball and wheel files of Django {django_version}, released {release_date}.\n\nIt also includes the commit hash of the release tag, identifying the exact\nsource revision the artifacts were built from.\n\nTo use this file, you will need a working install of PGP or other\ncompatible public-key encryption software. You will also need to have\nthe Django release manager's public key in you", "suffix": "or via the GitHub API:\n\n curl {pgp_key_url} | gpg --import -\n\nOnce the key is imported, verify this file:\n\n gpg --verify {checksum_file_name}\n\nOnce you have verified this file, you can use normal MD5, SHA1, or SHA256\nchecksumming applications to gene", "middle": "r keyring. This key has\nthe ID ``{pgp_key_id}`` and can be imported from the MIT\nkeyserver, for example, if using the open-source GNU Privacy Guard\nimplementation of PGP:\n\n gpg --keyserver pgp.mit.edu --recv-key {pgp_key_id}\n\n", "meta": {"filepath": "scripts/do_django_release.py", "language": "python", "file_size": 7718, "cut_index": 716, "middle_length": 229}} +{"prefix": "on any branch:\n- Ensures the summary line ends with a period.\n\nAdditionally, on stable branches:\n- Adds the [A.B.x] branch prefix if missing.\n- Adds \"Backport of from main.\" when cherry-picking.\n\nTo install:\n 1. Ensure the folder `.git/hooks` exists.\n 2. Create an executable file `.git/hooks/prepare-commit-msg` with content:\n\n#!/bin/sh\nexec python scripts/prepare_commit_msg.py \"$@\"\n\n\"\"\"\n\nimport os\nimport subprocess\nimport sys\n\n\ndef run(cmd):\n return subprocess.run(cmd, capture_output=True, text=T", "suffix": "ds with a period.\n - On stable branches, adds the [A.B.x] prefix to the first line if missing.\n - If cherry_sha is provided, appends \"Backport of from main.\" to\n the body if not already present.\n\n Returns the modified lines (body + comm", "middle": "rue).stdout.strip()\n\n\ndef process_commit_message(lines, branch, cherry_sha=None):\n \"\"\"Adjust commit message lines for a potential backport.\n\n - Separates body lines from trailing git comment lines.\n - Ensure all lines en", "meta": {"filepath": "scripts/prepare_commit_msg.py", "language": "python", "file_size": 3543, "cut_index": 614, "middle_length": 229}} +{"prefix": "ting-code/#committing-guidelines)).\",\n \"I have not requested, and will not request, an automated AI review\"\n \" for this PR.\"\n \" \",\n 'I have checked the \"Has patch\" ticket flag in the Trac system.',\n \"I have added or updated relevant tests.\",\n \"I have added or updated relevant docs, including release notes if\"\n \" applicable.\",\n \"I have attached screenshots in both light and dark modes for any UI\"\n ", "suffix": "ading spaces.\n return (\n f\"#### Trac ticket number\\n\"\n f\"\\n\"\n f'\\n'\n f\"\\n\"\n f\"{ticket}\\", "middle": " \" changes.\",\n ]\n checklist_lines = \"\\n\".join(\n f\"- [x] {item}\" if i < checked_items else f\"- [ ] {item}\"\n for i, item in enumerate(checklist_items)\n )\n\n # GitHub PR bodies are plain markdown with no le", "meta": {"filepath": "scripts/pr_quality/tests/test_check_pr.py", "language": "python", "file_size": 39032, "cut_index": 2151, "middle_length": 229}} +{"prefix": "on Middleware.\n\nThis module provides a middleware that implements protection against a\nmalicious site loading resources from your site in a hidden frame.\n\"\"\"\n\nfrom django.conf import settings\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass XFrameOptionsMiddleware(MiddlewareMixin):\n \"\"\"\n Set the X-Frame-Options HTTP header in HTTP responses.\n\n Do not set the header if it's already set or if the response contains\n a xframe_options_exempt value set to True.\n\n By default, set the X-F", "suffix": "in your project's Django settings to 'SAMEORIGIN'.\n \"\"\"\n\n def process_response(self, request, response):\n # Don't set it if it's already in the response\n if response.get(\"X-Frame-Options\") is not None:\n return response\n\n ", "middle": "rame-Options header to 'DENY', meaning the response\n cannot be displayed in a frame, regardless of the site attempting to do so.\n To enable the response to be loaded on a frame within the same site, set\n X_FRAME_OPTIONS ", "meta": {"filepath": "django/middleware/clickjacking.py", "language": "python", "file_size": 1724, "cut_index": 537, "middle_length": 229}} +{"prefix": "rom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.text import acompress_sequence, compress_sequence, compress_string\n\nre_accepts_gzip = _lazy_re_compile(r\"\\bgzip\\b\")\n\n\nclass GZipMiddleware(MiddlewareMixin):\n \"\"\"\n Compress content if the browser allows gzip compression.\n Set the Vary header accordingly, so that caches will base their storage\n on the Accept-Encoding header.\n \"\"\"\n\n max_random_bytes = 100\n\n def proce", "suffix": "g if we've already got a content-encoding.\n if response.has_header(\"Content-Encoding\"):\n return response\n\n patch_vary_headers(response, (\"Accept-Encoding\",))\n\n ae = request.META.get(\"HTTP_ACCEPT_ENCODING\", \"\")\n if not", "middle": "ss_response(self, request, response):\n # It's not worth attempting to compress really short responses.\n if not response.streaming and len(response.content) < 200:\n return response\n\n # Avoid gzippin", "meta": {"filepath": "django/middleware/gzip.py", "language": "python", "file_size": 2626, "cut_index": 563, "middle_length": 229}} +{"prefix": "None, flags=None\n ):\n if regex is not None:\n self.regex = regex\n if message is not None:\n self.message = message\n if code is not None:\n self.code = code\n if inverse_match is not None:\n self.inverse_match = inverse_match\n if flags is not None:\n self.flags = flags\n if self.flags and not isinstance(self.regex, str):\n raise TypeError(\n \"If the flags are set, regex must be a regular expre", "suffix": "True) a match for the regular expression.\n \"\"\"\n regex_matches = self.regex.search(str(value))\n invalid_input = regex_matches if self.inverse_match else not regex_matches\n if invalid_input:\n raise ValidationError(self.", "middle": "ssion string.\"\n )\n\n self.regex = _lazy_re_compile(self.regex, self.flags)\n\n def __call__(self, value):\n \"\"\"\n Validate that the input contains (or does *not* contain, if\n inverse_match is ", "meta": {"filepath": "django/core/validators.py", "language": "python", "file_size": 22484, "cut_index": 1331, "middle_length": 229}} +{"prefix": "inted error\n message to the appropriate output stream (i.e., stderr); as a\n result, raising this exception (with a sensible description of the\n error) is the preferred way to indicate that something has gone\n wrong in the execution of a command.\n \"\"\"\n\n def __init__(self, *args, returncode=1, **kwargs):\n self.returncode = returncode\n super().__init__(*args, **kwargs)\n\n\nclass SystemCheckError(CommandError):\n \"\"\"\n The system check framework detected unrecoverable errors.\n ", "suffix": "is called programmatically.\n \"\"\"\n\n def __init__(\n self, *, missing_args_message=None, called_from_command_line=None, **kwargs\n ):\n self.missing_args_message = missing_args_message\n self.called_from_command_line = called_from_c", "middle": " \"\"\"\n\n pass\n\n\nclass CommandParser(ArgumentParser):\n \"\"\"\n Customized ArgumentParser class to improve some error messages and prevent\n SystemExit in several occasions, as SystemExit is unacceptable when a\n command ", "meta": {"filepath": "django/core/management/base.py", "language": "python", "file_size": 25059, "cut_index": 1331, "middle_length": 229}} +{"prefix": ".startswith(\"_\") or not k.isupper()):\n \"\"\"Convert a module namespace to a Python dictionary.\"\"\"\n return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)}\n\n\nclass Command(BaseCommand):\n help = \"\"\"Displays differences between the current settings.py and Django's\n default settings.\"\"\"\n\n requires_system_checks = []\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--all\",\n action=\"store_true\",\n help=(\n 'Displa", "suffix": " help=(\n \"The settings module to compare the current settings against. Leave \"\n \"empty to compare against Django's default settings.\"\n ),\n )\n parser.add_argument(\n \"--output\",\n ", "middle": "y all settings, regardless of their value. In \"hash\" '\n 'mode, default values are prefixed by \"###\".'\n ),\n )\n parser.add_argument(\n \"--default\",\n metavar=\"MODULE\",\n ", "meta": {"filepath": "django/core/management/commands/diffsettings.py", "language": "python", "file_size": 3564, "cut_index": 614, "middle_length": 229}} +{"prefix": "o.core.mail import mail_admins, mail_managers, send_mail\nfrom django.core.management.base import BaseCommand\nfrom django.utils import timezone\n\n\nclass Command(BaseCommand):\n help = \"Sends a test email to the email addresses specified as arguments.\"\n missing_args_message = (\n \"You must specify some email recipients, or pass the --managers or --admin \"\n \"options.\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"email\",\n nargs=\"*\",\n ", "suffix": "ttings.MANAGERS.\",\n )\n parser.add_argument(\n \"--admins\",\n action=\"store_true\",\n help=\"Send a test email to the addresses specified in settings.ADMINS.\",\n )\n\n def handle(self, *args, **kwargs):\n ", "middle": " help=\"One or more email addresses to send a test email to.\",\n )\n parser.add_argument(\n \"--managers\",\n action=\"store_true\",\n help=\"Send a test email to the addresses specified in se", "meta": {"filepath": "django/core/management/commands/sendtestemail.py", "language": "python", "file_size": 1518, "cut_index": 537, "middle_length": 229}} +{"prefix": "m django.core.management.base import BaseCommand\nfrom django.db import connection\n\n\nclass Command(BaseCommand):\n help = \"Runs a development server with data from the given fixture(s).\"\n\n requires_system_checks = []\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"fixture\",\n nargs=\"*\",\n help=\"Path(s) to fixtures to load before running the server.\",\n )\n parser.add_argument(\n \"--noinput\",\n ", "suffix": " default=\"\",\n help=\"Port number or ipaddr:port to run the server on.\",\n )\n parser.add_argument(\n \"--ipv6\",\n \"-6\",\n action=\"store_true\",\n dest=\"use_ipv6\",\n help=\"Tells Dj", "middle": " \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=\"Tells Django to NOT prompt the user for input of any kind.\",\n )\n parser.add_argument(\n \"--addrport\",\n ", "meta": {"filepath": "django/core/management/commands/testserver.py", "language": "python", "file_size": 2221, "cut_index": 563, "middle_length": 229}} +{"prefix": "giref import simple_server\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.handlers.wsgi import LimitedStream\nfrom django.core.wsgi import get_wsgi_application\nfrom django.db import connections\nfrom django.utils.log import log_message\nfrom django.utils.module_loading import import_string\n\n__all__ = (\"WSGIServer\", \"WSGIRequestHandler\")\n\nlogger = logging.getLogger(\"django.server\")\n\n\ndef get_internal_wsgi_application():\n \"\"\"\n Load and return the WSGI application as configured by", "suffix": "e only useful\n for Django's internal server (runserver); external WSGI servers should just\n be configured to point to the correct application object directly.\n\n If settings.WSGI_APPLICATION is not set (is ``None``), return\n whatever ``django.co", "middle": " the user in\n ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,\n this will be the ``application`` object in ``projectname/wsgi.py``.\n\n This function, and the ``WSGI_APPLICATION`` setting itself, ar", "meta": {"filepath": "django/core/servers/basehttp.py", "language": "python", "file_size": 9776, "cut_index": 921, "middle_length": 229}} +{"prefix": "(__file__).resolve().parent.parent\n sys.path[:0] = [str(repo_root / \"tests\"), str(repo_root)]\n\n from runtests import ALWAYS_INSTALLED_APPS, get_apps_to_install, get_test_modules\n\n import django\n from django.apps import apps\n from django.core.management import call_command\n\n django.setup()\n\n test_modules = list(get_test_modules(gis_enabled=False))\n installed_apps = list(ALWAYS_INSTALLED_APPS)\n for app in get_apps_to_install(test_modules):\n # Check against the list to prevent", "suffix": "pps:\n installed_apps.append(app)\n apps.set_installed_apps(installed_apps)\n\n # Note: We don't use check=True here because --check calls sys.exit(1)\n # instead of raising CommandError when migrations are missing.\n call_command(\"makemig", "middle": " duplicate errors.\n if app not in installed_a", "meta": {"filepath": "scripts/check_migrations.py", "language": "python", "file_size": 964, "cut_index": 582, "middle_length": 52}} +{"prefix": "ion\n#\n# * fetch: fetch translations from transifex.com\n#\n# Each command support the --languages and --resources options to limit their\n# operation to the specified language or resource. For example, to get stats\n# for Spanish in contrib.admin, run:\n#\n# $ python scripts/manage_translations.py lang_stats -l es -r admin\n#\n# Also each command supports a --verbosity option to get progress feedback.\n\nimport json\nimport os\nimport subprocess\nfrom argparse import ArgumentParser\nfrom collections import defaultdict\nf", "suffix": "]\nLANG_OVERRIDES = {\n \"zh_CN\": \"zh_Hans\",\n \"zh_TW\": \"zh_Hant\",\n}\n\n\ndef run(*args, verbosity=0, **kwargs):\n if verbosity > 1:\n print(f\"\\n** subprocess.run ** command: {args=} {kwargs=}\")\n return subprocess.run(*args, **kwargs)\n\n\ndef get_a", "middle": "rom configparser import ConfigParser\nfrom datetime import datetime\nfrom itertools import product\n\nimport requests\n\nimport django\nfrom django.conf import settings\nfrom django.core.management import call_command\n\nHAVE_JS = [\"admin\"", "meta": {"filepath": "scripts/manage_translations.py", "language": "python", "file_size": 13511, "cut_index": 921, "middle_length": 229}} +{"prefix": "ommit_msg import process_commit_message\n\n\nclass ParseMajorVersionTests(unittest.TestCase):\n def test_final_patch_release(self):\n self.assertEqual(parse_major_version(\"5.2.4\"), \"5.2\")\n\n def test_final_dot_zero_release(self):\n self.assertEqual(parse_major_version(\"6.0\"), \"6.0\")\n\n def test_alpha(self):\n self.assertEqual(parse_major_version(\"6.0a1\"), \"6.0\")\n\n def test_beta(self):\n self.assertEqual(parse_major_version(\"6.0b1\"), \"6.0\")\n\n def test_release_candidate(self):", "suffix": "NTENT = b\"fake wheel content\"\n TARBALL_CONTENT = b\"fake tarball content\"\n\n def generate_checksum_file(self, **overrides):\n with tempfile.TemporaryDirectory() as tmp:\n dist_path = os.path.join(tmp, \"dist\")\n os.mkdir(dist_p", "middle": "\n self.assertEqual(parse_major_version(\"6.0rc1\"), \"6.0\")\n\n def test_two_digit_minor(self):\n self.assertEqual(parse_major_version(\"5.10a1\"), \"5.10\")\n\n\nclass CreateChecksumFileTests(unittest.TestCase):\n WHEEL_CO", "meta": {"filepath": "scripts/tests.py", "language": "python", "file_size": 9342, "cut_index": 921, "middle_length": 229}} +{"prefix": "time.\n\n\"\"\"\n\nLEVEL_ERROR = (\"🛑\", \"Error\")\nLEVEL_WARNING = (\"⚠️\", \"Warning\")\n\n\nclass Message:\n \"\"\"A PR quality check message bound to its runtime formatting kwargs.\"\"\"\n\n def __init__(self, title, body, **kwargs):\n self.title = title\n self.body = body\n self.kwargs = kwargs\n\n def as_details(self, level=LEVEL_ERROR):\n body = self.body.format(**self.kwargs) if self.kwargs else self.body\n symbol, label = level\n return (\n f\"
\\n{s", "suffix": "code/submitting-patches/\"\nTRIAGING_URL = f\"{CONTRIBUTING_URL}triaging-tickets/\"\nFORUM_URL = \"https://forum.djangoproject.com\"\nTRAC_URL = \"https://code.djangoproject.com\"\n\n\nCHECKS_HEADER = (\n \"Thank you for your contribution to Django! This pull request ", "middle": "ymbol} {label}: {self.title}\"\n f\"\\n\\n{body}\\n\\n
\"\n )\n\n\nCONTRIBUTING_URL = \"https://docs.djangoproject.com/en/dev/internals/contributing/\"\nSUBMITTING_URL = f\"{CONTRIBUTING_URL}writing-", "meta": {"filepath": "scripts/pr_quality/errors.py", "language": "python", "file_size": 6891, "cut_index": 716, "middle_length": 229}} +{"prefix": "on\nimport logging\nimport os\nimport re\nimport sys\nimport time\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom datetime import date, datetime, timedelta, timezone\nfrom http import HTTPStatus\n\nfrom pr_quality.errors import (\n CHECKS_FOOTER,\n CHECKS_HEADER,\n INCOMPLETE_CHECKLIST,\n INVALID_TRAC_STATUS,\n LEVEL_ERROR,\n LEVEL_WARNING,\n MISSING_AI_DESCRIPTION,\n MISSING_AI_DISCLOSURE,\n MISSING_DESCRIPTION,\n MISSING_HAS_PATCH_FLAG,\n MISSING_TICKET_IN_PR_TITLE,\n MI", "suffix": "inel: Trac returned HTTP 404 for the ticket.\nURLOPEN_TIMEOUT_SECONDS = 15\n# PRs opened before these dates predate PR template additions.\nPR_TEMPLATE_DATE = date(2024, 3, 4) # 3fcef50 -- PR template introduced\nAI_DISCLOSURE_DATE = date(2026, 1, 8) # 4f580", "middle": "SSING_TRAC_TICKET,\n Message,\n)\n\nGITHUB_PER_PAGE = 100\nLARGE_PR_THRESHOLD = 80 # additions + deletions\nMIN_WORDS = 5\nSKIPPED = object() # Sentinel: check was not applicable and was skipped.\nTICKET_NOT_FOUND = object() # Sent", "meta": {"filepath": "scripts/pr_quality/check_pr.py", "language": "python", "file_size": 19541, "cut_index": 1331, "middle_length": 229}} +{"prefix": "p import (\n Http404,\n HttpResponse,\n HttpResponsePermanentRedirect,\n HttpResponseRedirect,\n)\nfrom django.template import loader\nfrom django.urls import NoReverseMatch, reverse\nfrom django.utils.functional import Promise\nfrom django.utils.http import MAX_URL_REDIRECT_LENGTH\nfrom django.utils.translation import gettext as _\n\n\ndef render(\n request, template_name, context=None, content_type=None, status=None, using=None\n):\n \"\"\"\n Return an HttpResponse whose content is filled with the result", "suffix": "s)\n\n\ndef redirect(\n to,\n *args,\n permanent=False,\n preserve_request=False,\n max_length=MAX_URL_REDIRECT_LENGTH,\n **kwargs,\n):\n \"\"\"\n Return an HttpResponseRedirect to the appropriate URL for the arguments\n passed.\n\n The argumen", "middle": " of calling\n django.template.loader.render_to_string() with the passed arguments.\n \"\"\"\n content = loader.render_to_string(template_name, context, request, using=using)\n return HttpResponse(content, content_type, statu", "meta": {"filepath": "django/shortcuts.py", "language": "python", "file_size": 6884, "cut_index": 716, "middle_length": 229}} +{"prefix": "django.utils.version import get_version\n\nVERSION = (6, 2, 0, \"alpha\", 0)\n\n__version__ = get_version(VERSION)\n\n\ndef setup(set_prefix=True):\n \"\"\"\n Configure the settings (this happens as a side effect of accessing the\n first setting), configure logging and populate the app registry.\n Set the thread-local urlresolvers script prefix if `set_prefix` is True.\n \"\"\"\n from django.apps import apps\n from django.conf import settings\n from django.urls import set_script_prefix\n from django.util", "suffix": "onfigure_logging\n\n configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\n if set_prefix:\n set_script_prefix(\n \"/\" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME\n )\n apps.populate(settings.INST", "middle": "s.log import c", "meta": {"filepath": "django/__init__.py", "language": "python", "file_size": 799, "cut_index": 517, "middle_length": 14}} +{"prefix": "and\n``FetchFromCacheMiddleware`` as the last::\n\n MIDDLEWARE = [\n 'django.middleware.cache.UpdateCacheMiddleware',\n ...\n 'django.middleware.cache.FetchFromCacheMiddleware'\n ]\n\nThis is counterintuitive, but correct: ``UpdateCacheMiddleware`` needs to run\nlast during the response phase, which processes middleware bottom-up;\n``FetchFromCacheMiddleware`` needs to run last during the request phase, which\nprocesses middleware top-down.\n\nThe single-class ``CacheMiddleware`` can be used fo", "suffix": "\nDjango's ``LocaleMiddleware``.\n\nMore details about how the caching works:\n\n* Only GET or HEAD-requests with status code 200 are cached.\n\n* The number of seconds each page is stored for is set by the \"max-age\" section\n of the response's \"Cache-Control\" he", "middle": "r some simple sites.\nHowever, if any other piece of middleware needs to affect the cache key, you'll\nneed to use the two-part ``UpdateCacheMiddleware`` and\n``FetchFromCacheMiddleware``. This'll most often happen when you're using", "meta": {"filepath": "django/middleware/cache.py", "language": "python", "file_size": 8880, "cut_index": 716, "middle_length": 229}} +{"prefix": "conf import settings\nfrom django.utils.csp import CSP, LazyNonce, build_policy\nfrom django.utils.deprecation import MiddlewareMixin\n\n\ndef get_nonce(request):\n return getattr(request, \"_csp_nonce\", None)\n\n\nclass ContentSecurityPolicyMiddleware(MiddlewareMixin):\n def process_request(self, request):\n request._csp_nonce = LazyNonce()\n\n def process_response(self, request, response):\n nonce = get_nonce(request)\n\n sentinel = object()\n if (csp_config := getattr(response, \"_csp_c", "suffix": " for header, config in [\n (CSP.HEADER_ENFORCE, csp_config),\n (CSP.HEADER_REPORT_ONLY, csp_ro_config),\n ]:\n # If headers are already set on the response, don't overwrite them.\n # This allows for views ", "middle": "onfig\", sentinel)) is sentinel:\n csp_config = settings.SECURE_CSP\n if (csp_ro_config := getattr(response, \"_csp_ro_config\", sentinel)) is sentinel:\n csp_ro_config = settings.SECURE_CSP_REPORT_ONLY\n\n ", "meta": {"filepath": "django/middleware/csp.py", "language": "python", "file_size": 1279, "cut_index": 524, "middle_length": 229}} +{"prefix": "om django.http import HttpResponsePermanentRedirect\nfrom django.urls import is_valid_path\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.http import escape_leading_slashes\n\n\nclass CommonMiddleware(MiddlewareMixin):\n \"\"\"\n \"Common\" middleware for taking care of some basic operations:\n\n - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS\n\n - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,\n append missing slashes and/or prepen", "suffix": "RL is found in\n urlpatterns, return an HTTP redirect to this new URL; otherwise\n process the initial URL as usual.\n\n This behavior can be customized by subclassing CommonMiddleware and\n overriding the response_re", "middle": "ds missing \"www.\"s.\n\n - If APPEND_SLASH is set and the initial URL doesn't end with a\n slash, and it is not found in urlpatterns, form a new URL by\n appending a slash at the end. If this new U", "meta": {"filepath": "django/middleware/common.py", "language": "python", "file_size": 8162, "cut_index": 716, "middle_length": 229}} +{"prefix": "ile\n\nlogger = logging.getLogger(\"django.security.csrf\")\n# This matches if any character is not in CSRF_ALLOWED_CHARS.\ninvalid_token_chars_re = _lazy_re_compile(\"[^a-zA-Z0-9]\")\n\nREASON_BAD_ORIGIN = \"Origin checking failed - %s does not match any trusted origins.\"\nREASON_NO_REFERER = \"Referer checking failed - no Referer.\"\nREASON_BAD_REFERER = \"Referer checking failed - %s does not match any trusted origins.\"\nREASON_NO_CSRF_COOKIE = \"CSRF cookie not set.\"\nREASON_CSRF_TOKEN_MISSING = \"CSRF token missing.\"\nREAS", "suffix": "dTokenFormat. They are\n# phrases without a subject because they can be in reference to either the CSRF\n# cookie or non-cookie token.\nREASON_INCORRECT_LENGTH = \"has incorrect length\"\nREASON_INVALID_CHARACTERS = \"has invalid characters\"\n\nCSRF_SECRET_LENGTH =", "middle": "ON_MALFORMED_REFERER = \"Referer checking failed - Referer is malformed.\"\nREASON_INSECURE_REFERER = (\n \"Referer checking failed - Referer is insecure while host is secure.\"\n)\n# The reason strings below are for passing to Invali", "meta": {"filepath": "django/middleware/csrf.py", "language": "python", "file_size": 19521, "cut_index": 1331, "middle_length": 229}} +{"prefix": "mport cc_delim_re, get_conditional_response, set_response_etag\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.http import parse_http_date_safe\n\n\nclass ConditionalGetMiddleware(MiddlewareMixin):\n \"\"\"\n Handle conditional GET operations. If the response has an ETag or\n Last-Modified header and the request has If-None-Match or\n If-Modified-Since, replace the response with HttpNotModified. Add an ETag\n header if needed.\n \"\"\"\n\n def process_response(self, request, respo", "suffix": " != \"GET\":\n return response\n\n if self.needs_etag(response) and not response.has_header(\"ETag\"):\n set_response_etag(response)\n\n etag = response.get(\"ETag\")\n last_modified = response.get(\"Last-Modified\")\n las", "middle": "nse):\n # It's too late to prevent an unsafe request with a 412 response, and\n # for a HEAD request, the response body is always empty so computing\n # an accurate ETag isn't possible.\n if request.method", "meta": {"filepath": "django/middleware/http.py", "language": "python", "file_size": 1620, "cut_index": 537, "middle_length": 229}} +{"prefix": "ango.http import HttpResponsePermanentRedirect\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass SecurityMiddleware(MiddlewareMixin):\n def __init__(self, get_response):\n super().__init__(get_response)\n self.sts_seconds = settings.SECURE_HSTS_SECONDS\n self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS\n self.sts_preload = settings.SECURE_HSTS_PRELOAD\n self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF\n self.redirect = set", "suffix": "Y\n self.cross_origin_opener_policy = settings.SECURE_CROSS_ORIGIN_OPENER_POLICY\n\n def process_request(self, request):\n path = request.path.lstrip(\"/\")\n if (\n self.redirect\n and not request.is_secure()\n ", "middle": "tings.SECURE_SSL_REDIRECT\n self.redirect_host = settings.SECURE_SSL_HOST\n self.redirect_exempt = [re.compile(r) for r in settings.SECURE_REDIRECT_EXEMPT]\n self.referrer_policy = settings.SECURE_REFERRER_POLIC", "meta": {"filepath": "django/middleware/security.py", "language": "python", "file_size": 2599, "cut_index": 563, "middle_length": 229}} +{"prefix": "validPage(Exception):\n pass\n\n\nclass PageNotAnInteger(InvalidPage):\n pass\n\n\nclass EmptyPage(InvalidPage):\n pass\n\n\nclass BasePaginator:\n # Translators: String used to replace omitted page numbers in elided page\n # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10].\n ELLIPSIS = _(\"…\")\n default_error_messages = {\n \"invalid_page\": _(\"That page number is not an integer\"),\n \"min_page\": _(\"That page number is less than 1\"),\n \"no_results\": _(\"That page cont", "suffix": " self._check_object_list_is_ordered()\n self.per_page = int(per_page)\n self.orphans = int(orphans)\n self.allow_empty_first_page = allow_empty_first_page\n self.error_messages = (\n self.default_error_messages\n ", "middle": "ains no results\"),\n }\n\n def __init__(\n self,\n object_list,\n per_page,\n orphans=0,\n allow_empty_first_page=True,\n error_messages=None,\n ):\n self.object_list = object_list\n ", "meta": {"filepath": "django/core/paginator.py", "language": "python", "file_size": 15061, "cut_index": 921, "middle_length": 229}} +{"prefix": "om django.http import HttpResponseRedirect\nfrom django.urls import get_script_prefix, is_valid_path\nfrom django.utils import translation\nfrom django.utils.cache import patch_vary_headers\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass LocaleMiddleware(MiddlewareMixin):\n \"\"\"\n Parse a request and decide what translation object to install in the\n current thread context. This allows pages to be dynamically translated to\n the language the user desires (if the language is available).\n ", "suffix": "default_language,\n ) = is_language_prefix_patterns_used(urlconf)\n language = translation.get_language_from_request(\n request, check_path=i18n_patterns_used\n )\n language_from_path = translation.get_language_from_path(r", "middle": "\"\"\"\n\n response_redirect_class = HttpResponseRedirect\n\n def process_request(self, request):\n urlconf = getattr(request, \"urlconf\", settings.ROOT_URLCONF)\n (\n i18n_patterns_used,\n prefixed_", "meta": {"filepath": "django/middleware/locale.py", "language": "python", "file_size": 3442, "cut_index": 614, "middle_length": 229}} +{"prefix": "signing.loads(s) checks the signature and returns the deserialized object.\nIf the signature fails, a BadSignature exception is raised.\n\n>>> signing.loads(\"ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk\")\n'hello'\n>>> signing.loads(\"ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified\")\n...\nBadSignature: Signature \"ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified\" does\nnot match\n\nYou can optionally compress the JSON prior to base64 encoding it to save\nspace, using the compress=True argument. This checks if compression a", "suffix": "'\n\nThe fact that the string is compressed is signalled by the prefixed '.' at the\nstart of the base64 JSON.\n\nThere are 65 url-safe characters: the 64 used by url-safe base64 and the ':'.\nThese functions make use of all of them.\n\"\"\"\n\nimport base64\nimport da", "middle": "ctually\nhelps and only applies compression if the result is a shorter string:\n\n>>> signing.dumps(list(range(1, 20)), compress=True)\n'.eJwFwcERACAIwLCF-rCiILN47r-GyZVJsNgkxaFxoDgxcOHGxMKD_T7vhAml:1QaUaL:BA0thEZrp4FQVXIXuOvYJtLJSrQ", "meta": {"filepath": "django/core/signing.py", "language": "python", "file_size": 9305, "cut_index": 921, "middle_length": 229}} +{"prefix": "s\n\n\nclass AppRegistryNotReady(Exception):\n \"\"\"The django.apps registry is not populated yet\"\"\"\n\n pass\n\n\nclass ObjectDoesNotExist(Exception):\n \"\"\"The requested object does not exist\"\"\"\n\n silent_variable_failure = True\n\n\nclass ObjectNotUpdated(Exception):\n \"\"\"The updated object no longer exists.\"\"\"\n\n\nclass MultipleObjectsReturned(Exception):\n \"\"\"The query returned multiple objects when only one was expected.\"\"\"\n\n pass\n\n\nclass SuspiciousOperation(Exception):\n \"\"\"The user did something s", "suffix": " attempted\"\"\"\n\n pass\n\n\nclass DisallowedHost(SuspiciousOperation):\n \"\"\"HTTP_HOST header contains invalid value\"\"\"\n\n pass\n\n\nclass DisallowedRedirect(SuspiciousOperation):\n \"\"\"Redirect was too long or scheme was not in allowed list.\"\"\"\n\n pass\n\n", "middle": "uspicious\"\"\"\n\n\nclass SuspiciousMultipartForm(SuspiciousOperation):\n \"\"\"Suspect MIME request in multipart form data\"\"\"\n\n pass\n\n\nclass SuspiciousFileOperation(SuspiciousOperation):\n \"\"\"A Suspicious filesystem operation was", "meta": {"filepath": "django/core/exceptions.py", "language": "python", "file_size": 6771, "cut_index": 716, "middle_length": 229}} +{"prefix": "s.log import log_response\nfrom django.utils.module_loading import import_string\n\nfrom .exception import convert_exception_to_response\n\nlogger = logging.getLogger(\"django.request\")\n\n\nclass BaseHandler:\n _view_middleware = None\n _template_response_middleware = None\n _exception_middleware = None\n _middleware_chain = None\n\n def load_middleware(self, is_async=False):\n \"\"\"\n Populate middleware lists from settings.MIDDLEWARE.\n\n Must be called after the environment is fixed (see ", "suffix": "else self._get_response\n handler = convert_exception_to_response(get_response)\n handler_is_async = is_async\n for middleware_path in reversed(settings.MIDDLEWARE):\n middleware = import_string(middleware_path)\n midd", "middle": "__call__ in\n subclasses).\n \"\"\"\n self._view_middleware = []\n self._template_response_middleware = []\n self._exception_middleware = []\n\n get_response = self._get_response_async if is_async ", "meta": {"filepath": "django/core/handlers/base.py", "language": "python", "file_size": 14840, "cut_index": 921, "middle_length": 229}} +{"prefix": "import set_script_prefix\nfrom django.utils.encoding import repercent_broken_unicode\nfrom django.utils.functional import cached_property\nfrom django.utils.regex_helper import _lazy_re_compile\n\n_slashes_re = _lazy_re_compile(rb\"/+\")\n\n\nclass LimitedStream(IOBase):\n \"\"\"\n Wrap another stream to disallow reading it past a number of bytes.\n\n Based on the implementation from werkzeug.wsgi.LimitedStream. See:\n https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828\n \"\"\"\n\n def __", "suffix": "f.limit\n if _pos >= limit:\n return b\"\"\n if size == -1 or size is None:\n size = limit - _pos\n else:\n size = min(size, limit - _pos)\n data = self._read(size)\n self._pos += len(data)\n ", "middle": "init__(self, stream, limit):\n self._read = stream.read\n self._readline = stream.readline\n self._pos = 0\n self.limit = limit\n\n def read(self, size=-1, /):\n _pos = self._pos\n limit = sel", "meta": {"filepath": "django/core/handlers/wsgi.py", "language": "python", "file_size": 7314, "cut_index": 716, "middle_length": 229}} +{"prefix": "gement_dir, \"commands\")\n return [\n name\n for _, name, is_pkg in pkgutil.iter_modules([command_dir])\n if not is_pkg and not name.startswith(\"_\")\n ]\n\n\ndef load_command_class(app_name, name):\n \"\"\"\n Given a command name and an application name, return the Command\n class instance. Allow all errors raised by the import process\n (ImportError, AttributeError) to propagate.\n \"\"\"\n module = import_module(\"%s.management.commands.%s\" % (app_name, name))\n return module.Comm", "suffix": "-- if a commands package exists, register all\n commands in that package.\n\n Core commands are always included. If a settings module has been\n specified, also include user-defined commands.\n\n The dictionary is in the format {command_name: app_nam", "middle": "and()\n\n\n@functools.cache\ndef get_commands():\n \"\"\"\n Return a dictionary mapping command names to their callback applications.\n\n Look for a management.commands package in django.core, and in each\n installed application ", "meta": {"filepath": "django/core/management/__init__.py", "language": "python", "file_size": 17413, "cut_index": 1331, "middle_length": 229}} +{"prefix": "rt (\n FileResponse,\n HttpRequest,\n HttpResponse,\n HttpResponseBadRequest,\n HttpResponseServerError,\n QueryDict,\n parse_cookie,\n)\nfrom django.urls import set_script_prefix\nfrom django.utils.functional import cached_property\n\nlogger = logging.getLogger(\"django.request\")\n\n\ndef get_script_prefix(scope):\n \"\"\"\n Return the script prefix to use from either the scope or a setting.\n \"\"\"\n if settings.FORCE_SCRIPT_NAME:\n return settings.FORCE_SCRIPT_NAME\n return scope.get(\"roo", "suffix": "up on trying to read a request\n # body and aborts.\n body_receive_timeout = 60\n\n def __init__(self, scope, body_file):\n self.scope = scope\n self._post_parse_error = False\n self._read_started = False\n self.resolver_match ", "middle": "t_path\", \"\") or \"\"\n\n\nclass ASGIRequest(HttpRequest):\n \"\"\"\n Custom request subclass that decodes from an ASGI-standard request dict\n and wraps request body handling.\n \"\"\"\n\n # Number of seconds until a Request gives ", "meta": {"filepath": "django/core/handlers/asgi.py", "language": "python", "file_size": 13839, "cut_index": 921, "middle_length": 229}} +{"prefix": " django.core.exceptions import (\n BadRequest,\n PermissionDenied,\n RequestDataTooBig,\n SuspiciousOperation,\n TooManyFieldsSent,\n TooManyFilesSent,\n)\nfrom django.http import Http404\nfrom django.http.multipartparser import MultiPartParserError\nfrom django.urls import get_resolver, get_urlconf\nfrom django.utils.log import log_response\nfrom django.views import debug\n\n\ndef convert_exception_to_response(get_response):\n \"\"\"\n Wrap the given get_response callable in exception-to-response conve", "suffix": "\n converted to 500 responses.\n\n This decorator is automatically applied to all middleware to ensure that\n no middleware leaks an exception and that the next middleware in the stack\n can rely on getting a response instead of an exception.\n \"\"", "middle": "rsion.\n\n All exceptions will be converted. All known 4xx exceptions (Http404,\n PermissionDenied, MultiPartParserError, SuspiciousOperation) will be\n converted to the appropriate response, and all other exceptions will be", "meta": {"filepath": "django/core/handlers/exception.py", "language": "python", "file_size": 5980, "cut_index": 716, "middle_length": 229}} +{"prefix": "mport termcolors\n\ntry:\n import colorama\n\n # Avoid initializing colorama in non-Windows platforms.\n colorama.just_fix_windows_console()\nexcept (\n AttributeError, # colorama <= 0.4.6.\n ImportError, # colorama is not installed.\n # If just_fix_windows_console() accesses sys.stdout with\n # WSGIRestrictedStdout.\n OSError,\n):\n HAS_COLORAMA = False\nelse:\n HAS_COLORAMA = True\n\n\ndef supports_color():\n \"\"\"\n Return True if the running system's terminal supports color,\n and False", "suffix": " \"\"\"\n try:\n # winreg is only available on Windows.\n import winreg\n except ImportError:\n return False\n else:\n try:\n reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, \"Console", "middle": " otherwise.\n \"\"\"\n\n def vt_codes_enabled_in_windows_registry():\n \"\"\"\n Check the Windows Registry to see if VT code handling has been enabled\n by default, see https://superuser.com/a/1300251/447564.\n ", "meta": {"filepath": "django/core/management/color.py", "language": "python", "file_size": 3168, "cut_index": 614, "middle_length": 229}} +{"prefix": "ango.template import Context, Engine\nfrom django.utils import archive\nfrom django.utils.http import parse_header_parameters\nfrom django.utils.version import get_docs_version\n\n\nclass TemplateCommand(BaseCommand):\n \"\"\"\n Copy either a Django application layout template or a Django project\n layout template into the specified directory.\n\n :param style: A color style object (see django.core.management.color).\n :param app_or_project: The string 'app' or 'project'.\n :param name: The name of the ap", "suffix": "supported URL schemes\n url_schemes = [\"http\", \"https\", \"ftp\"]\n # Rewrite the following suffixes when determining the target filename.\n rewrite_template_suffixes = (\n # Allow shipping invalid .py files without byte-compilation.\n (\".py", "middle": "plication or project.\n :param directory: The directory to which the template should be copied.\n :param options: The additional variables passed to project or app templates\n \"\"\"\n\n requires_system_checks = []\n # The ", "meta": {"filepath": "django/core/management/templates.py", "language": "python", "file_size": 15458, "cut_index": 921, "middle_length": 229}} +{"prefix": "rypto import get_random_string\nfrom django.utils.encoding import DEFAULT_LOCALE_ENCODING\n\nfrom .base import CommandError, CommandParser\n\n\ndef popen_wrapper(args, stdout_encoding=\"utf-8\"):\n \"\"\"\n Friendly wrapper around Popen.\n\n Return stdout output, stderr output, and OS status code.\n \"\"\"\n try:\n p = run(args, capture_output=True, close_fds=os.name != \"nt\")\n except OSError as err:\n raise CommandError(\"Error executing %s\" % args[0]) from err\n return (\n p.stdout.decode(", "suffix": "sed by\n using --extension/-e multiple times.\n\n For example: running 'django-admin makemessages -e js,txt -e xhtml -a'\n would result in an extension list: ['.js', '.txt', '.xhtml']\n\n >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.p", "middle": "stdout_encoding),\n p.stderr.decode(DEFAULT_LOCALE_ENCODING, errors=\"replace\"),\n p.returncode,\n )\n\n\ndef handle_extensions(extensions):\n \"\"\"\n Organize multiple extensions that are separated with commas or pas", "meta": {"filepath": "django/core/management/utils.py", "language": "python", "file_size": 5636, "cut_index": 716, "middle_length": 229}} +{"prefix": "db import BaseDatabaseCache\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import (\n DEFAULT_DB_ALIAS,\n DatabaseError,\n connections,\n models,\n router,\n transaction,\n)\n\n\nclass Command(BaseCommand):\n help = \"Creates the tables needed to use the SQL cache backend.\"\n\n requires_system_checks = []\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"table_name\",\n nargs=\"*\",\n help=", "suffix": "ALIAS,\n choices=tuple(connections),\n help=\"Nominates a database onto which the cache tables will be \"\n 'installed. Defaults to the \"default\" database.',\n )\n parser.add_argument(\n \"--dry-run\",\n ", "middle": "(\n \"Optional table names. Otherwise, settings.CACHES is used to find \"\n \"cache tables.\"\n ),\n )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_", "meta": {"filepath": "django/core/management/commands/createcachetable.py", "language": "python", "file_size": 4656, "cut_index": 614, "middle_length": 229}} +{"prefix": "pps import apps\nfrom django.db import models\n\n\ndef sql_flush(style, connection, reset_sequences=True, allow_cascade=False):\n \"\"\"\n Return a list of the SQL statements used to flush the database.\n \"\"\"\n tables = connection.introspection.django_table_names(\n only_existing=True, include_views=False\n )\n return connection.ops.sql_flush(\n style,\n tables,\n reset_sequences=reset_sequences,\n allow_cascade=allow_cascade,\n )\n\n\ndef emit_pre_migrate_signal(verbosity,", "suffix": " stdout = kwargs.get(\"stdout\", sys.stdout)\n stdout.write(\n \"Running pre-migrate handlers for application %s\" % app_config.label\n )\n models.signals.pre_migrate.send(\n sender=app_config,\n ", "middle": " interactive, db, **kwargs):\n # Emit the pre_migrate signal for every application.\n for app_config in apps.get_app_configs():\n if app_config.models_module is None:\n continue\n if verbosity >= 2:\n ", "meta": {"filepath": "django/core/management/sql.py", "language": "python", "file_size": 1851, "cut_index": 537, "middle_length": 229}} +{"prefix": "import find_command, is_ignored_path, popen_wrapper\n\n\ndef has_bom(fn):\n with fn.open(\"rb\") as f:\n sample = f.read(4)\n return sample.startswith(\n (codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)\n )\n\n\ndef is_dir_writable(path):\n try:\n with tempfile.NamedTemporaryFile(dir=path):\n pass\n except OSError:\n return False\n return True\n\n\nclass Command(BaseCommand):\n help = \"Compiles .po files to .mo files for use with builtin gettext support.\"\n\n ", "suffix": "\",\n default=[],\n help=\"Locale(s) to process (e.g. de_AT). Default is to process all. \"\n \"Can be used multiple times.\",\n )\n parser.add_argument(\n \"--exclude\",\n \"-x\",\n action=\"ap", "middle": " requires_system_checks = []\n\n program = \"msgfmt\"\n program_options = [\"--check-format\"]\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--locale\",\n \"-l\",\n action=\"append", "meta": {"filepath": "django/core/management/commands/compilemessages.py", "language": "python", "file_size": 7010, "cut_index": 716, "middle_length": 229}} +{"prefix": "t checks\nfrom django.core.checks.registry import registry\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import connections\n\n\nclass Command(BaseCommand):\n help = \"Checks the entire Django project for potential problems.\"\n\n requires_system_checks = []\n\n def add_arguments(self, parser):\n parser.add_argument(\"args\", metavar=\"app_label\", nargs=\"*\")\n parser.add_argument(\n \"--tag\",\n \"-t\",\n action=\"append\",\n dest=\"", "suffix": "y --deploy to include available deployment \"\n \"tags.\"\n ),\n )\n parser.add_argument(\n \"--deploy\",\n action=\"store_true\",\n help=\"Check deployment settings.\",\n )\n parser.add_", "middle": "tags\",\n help=\"Run only checks labeled with given tag.\",\n )\n parser.add_argument(\n \"--list-tags\",\n action=\"store_true\",\n help=(\n \"List available tags. Specif", "meta": {"filepath": "django/core/management/commands/check.py", "language": "python", "file_size": 2832, "cut_index": 563, "middle_length": 229}} +{"prefix": "jango.core.management.base import BaseCommand, CommandError\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\n\nclass Command(BaseCommand):\n help = (\n \"Runs the command-line client for specified database, or the \"\n \"default database if none is provided.\"\n )\n\n requires_system_checks = []\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n ", "suffix": "t(\"parameters\", nargs=\"*\")\n\n def handle(self, **options):\n connection = connections[options[\"database\"]]\n try:\n connection.client.runshell(options[\"parameters\"])\n except FileNotFoundError:\n # Note that we're as", "middle": " \"Nominates a database onto which to open a shell. Defaults to the \"\n '\"default\" database.'\n ),\n )\n parameters = parser.add_argument_group(\"parameters\")\n parameters.add_argumen", "meta": {"filepath": "django/core/management/commands/dbshell.py", "language": "python", "file_size": 1762, "cut_index": 537, "middle_length": 229}} +{"prefix": "s_lzma = True\nexcept ImportError:\n has_lzma = False\n\n\nclass ProxyModelWarning(Warning):\n pass\n\n\nclass Command(BaseCommand):\n help = (\n \"Output the contents of the database as a fixture of the given format \"\n \"(using each model's default manager unless --all is specified).\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"app_label[.ModelName]\",\n nargs=\"*\",\n help=(\n \"Restricts dumped d", "suffix": "tion format for fixtures.\",\n )\n parser.add_argument(\n \"--indent\",\n type=int,\n help=\"Specifies the indent level to use when pretty-printing output.\",\n )\n parser.add_argument(\n \"--databa", "middle": "ata to the specified app_label or \"\n \"app_label.ModelName.\"\n ),\n )\n parser.add_argument(\n \"--format\",\n default=\"json\",\n help=\"Specifies the output serializa", "meta": {"filepath": "django/core/management/commands/dumpdata.py", "language": "python", "file_size": 11194, "cut_index": 921, "middle_length": 229}} +{"prefix": "S,\n choices=tuple(connections),\n help=(\n 'Nominates a database to introspect. Defaults to using the \"default\" '\n \"database.\"\n ),\n )\n parser.add_argument(\n \"--include-partitions\",\n action=\"store_true\",\n help=\"Also output models for partition tables.\",\n )\n parser.add_argument(\n \"--include-views\",\n action=\"store_true\",\n help=\"Also output models for databas", "suffix": " else:\n raise CommandError(\n \"Database inspection isn't supported for the currently selected \"\n \"database backend.\"\n )\n\n def handle_inspection(self, options):\n connection = connections[option", "middle": "e views.\",\n )\n\n def handle(self, **options):\n if connections[options[\"database\"]].features.supports_inspectdb:\n for line in self.handle_inspection(options):\n self.stdout.write(line)\n ", "meta": {"filepath": "django/core/management/commands/inspectdb.py", "language": "python", "file_size": 17670, "cut_index": 1331, "middle_length": 229}} +{"prefix": "\\s*$', re.MULTILINE | re.DOTALL\n)\nSTATUS_OK = 0\nNO_LOCALE_DIR = object()\n\n\ndef check_programs(*programs):\n for program in programs:\n if find_command(program) is None:\n raise CommandError(\n f\"Can't find {program}. Make sure you have GNU gettext tools \"\n \"0.19 or newer installed.\"\n )\n\n\ndef is_valid_locale(locale):\n return re.match(r\"^[a-z]+$\", locale) or re.match(r\"^[a-z]+_[A-Z0-9].*$\", locale)\n\n\n@total_ordering\nclass TranslatableFile:\n def _", "suffix": "name__,\n os.sep.join([self.dirpath, self.file]),\n )\n\n def __eq__(self, other):\n return self.path == other.path\n\n def __lt__(self, other):\n return self.path < other.path\n\n @property\n def path(self):\n return", "middle": "_init__(self, dirpath, file_name, locale_dir):\n self.file = file_name\n self.dirpath = dirpath\n self.locale_dir = locale_dir\n\n def __repr__(self):\n return \"<%s: %s>\" % (\n self.__class__.__", "meta": {"filepath": "django/core/management/commands/makemessages.py", "language": "python", "file_size": 29123, "cut_index": 1331, "middle_length": 229}} +{"prefix": "s database schema. Manages both apps with migrations and those without.\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_label\",\n nargs=\"?\",\n help=\"App label of an application to synchronize the state.\",\n )\n parser.add_argument(\n \"migration_name\",\n nargs=\"?\",\n help=\"Database state will be brought to the state after that \"\n 'migration. Use the name \"zero\" to unapply all migrations.',\n ", "suffix": ",\n )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n 'Nominates a database to synchronize. Defaults to the \"default\" '\n ", "middle": " )\n parser.add_argument(\n \"--noinput\",\n \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=\"Tells Django to NOT prompt the user for input of any kind.\"", "meta": {"filepath": "django/core/management/commands/migrate.py", "language": "python", "file_size": 21505, "cut_index": 1331, "middle_length": 229}} +{"prefix": ".servers.basehttp import WSGIServer, get_internal_wsgi_application, run\nfrom django.db import connections\nfrom django.utils import autoreload\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.version import get_docs_version\n\nnaiveip_re = _lazy_re_compile(\n r\"\"\"^(?:\n(?P\n (?P\\d{1,3}(?:\\.\\d{1,3}){3}) | # IPv4 address\n (?P\\[[a-fA-F0-9:]+\\]) | # IPv6 address\n (?P[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*) # FQDN\n):)?(?P\\d+)$\"\"\",\n re", "suffix": "7.0.0.1\"\n default_addr_ipv6 = \"::1\"\n default_port = \"8000\"\n protocol = \"http\"\n server_cls = WSGIServer\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"addrport\", nargs=\"?\", help=\"Optional port number, or ipaddr:p", "middle": ".X,\n)\n\n\nclass Command(BaseCommand):\n help = \"Starts a lightweight web server for development.\"\n\n stealth_options = (\"shutdown_message\",)\n suppressed_base_arguments = {\"--verbosity\", \"--traceback\"}\n\n default_addr = \"12", "meta": {"filepath": "django/core/management/commands/runserver.py", "language": "python", "file_size": 7560, "cut_index": 716, "middle_length": 229}} +{"prefix": "e.management.utils import parse_apps_and_model_labels\nfrom django.db import (\n DEFAULT_DB_ALIAS,\n DatabaseError,\n IntegrityError,\n connections,\n router,\n transaction,\n)\nfrom django.utils.functional import cached_property\n\ntry:\n import bz2\n\n has_bz2 = True\nexcept ImportError:\n has_bz2 = False\n\ntry:\n import lzma\n\n has_lzma = True\nexcept ImportError:\n has_lzma = False\n\nREAD_STDIN = \"-\"\n\n\nclass Command(BaseCommand):\n help = \"Installs the named fixture(s) in the database.\"\n", "suffix": " \"args\", metavar=\"fixture\", nargs=\"+\", help=\"Fixture labels.\"\n )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n \"Nominates ", "middle": " missing_args_message = (\n \"No database fixture specified. Please provide the path of at least \"\n \"one fixture in the command line.\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n ", "meta": {"filepath": "django/core/management/commands/loaddata.py", "language": "python", "file_size": 16008, "cut_index": 921, "middle_length": 229}} +{"prefix": "tions\nfrom django.db.migrations.exceptions import AmbiguityError\nfrom django.db.migrations.loader import MigrationLoader\nfrom django.db.migrations.optimizer import MigrationOptimizer\nfrom django.db.migrations.writer import MigrationWriter\nfrom django.utils.version import get_docs_version\n\n\nclass Command(BaseCommand):\n help = \"Optimizes the operations for the named migration.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_label\",\n help=\"App label of the app", "suffix": " action=\"store_true\",\n help=\"Exit with a non-zero status if the migration can be optimized.\",\n )\n\n def handle(self, *args, **options):\n verbosity = options[\"verbosity\"]\n app_label = options[\"app_label\"]\n m", "middle": "lication to optimize the migration for.\",\n )\n parser.add_argument(\n \"migration_name\", help=\"Migration name to optimize the operations for.\"\n )\n parser.add_argument(\n \"--check\",\n ", "meta": {"filepath": "django/core/management/commands/optimizemigration.py", "language": "python", "file_size": 5244, "cut_index": 716, "middle_length": 229}} +{"prefix": "ort BaseCommand, CommandError\nfrom django.core.management.color import no_style\nfrom django.core.management.sql import emit_post_migrate_signal, sql_flush\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\n\nclass Command(BaseCommand):\n help = (\n \"Removes ALL DATA from the database, including data added during \"\n 'migrations. Does not achieve a \"fresh install\" state.'\n )\n stealth_options = (\"reset_sequences\", \"allow_cascade\", \"inhibit_post_migrate\")\n\n def add_arguments(self, parse", "suffix": " )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help='Nominates a database to flush. Defaults to the \"default\" database.',\n )\n\n def handle(", "middle": "r):\n parser.add_argument(\n \"--noinput\",\n \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=\"Tells Django to NOT prompt the user for input of any kind.\",\n", "meta": {"filepath": "django/core/management/commands/flush.py", "language": "python", "file_size": 3623, "cut_index": 614, "middle_length": 229}} +{"prefix": "and(BaseCommand):\n help = (\n \"Runs a Python interactive interpreter. Tries to use IPython or \"\n \"bpython, if one of them is available. Any standard input is executed \"\n \"as code.\"\n )\n\n requires_system_checks = []\n shells = [\"ipython\", \"bpython\", \"python\"]\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--no-startup\",\n action=\"store_true\",\n help=(\n \"When using plain Python, ignore the PYTHONSTARTUP environme", "suffix": ",\n )\n parser.add_argument(\n \"-i\",\n \"--interface\",\n choices=self.shells,\n help=(\n \"Specify an interactive interpreter interface. Available options: \"\n '\"ipython\", \"bpyth", "middle": "nt \"\n \"variable and ~/.pythonrc.py script.\"\n ),\n )\n parser.add_argument(\n \"--no-imports\",\n action=\"store_true\",\n help=\"Disable automatic imports of models.\"", "meta": {"filepath": "django/core/management/commands/shell.py", "language": "python", "file_size": 9695, "cut_index": 921, "middle_length": 229}} +{"prefix": "m django.db.migrations.recorder import MigrationRecorder\n\n\nclass Command(BaseCommand):\n help = \"Shows all available migrations for the current project\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_label\",\n nargs=\"*\",\n help=\"App labels of applications to limit the output to.\",\n )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n ", "suffix": " \"--list\",\n \"-l\",\n action=\"store_const\",\n dest=\"format\",\n const=\"list\",\n help=(\n \"Shows a list of all migrations and which are applied. \"\n \"With a verbosity level of 2 ", "middle": " \"Nominates a database to show migrations for. Defaults to the \"\n '\"default\" database.'\n ),\n )\n\n formats = parser.add_mutually_exclusive_group()\n formats.add_argument(\n ", "meta": {"filepath": "django/core/management/commands/showmigrations.py", "language": "python", "file_size": 6847, "cut_index": 716, "middle_length": 229}} +{"prefix": "m django.core.management.base import AppCommand\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\n\nclass Command(AppCommand):\n help = (\n \"Prints the SQL statements for resetting sequences for the given app name(s).\"\n )\n\n output_transaction = True\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n 'N", "suffix": " return\n connection = connections[options[\"database\"]]\n models = app_config.get_models(include_auto_created=True)\n statements = connection.ops.sequence_reset_sql(self.style, models)\n if not statements and options[\"verbosi", "middle": "ominates a database to print the SQL for. Defaults to the \"default\" '\n \"database.\"\n ),\n )\n\n def handle_app_config(self, app_config, **options):\n if app_config.models_module is None:\n ", "meta": {"filepath": "django/core/management/commands/sqlsequencereset.py", "language": "python", "file_size": 1101, "cut_index": 515, "middle_length": 229}} +{"prefix": "security.base import SECRET_KEY_INSECURE_PREFIX\nfrom django.core.management.templates import TemplateCommand\nfrom django.core.management.utils import get_random_secret_key\n\n\nclass Command(TemplateCommand):\n help = (\n \"Creates a Django project directory structure for the given project \"\n \"name in the current directory or optionally in the given directory.\"\n )\n missing_args_message = \"You must provide a project name.\"\n\n def handle(self, **options):\n project_name = options.pop(", "suffix": " target = options.pop(\"directory\")\n\n # Create a random SECRET_KEY to put it in the main settings.\n options[\"secret_key\"] = SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()\n\n super().handle(\"project\", project_name, target, **option", "middle": "\"name\")\n ", "meta": {"filepath": "django/core/management/commands/startproject.py", "language": "python", "file_size": 809, "cut_index": 536, "middle_length": 14}} +{"prefix": "ort ProjectState\nfrom django.db.migrations.utils import get_migration_name_timestamp\nfrom django.db.migrations.writer import MigrationWriter\n\n\nclass Command(BaseCommand):\n autodetector = MigrationAutodetector\n help = \"Creates new migration(s) for apps.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"app_label\",\n nargs=\"*\",\n help=\"Specify the app label(s) to create migrations for.\",\n )\n parser.add_argument(", "suffix": "store_true\",\n help=\"Enable fixing of migration conflicts.\",\n )\n parser.add_argument(\n \"--empty\",\n action=\"store_true\",\n help=\"Create an empty migration.\",\n )\n parser.add_argument(\n ", "middle": "\n \"--dry-run\",\n action=\"store_true\",\n help=\"Just show what migrations would be made; don't actually write them.\",\n )\n parser.add_argument(\n \"--merge\",\n action=\"", "meta": {"filepath": "django/core/management/commands/makemigrations.py", "language": "python", "file_size": 22559, "cut_index": 1331, "middle_length": 229}} +{"prefix": "rom django.core.management.base import BaseCommand\nfrom django.core.management.sql import sql_flush\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\n\nclass Command(BaseCommand):\n help = (\n \"Returns a list of the SQL statements required to return all tables in \"\n \"the database to the state they were in just after they were installed.\"\n )\n\n output_transaction = True\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument(\n \"", "suffix": " ),\n )\n\n def handle(self, **options):\n sql_statements = sql_flush(self.style, connections[options[\"database\"]])\n if not sql_statements and options[\"verbosity\"] >= 1:\n self.stderr.write(\"No tables found.\")\n ", "middle": "--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n 'Nominates a database to print the SQL for. Defaults to the \"default\" '\n \"database.\"\n ", "meta": {"filepath": "django/core/management/commands/sqlflush.py", "language": "python", "file_size": 1031, "cut_index": 513, "middle_length": 229}} +{"prefix": "mport MigrationOptimizer\nfrom django.db.migrations.writer import MigrationWriter\n\n\nclass Command(BaseCommand):\n help = (\n \"Squashes an existing set of migrations (from first until specified) into a \"\n \"single new one.\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_label\",\n help=\"App label of the application to squash migrations for.\",\n )\n parser.add_argument(\n \"start_migration_name\",\n nargs=\"?\",\n ", "suffix": "ations will be squashed until and including this migration.\",\n )\n parser.add_argument(\n \"--no-optimize\",\n action=\"store_true\",\n help=\"Do not try to optimize the squashed operations.\",\n )\n parser.", "middle": " help=(\n \"Migrations will be squashed starting from and including this \"\n \"migration.\"\n ),\n )\n parser.add_argument(\n \"migration_name\",\n help=\"Migr", "meta": {"filepath": "django/core/management/commands/squashmigrations.py", "language": "python", "file_size": 10131, "cut_index": 921, "middle_length": 229}} +{"prefix": "ango.db import DEFAULT_DB_ALIAS, connections\nfrom django.db.migrations.loader import AmbiguityError, MigrationLoader\n\n\nclass Command(BaseCommand):\n help = \"Prints the SQL statements for the named migration.\"\n\n output_transaction = True\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_label\", help=\"App label of the application containing the migration.\"\n )\n parser.add_argument(\n \"migration_name\", help=\"Migration name to print the SQL for.\"\n ", "suffix": "he \"default\" '\n \"database.\"\n ),\n )\n parser.add_argument(\n \"--backwards\",\n action=\"store_true\",\n help=\"Creates SQL to unapply the migration, rather than to apply it\",\n )\n\n de", "middle": " )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help=(\n 'Nominates a database to create SQL for. Defaults to t", "meta": {"filepath": "django/core/management/commands/sqlmigrate.py", "language": "python", "file_size": 3310, "cut_index": 614, "middle_length": 229}} +{"prefix": "his package defines set of cache backends that all conform to a simple API.\nIn a nutshell, a cache is a set of values -- which can be any object that\nmay be pickled -- identified by string keys. For the complete API, see\nthe abstract BaseCache class in django.core.cache.backends.base.\n\nClient code should use the `cache` variable defined here to access the default\ncache backend and look up non-default cache backends in the `caches` dict-like\nobject.\n\nSee docs/topics/cache.txt for information on the public AP", "suffix": "ler, ConnectionProxy\nfrom django.utils.module_loading import import_string\n\n__all__ = [\n \"cache\",\n \"caches\",\n \"DEFAULT_CACHE_ALIAS\",\n \"InvalidCacheBackendError\",\n \"CacheKeyWarning\",\n \"BaseCache\",\n \"InvalidCacheKey\",\n]\n\nDEFAULT_CACHE_AL", "middle": "I.\n\"\"\"\n\nfrom django.core import signals\nfrom django.core.cache.backends.base import (\n BaseCache,\n CacheKeyWarning,\n InvalidCacheBackendError,\n InvalidCacheKey,\n)\nfrom django.utils.connection import BaseConnectionHand", "meta": {"filepath": "django/core/cache/__init__.py", "language": "python", "file_size": 1928, "cut_index": 537, "middle_length": 229}} +{"prefix": "is allows cache operations to be controlled by the router\n \"\"\"\n\n def __init__(self, table):\n self.db_table = table\n self.app_label = \"django_cache\"\n self.model_name = \"cacheentry\"\n self.verbose_name = \"cache entry\"\n self.verbose_name_plural = \"cache entries\"\n self.object_name = \"CacheEntry\"\n self.abstract = False\n self.managed = True\n self.proxy = False\n self.swapped = False\n\n\nclass BaseDatabaseCache(BaseCache):\n def __init__(sel", "suffix": " # This class uses cursors provided by the database connection. This means\n # it reads expiration values as aware or naive datetimes, depending on the\n # value of USE_TZ and whether the database supports time zones. The ORM's\n # conversion and ", "middle": "f, table, params):\n super().__init__(params)\n self._table = table\n\n class CacheEntry:\n _meta = Options(table)\n\n self.cache_model_class = CacheEntry\n\n\nclass DatabaseCache(BaseDatabaseCache):\n", "meta": {"filepath": "django/core/cache/backends/db.py", "language": "python", "file_size": 11392, "cut_index": 921, "middle_length": 229}} +{"prefix": "BaseCache\nfrom django.core.files import locks\nfrom django.core.files.move import file_move_safe\nfrom django.utils._os import safe_makedirs\n\n\nclass FileBasedCache(BaseCache):\n cache_suffix = \".djcache\"\n pickle_protocol = pickle.HIGHEST_PROTOCOL\n\n def __init__(self, dir, params):\n super().__init__(params)\n self._dir = os.path.abspath(dir)\n self._createdir()\n\n def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n if self.has_key(key, version):\n re", "suffix": " f:\n if not self._is_expired(f):\n return pickle.loads(zlib.decompress(f.read()))\n except FileNotFoundError:\n pass\n return default\n\n def _write_content(self, file, timeout, value):\n expiry", "middle": "turn False\n self.set(key, value, timeout, version)\n return True\n\n def get(self, key, default=None, version=None):\n fname = self._key_to_file(key, version)\n try:\n with open(fname, \"rb\") as", "meta": {"filepath": "django/core/cache/backends/filebased.py", "language": "python", "file_size": 5797, "cut_index": 716, "middle_length": 229}} +{"prefix": "tional import cached_property\n\n\nclass BaseMemcachedCache(BaseCache):\n def __init__(self, server, params, library, value_not_found_exception):\n super().__init__(params)\n if isinstance(server, str):\n self._servers = re.split(\"[;,]\", server)\n else:\n self._servers = server\n\n # Exception type raised by the underlying client library for a\n # nonexistent key.\n self.LibraryValueNotFoundException = value_not_found_exception\n\n self._lib = libra", "suffix": " Implement transparent thread-safe access to a memcached client.\n \"\"\"\n return self._class(self.client_servers, **self._options)\n\n def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):\n \"\"\"\n Memcached deals with long (> 30 d", "middle": "ry\n self._class = library.Client\n self._options = params.get(\"OPTIONS\") or {}\n\n @property\n def client_servers(self):\n return self._servers\n\n @cached_property\n def _cache(self):\n \"\"\"\n ", "meta": {"filepath": "django/core/cache/backends/memcached.py", "language": "python", "file_size": 6791, "cut_index": 716, "middle_length": 229}} +{"prefix": "jango.core.management.base import BaseCommand\nfrom django.core.management.utils import get_command_line_option\nfrom django.test.runner import get_max_test_processes\nfrom django.test.utils import NullTimeKeeper, TimeKeeper, get_runner\n\n\nclass Command(BaseCommand):\n help = \"Discover and run tests in the specified modules or the current directory.\"\n\n # DiscoverRunner runs the checks after databases are set up.\n requires_system_checks = []\n test_runner = None\n\n def run_from_argv(self, argv):\n ", "suffix": "_line_option(argv, \"--testrunner\")\n super().run_from_argv(argv)\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"test_label\",\n nargs=\"*\",\n help=(\n \"Modul", "middle": " \"\"\"\n Pre-parse the command line to extract the value of the --testrunner\n option. This allows a test runner to define additional command line\n arguments.\n \"\"\"\n self.test_runner = get_command", "meta": {"filepath": "django/core/management/commands/test.py", "language": "python", "file_size": 2367, "cut_index": 563, "middle_length": 229}} +{"prefix": "Dummy cache backend\"\n\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\n\nclass DummyCache(BaseCache):\n def __init__(self, host, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n self.make_and_validate_key(key, version=version)\n return True\n\n def get(self, key, default=None, version=None):\n self.make_and_validate_key(key, version=version)\n return default\n\n def set(self,", "suffix": "on)\n return False\n\n def delete(self, key, version=None):\n self.make_and_validate_key(key, version=version)\n return False\n\n def has_key(self, key, version=None):\n self.make_and_validate_key(key, version=version)\n ret", "middle": " key, value, timeout=DEFAULT_TIMEOUT, version=None):\n self.make_and_validate_key(key, version=version)\n\n def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):\n self.make_and_validate_key(key, version=versi", "meta": {"filepath": "django/core/cache/backends/dummy.py", "language": "python", "file_size": 1043, "cut_index": 513, "middle_length": 229}} +{"prefix": "from django.utils.module_loading import import_string\n\n\nclass RedisSerializer:\n def __init__(self, protocol=None):\n self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol\n\n def dumps(self, obj):\n # For better incr() and decr() atomicity, don't pickle integers.\n # Using type() rather than isinstance() matches only integers and not\n # subclasses like bool.\n if type(obj) is int:\n return obj\n return pickle.dumps(obj, self.protocol)\n\n ", "suffix": "ne,\n pool_class=None,\n parser_class=None,\n **options,\n ):\n import redis\n\n self._lib = redis\n self._servers = servers\n self._pools = {}\n\n self._client = self._lib.Redis\n\n if isinstance(pool_c", "middle": " def loads(self, data):\n try:\n return int(data)\n except ValueError:\n return pickle.loads(data)\n\n\nclass RedisCacheClient:\n def __init__(\n self,\n servers,\n serializer=No", "meta": {"filepath": "django/core/cache/backends/redis.py", "language": "python", "file_size": 8491, "cut_index": 716, "middle_length": 229}} +{"prefix": "json))\n\nTo add your own serializers, use the SERIALIZATION_MODULES setting::\n\n SERIALIZATION_MODULES = {\n \"csv\": \"path.to.csv.serializer\",\n \"txt\": \"path.to.txt.serializer\",\n }\n\n\"\"\"\n\nimport importlib\n\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.core.serializers.base import SerializerDoesNotExist\n\n# Built-in serializers\nBUILTIN_SERIALIZERS = {\n \"xml\": \"django.core.serializers.xml_serializer\",\n \"python\": \"django.core.serializers.python\",\n \"json\": \"djan", "suffix": "ration\n\n This allows the serializer registration to cache serializers and if there\n is an error raised in the process of creating a serializer it will be\n raised and passed along to the caller when the serializer is used.\n \"\"\"\n\n internal_use", "middle": "go.core.serializers.json\",\n \"yaml\": \"django.core.serializers.pyyaml\",\n \"jsonl\": \"django.core.serializers.jsonl\",\n}\n\n_serializers = {}\n\n\nclass BadSerializer:\n \"\"\"\n Stub serializer to hold exception raised during regist", "meta": {"filepath": "django/core/serializers/__init__.py", "language": "python", "file_size": 8785, "cut_index": 716, "middle_length": 229}} +{"prefix": "hat can be reopened in the same\nprocess on any platform. Most platforms use the standard Python\ntempfile.NamedTemporaryFile class, but Windows users are given a custom class.\n\nThis is needed because the Python implementation of NamedTemporaryFile uses the\nO_TEMPORARY flag under Windows, which prevents the file from being reopened\nif the same flag is not provided [1][2]. Note that this does not address the\nmore general issue of opening a file for writing and reading in multiple\nprocesses in a manner that wor", "suffix": "tps://bugs.python.org/issue14243\n\"\"\"\n\nimport os\nimport tempfile\n\nfrom django.core.files.utils import FileProxyMixin\n\n__all__ = (\n \"NamedTemporaryFile\",\n \"gettempdir\",\n)\n\n\nif os.name == \"nt\":\n\n class TemporaryFile(FileProxyMixin):\n \"\"\"\n ", "middle": "ks across platforms.\n\nThe custom version of NamedTemporaryFile doesn't support the same keyword\narguments available in tempfile.NamedTemporaryFile.\n\n1: https://mail.python.org/pipermail/python-list/2005-December/336955.html\n2: ht", "meta": {"filepath": "django/core/files/temp.py", "language": "python", "file_size": 2503, "cut_index": 563, "middle_length": 229}} +{"prefix": "t settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.mail import InvalidMailer\nfrom django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend\n\n\nclass EmailBackend(ConsoleEmailBackend):\n def __init__(self, fail_silently=False, file_path=None, **kwargs):\n self._fname = None\n # Since we're using the console-based backend as a base, force the\n # stream to be None, so we don't default to stdout.\n kwargs[\"stream\"] = None\n supe", "suffix": " self.file_path = file_path\n else:\n self.file_path = getattr(settings, \"EMAIL_FILE_PATH\", None)\n if self.file_path is None:\n raise ImproperlyConfigured(\n \"The EMAIL_FILE_PATH se", "middle": "r().__init__(fail_silently=fail_silently, **kwargs)\n\n # RemovedInDjango70Warning.\n if self.alias is None:\n # Use deprecated settings when MAILERS not enabled.\n if file_path is not None:\n ", "meta": {"filepath": "django/core/mail/backends/filebased.py", "language": "python", "file_size": 3659, "cut_index": 614, "middle_length": 229}} +{"prefix": "inary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of Distance nor the names of its contributors may be\n# used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANT", "suffix": "CIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# C", "middle": "IES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, IN", "meta": {"filepath": "django/contrib/gis/measure.py", "language": "python", "file_size": 12576, "cut_index": 921, "middle_length": 229}} +{"prefix": "from threading import Lock\n\nfrom django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n\n# Global in-memory store of cache data. Keyed by name, to provide\n# multiple named local memory caches.\n_caches = {}\n_expire_info = {}\n_locks = {}\n\n\nclass LocMemCache(BaseCache):\n pickle_protocol = pickle.HIGHEST_PROTOCOL\n\n def __init__(self, name, params):\n super().__init__(params)\n self._cache = _caches.setdefault(name, OrderedDict())\n self._expire_info = _expire_info.setdefault(n", "suffix": "lue, self.pickle_protocol)\n with self._lock:\n if self._has_expired(key):\n self._set(key, pickled, timeout)\n return True\n return False\n\n def get(self, key, default=None, version=None):\n ke", "middle": "ame, {})\n self._lock = _locks.setdefault(name, Lock())\n\n def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):\n key = self.make_and_validate_key(key, version=version)\n pickled = pickle.dumps(va", "meta": {"filepath": "django/core/cache/backends/locmem.py", "language": "python", "file_size": 4036, "cut_index": 614, "middle_length": 229}} +{"prefix": "LAG_HASNODATA,\n BANDTYPE_PIXTYPE_MASK,\n GDAL_TO_POSTGIS,\n GDAL_TO_STRUCT,\n POSTGIS_HEADER_STRUCTURE,\n POSTGIS_TO_GDAL,\n STRUCT_SIZE,\n)\n\n\ndef pack(structure, data):\n \"\"\"\n Pack data into hex string with little endian format.\n \"\"\"\n return struct.pack(\"<\" + structure, *data)\n\n\ndef unpack(structure, data):\n \"\"\"\n Unpack little endian hexlified binary string into a list.\n \"\"\"\n return struct.unpack(\"<\" + structure, bytes.fromhex(data))\n\n\ndef chunk(data, index):\n \"\"\"\n ", "suffix": " # Split raster header from data\n header, data = chunk(data, 122)\n header = unpack(POSTGIS_HEADER_STRUCTURE, header)\n\n # Parse band data\n bands = []\n pixeltypes = []\n while data:\n # Get pixel type for this band\n pixeltype_", "middle": "Split a string into two parts at the input index.\n \"\"\"\n return data[:index], data[index:]\n\n\ndef from_pgraster(data):\n \"\"\"\n Convert a PostGIS HEX String into a dictionary.\n \"\"\"\n if data is None:\n return\n\n ", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/pgraster.py", "language": "python", "file_size": 4588, "cut_index": 614, "middle_length": 229}} +{"prefix": "ss-origin\",\n \"same-origin\",\n \"strict-origin\",\n \"strict-origin-when-cross-origin\",\n \"unsafe-url\",\n}\n\nSECRET_KEY_INSECURE_PREFIX = \"django-insecure-\"\nSECRET_KEY_MIN_LENGTH = 50\nSECRET_KEY_MIN_UNIQUE_CHARACTERS = 5\n\nSECRET_KEY_WARNING_MSG = (\n f\"Your %s has less than {SECRET_KEY_MIN_LENGTH} characters, less than \"\n f\"{SECRET_KEY_MIN_UNIQUE_CHARACTERS} unique characters, or it's prefixed \"\n f\"with '{SECRET_KEY_INSECURE_PREFIX}' indicating that it was generated \"\n f\"automatically by Djang", "suffix": "re' \"\n \"in your MIDDLEWARE so the SECURE_HSTS_SECONDS, \"\n \"SECURE_CONTENT_TYPE_NOSNIFF, SECURE_REFERRER_POLICY, \"\n \"SECURE_CROSS_ORIGIN_OPENER_POLICY, and SECURE_SSL_REDIRECT settings will \"\n \"have no effect.\",\n id=\"security.W001\",\n)\n\nW002 =", "middle": "o. Please generate a long and random value, \"\n f\"otherwise many of Django's security-critical features will be \"\n f\"vulnerable to attack.\"\n)\n\nW001 = Warning(\n \"You do not have 'django.middleware.security.SecurityMiddlewa", "meta": {"filepath": "django/core/checks/security/base.py", "language": "python", "file_size": 11550, "cut_index": 921, "middle_length": 229}} +{"prefix": "messages import (\n CRITICAL,\n DEBUG,\n ERROR,\n INFO,\n WARNING,\n CheckMessage,\n Critical,\n Debug,\n Error,\n Info,\n Warning,\n)\nfrom .registry import Tags, register, run_checks, tag_exists\n\n# Import these to force registration of checks\nimport django.core.checks.async_checks # NOQA isort:skip\nimport django.core.checks.caches # NOQA isort:skip\nimport django.core.checks.commands # NOQA isort:skip\nimport django.core.checks.compatibility.django_4_0 # NOQA isort:skip\nimport django", "suffix": "hecks.security.csrf # NOQA isort:skip\nimport django.core.checks.security.sessions # NOQA isort:skip\nimport django.core.checks.templates # NOQA isort:skip\nimport django.core.checks.translation # NOQA isort:skip\nimport django.core.checks.urls # NOQA iso", "middle": ".core.checks.database # NOQA isort:skip\nimport django.core.checks.files # NOQA isort:skip\nimport django.core.checks.model_checks # NOQA isort:skip\nimport django.core.checks.security.base # NOQA isort:skip\nimport django.core.c", "meta": {"filepath": "django/core/checks/__init__.py", "language": "python", "file_size": 1248, "cut_index": 518, "middle_length": 229}} +{"prefix": "om django.core.cache import DEFAULT_CACHE_ALIAS, caches\nfrom django.core.cache.backends.filebased import FileBasedCache\n\nfrom . import Error, Tags, Warning, register\n\nE001 = Error(\n \"You must define a '%s' cache in your CACHES setting.\" % DEFAULT_CACHE_ALIAS,\n id=\"caches.E001\",\n)\n\n\n@register(Tags.caches)\ndef check_default_cache_is_configured(app_configs, **kwargs):\n if DEFAULT_CACHE_ALIAS not in settings.CACHES:\n return [E001]\n return []\n\n\n@register(Tags.caches, deploy=True)\ndef check_cac", "suffix": " if name == \"STATICFILES_DIRS\":\n paths = set()\n for staticfiles_dir in setting:\n if isinstance(staticfiles_dir, (list, tuple)):\n _, staticfiles_dir = staticfiles_dir\n paths.add(pathli", "middle": "he_location_not_exposed(app_configs, **kwargs):\n errors = []\n for name in (\"MEDIA_ROOT\", \"STATIC_ROOT\", \"STATICFILES_DIRS\"):\n setting = getattr(settings, name, None)\n if not setting:\n continue\n ", "meta": {"filepath": "django/core/checks/caches.py", "language": "python", "file_size": 2643, "cut_index": 563, "middle_length": 229}} +{"prefix": "ng, register\n\n\n@register(Tags.models)\ndef check_all_models(app_configs, **kwargs):\n db_table_models = defaultdict(list)\n indexes = defaultdict(list)\n constraints = defaultdict(list)\n errors = []\n if app_configs is None:\n models = apps.get_models()\n else:\n models = chain.from_iterable(\n app_config.get_models() for app_config in app_configs\n )\n for model in models:\n if model._meta.managed and not model._meta.proxy:\n db_table_models[model._", "suffix": " % (model.__name__, model.check),\n obj=model,\n id=\"models.E020\",\n )\n )\n else:\n errors.extend(model.check(**kwargs))\n for model_index in model._meta.indexes:\n", "middle": "meta.db_table].append(model._meta.label)\n if not inspect.ismethod(model.check):\n errors.append(\n Error(\n \"The '%s.check()' class method is currently overridden by %r.\"\n ", "meta": {"filepath": "django/core/checks/model_checks.py", "language": "python", "file_size": 8820, "cut_index": 716, "middle_length": 229}} +{"prefix": "ettings\nfrom django.utils.translation import get_supported_language_variant\nfrom django.utils.translation.trans_real import language_code_re\n\nfrom . import Error, Tags, register\n\nE001 = Error(\n \"You have provided an invalid value for the LANGUAGE_CODE setting: {!r}.\",\n id=\"translation.E001\",\n)\n\nE002 = Error(\n \"You have provided an invalid language code in the LANGUAGES setting: {!r}.\",\n id=\"translation.E002\",\n)\n\nE003 = Error(\n \"You have provided an invalid language code in the LANGUAGES_BIDI ", "suffix": "ef check_setting_language_code(app_configs, **kwargs):\n \"\"\"Error if LANGUAGE_CODE setting is invalid.\"\"\"\n tag = settings.LANGUAGE_CODE\n if not isinstance(tag, str) or not language_code_re.match(tag):\n return [Error(E001.msg.format(tag), id=", "middle": "setting: {!r}.\",\n id=\"translation.E003\",\n)\n\nE004 = Error(\n \"You have provided a value for the LANGUAGE_CODE setting that is not in \"\n \"the LANGUAGES setting.\",\n id=\"translation.E004\",\n)\n\n\n@register(Tags.translation)\nd", "meta": {"filepath": "django/core/checks/translation.py", "language": "python", "file_size": 1990, "cut_index": 537, "middle_length": 229}} +{"prefix": "iewDoesNotExist\nfrom django.utils.inspect import signature\n\nfrom . import Error, Tags, Warning, register\n\n\n@register(Tags.urls)\ndef check_url_config(app_configs, **kwargs):\n if getattr(settings, \"ROOT_URLCONF\", None):\n from django.urls import get_resolver\n\n resolver = get_resolver()\n return check_resolver(resolver)\n return []\n\n\ndef check_resolver(resolver):\n \"\"\"\n Recursively check the resolver.\n \"\"\"\n check_method = getattr(resolver, \"check\", None)\n if check_method i", "suffix": "configs, **kwargs):\n \"\"\"\n Warn if URL namespaces used in applications aren't unique.\n \"\"\"\n if not getattr(settings, \"ROOT_URLCONF\", None):\n return []\n\n from django.urls import get_resolver\n\n resolver = get_resolver()\n all_namesp", "middle": "s not None:\n return check_method()\n elif not hasattr(resolver, \"resolve\"):\n return get_warning_for_invalid_pattern(resolver)\n else:\n return []\n\n\n@register(Tags.urls)\ndef check_url_namespaces_unique(app_", "meta": {"filepath": "django/core/checks/urls.py", "language": "python", "file_size": 4906, "cut_index": 614, "middle_length": 229}} +{"prefix": " pass\n\n\n# Stub class to ensure not passing in a `timeout` argument results in\n# the default timeout\nDEFAULT_TIMEOUT = object()\n\n# Memcached does not accept keys longer than this.\nMEMCACHE_MAX_KEY_LENGTH = 250\n\n\ndef default_key_func(key, key_prefix, version):\n \"\"\"\n Default function to generate keys.\n\n Construct the key used by all other methods. By default, prepend\n the `key_prefix`. KEY_FUNCTION can be used to specify an alternate\n function with custom key making behavior.\n \"\"\"\n return", "suffix": "unc):\n return key_func\n else:\n return import_string(key_func)\n return default_key_func\n\n\nclass BaseCache:\n _missing_key = object()\n\n def __init__(self, params):\n timeout = params.get(\"timeout\", params.get(\"TIMEO", "middle": " \"%s:%s:%s\" % (key_prefix, version, key)\n\n\ndef get_key_func(key_func):\n \"\"\"\n Function to decide which key function to use.\n\n Default to ``default_key_func``.\n \"\"\"\n if key_func is not None:\n if callable(key_f", "meta": {"filepath": "django/core/cache/backends/base.py", "language": "python", "file_size": 15772, "cut_index": 921, "middle_length": 229}} +{"prefix": "40\nCRITICAL = 50\n\n\nclass CheckMessage:\n def __init__(self, level, msg, hint=None, obj=None, id=None):\n if not isinstance(level, int):\n raise TypeError(\"The first argument should be level.\")\n self.level = level\n self.msg = msg\n self.hint = hint\n self.obj = obj\n self.id = id\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and all(\n getattr(self, attr) == getattr(other, attr)\n for attr in [\"level\", \"msg", "suffix": " hardcode ModelBase and Field cases because its __str__\n # method doesn't return \"applabel.modellabel\" and cannot be\n # changed.\n obj = self.obj._meta.label\n else:\n obj = str(self.obj)\n id = \"(%s) \"", "middle": "\", \"hint\", \"obj\", \"id\"]\n )\n\n def __str__(self):\n from django.db import models\n\n if self.obj is None:\n obj = \"?\"\n elif isinstance(self.obj, models.base.ModelBase):\n # We need to", "meta": {"filepath": "django/core/checks/messages.py", "language": "python", "file_size": 2255, "cut_index": 563, "middle_length": 229}} +{"prefix": "hecks import Error, Tags, Warning, register\nfrom django.utils.inspect import signature\n\nW003 = Warning(\n \"You don't appear to be using Django's built-in \"\n \"cross-site request forgery protection via the middleware \"\n \"('django.middleware.csrf.CsrfViewMiddleware' is not in your \"\n \"MIDDLEWARE). Enabling the middleware is the safest approach \"\n \"to ensure you don't leave any holes.\",\n id=\"security.W003\",\n)\n\nW016 = Warning(\n \"You have 'django.middleware.csrf.CsrfViewMiddleware' in your \"\n ", "suffix": "middleware():\n return \"django.middleware.csrf.CsrfViewMiddleware\" in settings.MIDDLEWARE\n\n\n@register(Tags.security, deploy=True)\ndef check_csrf_middleware(app_configs, **kwargs):\n passed_check = _csrf_middleware()\n return [] if passed_check else [", "middle": " \"MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. \"\n \"Using a secure-only CSRF cookie makes it more difficult for network \"\n \"traffic sniffers to steal the CSRF token.\",\n id=\"security.W016\",\n)\n\n\ndef _csrf_", "meta": {"filepath": "django/core/checks/security/csrf.py", "language": "python", "file_size": 2089, "cut_index": 563, "middle_length": 229}} +{"prefix": "om django.utils.inspect import func_accepts_kwargs\n\n\nclass Tags:\n \"\"\"\n Built-in tags for internal checks.\n \"\"\"\n\n admin = \"admin\"\n async_support = \"async_support\"\n caches = \"caches\"\n commands = \"commands\"\n compatibility = \"compatibility\"\n database = \"database\"\n files = \"files\"\n models = \"models\"\n security = \"security\"\n signals = \"signals\"\n sites = \"sites\"\n staticfiles = \"staticfiles\"\n templates = \"templates\"\n translation = \"translation\"\n urls = \"urls\"\n\n\nc", "suffix": "corator. Register given function\n `f` labeled with given `tags`. The function should receive **kwargs\n and return list of Errors and Warnings.\n\n Example::\n\n registry = CheckRegistry()\n @registry.register('mytag', ", "middle": "lass CheckRegistry:\n def __init__(self):\n self.registered_checks = set()\n self.deployment_checks = set()\n\n def register(self, check=None, *tags, **kwargs):\n \"\"\"\n Can be used as a function or a de", "meta": {"filepath": "django/core/checks/registry.py", "language": "python", "file_size": 3880, "cut_index": 614, "middle_length": 229}} +{"prefix": "commands)\ndef migrate_and_makemigrations_autodetector(**kwargs):\n from django.core.management import get_commands, load_command_class\n\n commands = get_commands()\n\n make_migrations = load_command_class(commands[\"makemigrations\"], \"makemigrations\")\n migrate = load_command_class(commands[\"migrate\"], \"migrate\")\n\n if make_migrations.autodetector is not migrate.autodetector:\n return [\n Error(\n \"The migrate and makemigrations commands must have the same \"\n ", "suffix": " f\"makemigrations.Command.autodetector is \"\n f\"{make_migrations.autodetector.__name__}, but \"\n f\"migrate.Command.autodetector is \"\n f\"{migrate.autodetector.__name__}.\"\n ),\n", "middle": " \"autodetector.\",\n hint=(\n ", "meta": {"filepath": "django/core/checks/commands.py", "language": "python", "file_size": 965, "cut_index": 582, "middle_length": 52}} +{"prefix": "go.core.serializers.base import DeserializationError\nfrom django.core.serializers.python import Deserializer as PythonDeserializer\nfrom django.core.serializers.python import Serializer as PythonSerializer\nfrom django.utils.duration import duration_iso_string\nfrom django.utils.functional import Promise\nfrom django.utils.timezone import is_aware\n\n\nclass Serializer(PythonSerializer):\n \"\"\"Convert a queryset to JSON.\"\"\"\n\n internal_use_only = False\n\n def _init_options(self):\n self._current = None\n", "suffix": "f.json_kwargs[\"separators\"] = (\",\", \": \")\n self.json_kwargs.setdefault(\"cls\", DjangoJSONEncoder)\n self.json_kwargs.setdefault(\"ensure_ascii\", False)\n\n def start_serialization(self):\n self._init_options()\n self.stream.write(\"[", "middle": " self.json_kwargs = self.options.copy()\n self.json_kwargs.pop(\"stream\", None)\n self.json_kwargs.pop(\"fields\", None)\n if self.options.get(\"indent\"):\n # Prevent trailing spaces\n sel", "meta": {"filepath": "django/core/serializers/json.py", "language": "python", "file_size": 3714, "cut_index": 614, "middle_length": 229}} +{"prefix": "apps import apps\nfrom django.core.serializers import base\nfrom django.db import DEFAULT_DB_ALIAS, models\nfrom django.db.models import CompositePrimaryKey\nfrom django.utils.encoding import is_protected_type\n\n\nclass Serializer(base.Serializer):\n \"\"\"\n Serialize a QuerySet to basic Python objects.\n \"\"\"\n\n internal_use_only = True\n\n def start_serialization(self):\n self._current = None\n self.objects = []\n\n def end_serialization(self):\n pass\n\n def start_object(self, obj):\n ", "suffix": "f not self.use_natural_primary_keys or not self._resolve_natural_key(obj):\n data[\"pk\"] = self._value_from_field(obj, obj._meta.pk)\n data[\"fields\"] = self._current\n return data\n\n def _value_from_field(self, obj, field):\n i", "middle": " self._current = {}\n\n def end_object(self, obj):\n self.objects.append(self.get_dump_object(obj))\n self._current = None\n\n def get_dump_object(self, obj):\n data = {\"model\": str(obj._meta)}\n i", "meta": {"filepath": "django/core/serializers/python.py", "language": "python", "file_size": 8902, "cut_index": 716, "middle_length": 229}} +{"prefix": "en the XML document and the root element.\n \"\"\"\n # Increment the indent_level before each startElement() and decrement\n # it following each endElement(). If the closing tag should appear on\n # its own line, use self.indent(self.indent_level) before endElement().\n self.indent_level = 0\n self.xml = SimplerXMLGenerator(\n self.stream, self.options.get(\"encoding\", settings.DEFAULT_CHARSET)\n )\n self.xml.startDocument()\n self.xml.startElement", "suffix": " self.xml.endDocument()\n\n def start_object(self, obj):\n \"\"\"\n Called as each object is handled.\n \"\"\"\n if not hasattr(obj, \"_meta\"):\n raise base.SerializationError(\n \"Non-model object (%s) encou", "middle": "(\"django-objects\", {\"version\": \"1.0\"})\n\n def end_serialization(self):\n \"\"\"\n End serialization -- end the document.\n \"\"\"\n self.indent(self.indent_level)\n self.xml.endElement(\"django-objects\")\n", "meta": {"filepath": "django/core/serializers/xml_serializer.py", "language": "python", "file_size": 21893, "cut_index": 1331, "middle_length": 229}} +{"prefix": "s Pillow as you might imagine.\n\"\"\"\n\nimport struct\nimport zlib\n\nfrom django.core.files import File\n\n\nclass ImageFile(File):\n \"\"\"\n A mixin for use alongside django.core.files.base.File, which provides\n additional features for dealing with images.\n \"\"\"\n\n @property\n def width(self):\n return self._get_image_dimensions()[0]\n\n @property\n def height(self):\n return self._get_image_dimensions()[1]\n\n def _get_image_dimensions(self):\n if not hasattr(self, \"_dimensions_cac", "suffix": "):\n \"\"\"\n Return the (width, height) of an image, given an open file or a path. Set\n 'close' to True to close the file at the end if it is initially in an open\n state.\n \"\"\"\n from PIL import ImageFile as PillowImageFile\n\n p = PillowImage", "middle": "he\"):\n close = self.closed\n self.open()\n self._dimensions_cache = get_image_dimensions(self, close=close)\n return self._dimensions_cache\n\n\ndef get_image_dimensions(file_or_path, close=False", "meta": {"filepath": "django/core/files/images.py", "language": "python", "file_size": 2643, "cut_index": 563, "middle_length": 229}} +{"prefix": "n\nCookbook [1] (licensed under the Python Software License) and a ctypes port by\nAnatoly Techtonik for Roundup [2] (license [3]).\n\n[1] https://code.activestate.com/recipes/65203/\n[2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py # NOQA\n[3] https://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt\n\nExample Usage::\n\n >>> from django.core.files import locks\n >>> with open('./file', 'wb') as f:\n ... locks.lock(f, locks.LOCK_EX)\n ... f.write(", "suffix": "e f\n\n\nif os.name == \"nt\":\n import msvcrt\n from ctypes import (\n POINTER,\n Structure,\n Union,\n WinDLL,\n byref,\n c_int64,\n c_ulong,\n c_void_p,\n sizeof,\n )\n from ctypes.wintypes import", "middle": "'Django')\n\"\"\"\n\nimport os\n\n__all__ = (\"LOCK_EX\", \"LOCK_SH\", \"LOCK_NB\", \"lock\", \"unlock\")\n\n\ndef _fd(f):\n \"\"\"Get a filedescriptor from something which could be a file or an fd.\"\"\"\n return f.fileno() if hasattr(f, \"fileno\") els", "meta": {"filepath": "django/core/files/locks.py", "language": "python", "file_size": 3614, "cut_index": 614, "middle_length": 229}} +{"prefix": "hecks import Tags, Warning, register\n\n\ndef add_session_cookie_message(message):\n return message + (\n \" Using a secure-only session cookie makes it more difficult for \"\n \"network traffic sniffers to hijack user sessions.\"\n )\n\n\nW010 = Warning(\n add_session_cookie_message(\n \"You have 'django.contrib.sessions' in your INSTALLED_APPS, \"\n \"but you have not set SESSION_COOKIE_SECURE to True.\"\n ),\n id=\"security.W010\",\n)\n\nW011 = Warning(\n add_session_cookie_message(\n ", "suffix": "_cookie_message(\"SESSION_COOKIE_SECURE is not set to True.\"),\n id=\"security.W012\",\n)\n\n\ndef add_httponly_message(message):\n return message + (\n \" Using an HttpOnly session cookie makes it more difficult for \"\n \"cross-site scripting attac", "middle": " \"You have 'django.contrib.sessions.middleware.SessionMiddleware' \"\n \"in your MIDDLEWARE, but you have not set \"\n \"SESSION_COOKIE_SECURE to True.\"\n ),\n id=\"security.W011\",\n)\n\nW012 = Warning(\n add_session", "meta": {"filepath": "django/core/checks/security/sessions.py", "language": "python", "file_size": 2569, "cut_index": 563, "middle_length": 229}} +{"prefix": "ass DeserializationError(Exception):\n \"\"\"Something bad happened during deserialization.\"\"\"\n\n @classmethod\n def WithData(cls, original_exc, model, fk, field_value):\n \"\"\"\n Factory method for creating a deserialization error which has a more\n explanatory message.\n \"\"\"\n return cls(\n \"%s: (%s:pk=%s) field_value was '%s'\"\n % (original_exc, model, fk, field_value)\n )\n\n\nclass M2MDeserializationError(Exception):\n \"\"\"Something bad happened du", "suffix": "otal_count):\n self.output = output\n self.total_count = total_count\n self.prev_done = 0\n\n def update(self, count):\n if not self.output:\n return\n perc = count * 100 // self.total_count\n done = perc * se", "middle": "ring deserialization of a ManyToManyField.\"\"\"\n\n def __init__(self, original_exc, pk):\n self.original_exc = original_exc\n self.pk = pk\n\n\nclass ProgressBar:\n progress_width = 75\n\n def __init__(self, output, t", "meta": {"filepath": "django/core/serializers/base.py", "language": "python", "file_size": 13573, "cut_index": 921, "middle_length": 229}} +{"prefix": "FileProxyMixin\nfrom django.utils.functional import cached_property\n\n\nclass File(FileProxyMixin):\n DEFAULT_CHUNK_SIZE = 64 * 2**10\n\n def __init__(self, file, name=None):\n self.file = file\n if name is None:\n name = getattr(file, \"name\", None)\n self.name = name\n if hasattr(file, \"mode\"):\n self.mode = file.mode\n\n def __str__(self):\n return self.name or \"\"\n\n def __repr__(self):\n return \"<%s: %s>\" % (self.__class__.__name__, self.name or ", "suffix": "asattr(self.file, \"name\"):\n try:\n return os.path.getsize(self.file.name)\n except (OSError, TypeError):\n pass\n if hasattr(self.file, \"tell\") and hasattr(self.file, \"seek\"):\n pos = self.fi", "middle": "\"None\")\n\n def __bool__(self):\n return True\n\n def __len__(self):\n return self.size\n\n @cached_property\n def size(self):\n if hasattr(self.file, \"size\"):\n return self.file.size\n if h", "meta": {"filepath": "django/core/files/base.py", "language": "python", "file_size": 4976, "cut_index": 614, "middle_length": 229}} +{"prefix": ">> from django.core.files.move import file_move_safe\n >>> file_move_safe(\"/tmp/old_file\", \"/tmp/new_file\")\n\"\"\"\n\nimport os\nfrom shutil import copymode, copystat\n\nfrom django.core.files import locks\n\n__all__ = [\"file_move_safe\"]\n\n\ndef file_move_safe(\n old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False\n):\n \"\"\"\n Move a file from one location to another in the safest way possible.\n\n First, try ``os.rename``, which is simple but will break across\n filesystems. If that fail", "suffix": "\n try:\n if os.path.samefile(old_file_name, new_file_name):\n return\n except OSError:\n pass\n\n if not allow_overwrite and os.access(new_file_name, os.F_OK):\n raise FileExistsError(\n f\"Destination file {new_f", "middle": "s, stream manually from one file to another in\n pure Python.\n\n If the destination file exists and ``allow_overwrite`` is ``False``, raise\n ``FileExistsError``.\n \"\"\"\n # There's no reason to move if we don't have to.", "meta": {"filepath": "django/core/files/move.py", "language": "python", "file_size": 2951, "cut_index": 563, "middle_length": 229}} +{"prefix": "son\n\nfrom django.core.serializers.base import DeserializationError\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.core.serializers.python import Deserializer as PythonDeserializer\nfrom django.core.serializers.python import Serializer as PythonSerializer\n\n\nclass Serializer(PythonSerializer):\n \"\"\"Convert a queryset to JSON Lines.\"\"\"\n\n internal_use_only = False\n\n def _init_options(self):\n self._current = None\n self.json_kwargs = self.options.copy()\n self.js", "suffix": "oder)\n self.json_kwargs.setdefault(\"ensure_ascii\", False)\n\n def start_serialization(self):\n self._init_options()\n\n def end_object(self, obj):\n # self._current has the field data\n json.dump(self.get_dump_object(obj), self.s", "middle": "on_kwargs.pop(\"stream\", None)\n self.json_kwargs.pop(\"fields\", None)\n self.json_kwargs.pop(\"indent\", None)\n self.json_kwargs[\"separators\"] = (\",\", \": \")\n self.json_kwargs.setdefault(\"cls\", DjangoJSONEnc", "meta": {"filepath": "django/core/serializers/jsonl.py", "language": "python", "file_size": 2258, "cut_index": 563, "middle_length": 229}} +{"prefix": "ml.org/), but that's checked for in __init__.\n\"\"\"\n\nimport datetime\nimport decimal\n\nimport yaml\n\nfrom django.core.serializers.base import DeserializationError\nfrom django.core.serializers.python import Deserializer as PythonDeserializer\nfrom django.core.serializers.python import Serializer as PythonSerializer\n\n# Use the C (faster) implementation if possible\ntry:\n from yaml import CSafeDumper as SafeDumper\n from yaml import CSafeLoader as SafeLoader\nexcept ImportError:\n from yaml import SafeDumper, S", "suffix": " def represent_time(self, data):\n # Base YAML doesn't support serialization of time types (as opposed to\n # dates or datetimes, which it does support). Converting them to\n # strings isn't perfect, but it's better than a \"!!python/time", "middle": "afeLoader\n\n\nclass DjangoSafeDumper(SafeDumper):\n # The \"safe\" serializer is used for better interoperability.\n\n def represent_decimal(self, data):\n return self.represent_scalar(\"tag:yaml.org,2002:str\", str(data))\n\n ", "meta": {"filepath": "django/core/serializers/pyyaml.py", "language": "python", "file_size": 2619, "cut_index": 563, "middle_length": 229}} +{"prefix": " import InMemoryUploadedFile, TemporaryUploadedFile\nfrom django.utils.module_loading import import_string\n\n__all__ = [\n \"UploadFileException\",\n \"StopUpload\",\n \"SkipFile\",\n \"FileUploadHandler\",\n \"TemporaryFileUploadHandler\",\n \"MemoryFileUploadHandler\",\n \"load_handler\",\n \"StopFutureHandlers\",\n]\n\n\nclass UploadFileException(Exception):\n \"\"\"\n Any error having to do with uploading files.\n \"\"\"\n\n pass\n\n\nclass StopUpload(UploadFileException):\n \"\"\"\n This exception is raised w", "suffix": "will cause the browser\n to show a \"connection reset\" error.\n \"\"\"\n self.connection_reset = connection_reset\n\n def __str__(self):\n if self.connection_reset:\n return \"StopUpload: Halt current upload.\"\n else:\n ", "middle": "hen an upload must abort.\n \"\"\"\n\n def __init__(self, connection_reset=False):\n \"\"\"\n If ``connection_reset`` is ``True``, Django knows will halt the upload\n without consuming the rest of the upload. This ", "meta": {"filepath": "django/core/files/uploadhandler.py", "language": "python", "file_size": 7813, "cut_index": 716, "middle_length": 229}} +{"prefix": "rt get_random_string\nfrom django.utils.text import get_valid_filename\n\n\nclass Storage:\n \"\"\"\n A base storage class, providing some default behaviors that all other\n storage systems can inherit or override, as necessary.\n \"\"\"\n\n # The following methods represent a public interface to private methods.\n # These shouldn't be overridden by subclasses unless absolutely necessary.\n\n def open(self, name, mode=\"rb\"):\n \"\"\"Retrieve the specified file from storage.\"\"\"\n return self._open", "suffix": "read\n from the beginning.\n \"\"\"\n # Get the proper name for the file, as it will actually be saved.\n if name is None:\n name = content.name\n\n if not hasattr(content, \"chunks\"):\n content = File(content, ", "middle": "(name, mode)\n\n def save(self, name, content, max_length=None):\n \"\"\"\n Save new content to the file specified by name. The content should be\n a proper File object or any Python file-like object, ready to be ", "meta": {"filepath": "django/core/files/storage/base.py", "language": "python", "file_size": 8297, "cut_index": 716, "middle_length": 229}} +{"prefix": "conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.functional import cached_property\nfrom django.utils.module_loading import import_string\n\n\nclass InvalidStorageError(ImproperlyConfigured):\n pass\n\n\nclass StorageHandler:\n def __init__(self, backends=None):\n # backends is an optional dict of storage backend definitions\n # (structured like settings.STORAGES).\n self._backends = backends\n self._storages = {}\n\n @cached_property\n d", "suffix": " except KeyError:\n try:\n params = self.backends[alias]\n except KeyError:\n raise InvalidStorageError(\n f\"Could not find config for '{alias}' in settings.STORAGES.\"\n )", "middle": "ef backends(self):\n if self._backends is None:\n self._backends = settings.STORAGES.copy()\n return self._backends\n\n def __getitem__(self, alias):\n try:\n return self._storages[alias]\n ", "meta": {"filepath": "django/core/files/storage/handler.py", "language": "python", "file_size": 1507, "cut_index": 524, "middle_length": 229}} +{"prefix": "ore/mail.py before the introduction of email\n# backends and the subsequent reorganization (See #10355)\nfrom django.core.mail.message import (\n DEFAULT_ATTACHMENT_MIME_TYPE,\n EmailAlternative,\n EmailAttachment,\n EmailMessage,\n EmailMultiAlternatives,\n forbid_multi_line_headers,\n make_msgid,\n)\nfrom django.core.mail.utils import DNS_NAME, CachedDnsName\nfrom django.utils.deprecation import (\n RemovedInDjango70Warning,\n deprecate_posargs,\n warn_about_external_use,\n)\nfrom django.util", "suffix": " warn_about_default_mailers_if_needed,\n)\n\n__all__ = [\n \"InvalidMailer\",\n \"MailerDoesNotExist\",\n \"CachedDnsName\",\n \"DNS_NAME\",\n \"EmailMessage\",\n \"EmailMultiAlternatives\",\n \"DEFAULT_ATTACHMENT_MIME_TYPE\",\n \"make_msgid\",\n \"mailers\",", "middle": "s.functional import Promise\nfrom django.utils.module_loading import import_string\n\nfrom .deprecation import (\n AUTH_ARGS_WARNING,\n CONNECTION_ARG_WARNING,\n FAIL_SILENTLY_ARG_WARNING,\n report_using_incompatibility,\n ", "meta": {"filepath": "django/core/mail/__init__.py", "language": "python", "file_size": 12405, "cut_index": 921, "middle_length": 229}} +{"prefix": "ail import InvalidMailer, MailerDoesNotExist\nfrom django.utils.module_loading import import_string\n\nDEFAULT_MAILER_ALIAS = \"default\"\n\n# Default value for a MAILERS \"BACKEND\". (Not related to the default mailer.)\nDEFAULT_MAILER_BACKEND = \"django.core.mail.backends.smtp.EmailBackend\"\n\n\nclass MailersHandler:\n def __getitem__(self, /, alias):\n return self.create_connection(alias)\n\n def __contains__(self, /, alias):\n return alias in self.settings\n\n def __iter__(self):\n return iter(s", "suffix": "_MAILER_ALIAS]\n\n @property\n def settings(self):\n # RemovedInDjango70Warning: change to:\n # return settings.MAILERS\n return getattr(settings, \"MAILERS\", {})\n\n # RemovedInDjango70Warning.\n @property\n def _is_configured(s", "middle": "elf.settings)\n\n def get(self, alias, /, default=None):\n try:\n return self[alias]\n except MailerDoesNotExist:\n return default\n\n @property\n def default(self):\n return self[DEFAULT", "meta": {"filepath": "django/core/mail/handler.py", "language": "python", "file_size": 2727, "cut_index": 563, "middle_length": 229}} +{"prefix": "ion import RemovedInDjango70Warning, warn_about_external_use\n\n# RemovedInDjango70Warning.\n_NOT_PROVIDED = object()\n\n\nclass BaseEmailBackend:\n \"\"\"\n Base class for email backend implementations.\n\n Subclasses must implement at least send_messages().\n\n Subclass __init__() should pass alias and unknown **kwargs to\n super().__init__() for proper error reporting.\n\n open() and close() can be called indirectly by using a backend object as a\n context manager:\n\n with backend as connection:\n ", "suffix": "s=None,\n _ignore_unknown_kwargs=None,\n **kwargs,\n ):\n self.alias = alias\n\n # RemovedInDjango70Warning.\n if fail_silently is _NOT_PROVIDED:\n self._fail_silently = False\n else:\n self._fail_si", "middle": " # do something with connection\n pass\n \"\"\"\n\n # RemovedInDjango70Warning: fail_silently, _ignore_unknown_kwargs.\n def __init__(\n self,\n fail_silently=_NOT_PROVIDED,\n *,\n alia", "meta": {"filepath": "django/core/mail/backends/base.py", "language": "python", "file_size": 4262, "cut_index": 614, "middle_length": 229}} +{"prefix": "t settings\nfrom django.core.files import temp as tempfile\nfrom django.core.files.base import File\nfrom django.core.files.utils import validate_file_name\n\n__all__ = (\n \"UploadedFile\",\n \"TemporaryUploadedFile\",\n \"InMemoryUploadedFile\",\n \"SimpleUploadedFile\",\n)\n\n\nclass UploadedFile(File):\n \"\"\"\n An abstract uploaded file (``TemporaryUploadedFile`` and\n ``InMemoryUploadedFile`` are the built-in concrete subclasses).\n\n An ``UploadedFile`` object behaves somewhat like a file object and\n ", "suffix": "e_extra=None,\n ):\n super().__init__(file, name)\n self.size = size\n self.content_type = content_type\n self.charset = charset\n self.content_type_extra = content_type_extra\n\n def __repr__(self):\n return \"<%s: %s", "middle": "represents some file data that the user submitted with a form.\n \"\"\"\n\n def __init__(\n self,\n file=None,\n name=None,\n content_type=None,\n size=None,\n charset=None,\n content_typ", "meta": {"filepath": "django/core/files/uploadedfile.py", "language": "python", "file_size": 4263, "cut_index": 614, "middle_length": 229}} +{"prefix": "from django.core.signals import setting_changed\nfrom django.utils._os import safe_join, safe_makedirs\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.encoding import filepath_to_uri\nfrom django.utils.functional import cached_property\n\nfrom .base import Storage\nfrom .mixins import StorageSettingsMixin\n\n\n@deconstructible(path=\"django.core.files.storage.FileSystemStorage\")\nclass FileSystemStorage(Storage, StorageSettingsMixin):\n \"\"\"\n Standard filesystem storage\n \"\"\"\n\n def __i", "suffix": "_base_url = base_url\n self._file_permissions_mode = file_permissions_mode\n self._directory_permissions_mode = directory_permissions_mode\n self._allow_overwrite = allow_overwrite\n setting_changed.connect(self._clear_cached_proper", "middle": "nit__(\n self,\n location=None,\n base_url=None,\n file_permissions_mode=None,\n directory_permissions_mode=None,\n allow_overwrite=False,\n ):\n self._location = location\n self.", "meta": {"filepath": "django/core/files/storage/filesystem.py", "language": "python", "file_size": 8510, "cut_index": 716, "middle_length": 229}} +{"prefix": "lers-related deprecation warnings and helpers used in multiple places.\n# (In a separate file to avoid circular import problems.)\nimport warnings\n\nfrom django.conf import DEPRECATED_EMAIL_SETTINGS, settings\nfrom django.utils.deprecation import (\n RemovedInDjango70Warning,\n django_file_prefixes,\n)\n\nFAIL_SILENTLY_ARG_WARNING = (\n \"The 'fail_silently' argument is deprecated. See 'Migrating email to \"\n \"mailers' in Django's documentation for recommended replacements.\"\n)\nAUTH_ARGS_WARNING = (\n \"The", "suffix": "t \"\n \"with a MAILERS alias.\"\n)\nNO_DEFAULT_MAILER_WARNING = (\n \"Django 7.0 will not have a default mailer. Configure \"\n \"settings.MAILERS to avoid errors when sending email.\"\n)\n\n\ndef report_using_incompatibility(\n connection=None, fail_silently=", "middle": " 'auth_user' and 'auth_password' arguments are deprecated. Set \"\n \"'username' and 'password' OPTIONS in MAILERS instead.\"\n)\nCONNECTION_ARG_WARNING = (\n \"The 'connection' argument is deprecated. Switch to the 'using' argumen", "meta": {"filepath": "django/core/mail/deprecation.py", "language": "python", "file_size": 2225, "cut_index": 563, "middle_length": 229}} +{"prefix": "ns import SuspiciousFileOperation\n\n\ndef validate_file_name(name, allow_relative_path=False):\n # Remove potentially dangerous names\n if os.path.basename(name) in {\"\", \".\", \"..\"}:\n raise SuspiciousFileOperation(\"Could not derive file name from '%s'\" % name)\n\n if allow_relative_path:\n # Ensure that name can be treated as a pure posix path, i.e. Unix\n # style (with forward slashes).\n path = pathlib.PurePosixPath(str(name).replace(\"\\\\\", \"/\"))\n if path.is_absolute() or ", "suffix": "me '%s' includes path elements\" % name)\n\n return name\n\n\nclass FileProxyMixin:\n \"\"\"\n A mixin class used to forward file methods to an underlying file\n object. The internal file object has to be called \"file\"::\n\n class FileProxy(FileProxyM", "middle": "\"..\" in path.parts:\n raise SuspiciousFileOperation(\n \"Detected path traversal attempt in '%s'\" % name\n )\n elif name != os.path.basename(name):\n raise SuspiciousFileOperation(\"File na", "meta": {"filepath": "django/core/files/utils.py", "language": "python", "file_size": 2601, "cut_index": 563, "middle_length": 229}} +{"prefix": "_external_use,\n)\nfrom django.utils.encoding import force_bytes, force_str, punycode\nfrom django.utils.timezone import get_current_timezone\n\nfrom .deprecation import (\n CONNECTION_ARG_WARNING,\n FAIL_SILENTLY_ARG_WARNING,\n report_using_incompatibility,\n)\n\n# RemovedInDjango70Warning.\n# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from\n# some spam filters.\nutf8_charset = Charset.Charset(\"utf-8\")\nutf8_charset.body_encoding = None # Python defaults to BASE64\nutf8_charset_qp = C", "suffix": "emovedInDjango70Warning.\nRFC5322_EMAIL_LINE_LENGTH_LIMIT = 998\n\n\n# RemovedInDjango70Warning.\n# BadHeaderError must be ValueError (not subclass it), so that existing code\n# with `except BadHeaderError` will catch the ValueError that Python's modern\n# email ", "middle": "harset.Charset(\"utf-8\")\nutf8_charset_qp.body_encoding = Charset.QP\n\n# Default MIME type to use on attachments (if it is not explicitly given\n# and cannot be guessed).\nDEFAULT_ATTACHMENT_MIME_TYPE = \"application/octet-stream\"\n\n# R", "meta": {"filepath": "django/core/mail/message.py", "language": "python", "file_size": 25403, "cut_index": 1331, "middle_length": 229}} +{"prefix": "\nBackend for test environment.\n\"\"\"\n\nimport copy\n\nfrom django.core import mail\nfrom django.core.mail.backends.base import BaseEmailBackend\n\n\nclass EmailBackend(BaseEmailBackend):\n \"\"\"\n An email backend for use during test sessions.\n\n The test connection stores email messages in a dummy outbox,\n rather than sending them out on the wire.\n\n The dummy outbox is accessible through the outbox instance attribute.\n \"\"\"\n\n # RemovedInDjango70Warning: *args. (The only supported posarg will be\n #", "suffix": "essages):\n \"\"\"Redirect messages to the dummy outbox\"\"\"\n msg_count = 0\n for message in messages:\n message.message() # Trigger header validation.\n msg_copy = copy.deepcopy(message)\n msg_copy.sent_using =", "middle": " removed from BaseEmailBackend in Django 7.0.)\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not hasattr(mail, \"outbox\"):\n mail.outbox = []\n\n def send_messages(self, m", "meta": {"filepath": "django/core/mail/backends/locmem.py", "language": "python", "file_size": 1105, "cut_index": 515, "middle_length": 229}} +{"prefix": "ttings\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass FlatpageForm(forms.ModelForm):\n url = forms.RegexField(\n label=_(\"URL\"),\n max_length=100,\n regex=r\"^[-\\w/.~]+$\",\n help_text=_(\n \"Example: “/about/contact/”. Make sure to have leading and trailing \"\n \"slashes.\"\n ),\n error_messa", "suffix": "atPage\n fields = \"__all__\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not self._trailing_slash_required():\n self.fields[\"url\"].help_text = _(\n \"Example: “/about/contact”. ", "middle": "ges={\n \"invalid\": _(\n \"This value must contain only letters, numbers, dots, \"\n \"underscores, dashes, slashes or tildes.\"\n ),\n },\n )\n\n class Meta:\n model = Fl", "meta": {"filepath": "django/contrib/flatpages/forms.py", "language": "python", "file_size": 2492, "cut_index": 563, "middle_length": 229}} +{"prefix": ".models import Site\nfrom django.db import models\nfrom django.urls import NoReverseMatch, get_script_prefix, reverse\nfrom django.utils.encoding import iri_to_uri\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass FlatPage(models.Model):\n url = models.CharField(_(\"URL\"), max_length=100, db_index=True)\n title = models.CharField(_(\"title\"), max_length=200)\n content = models.TextField(_(\"content\"), blank=True)\n enable_comments = models.BooleanField(_(\"enable comments\"), default=False)\n ", "suffix": " will use “flatpages/default.html”.\"\n ),\n )\n registration_required = models.BooleanField(\n _(\"registration required\"),\n help_text=_(\n \"If this is checked, only logged-in users will be able to view the page.\"\n ),", "middle": " template_name = models.CharField(\n _(\"template name\"),\n max_length=70,\n blank=True,\n help_text=_(\n \"Example: “flatpages/contact_page.html”. If this isn’t provided, \"\n \"the system", "meta": {"filepath": "django/contrib/flatpages/models.py", "language": "python", "file_size": 1764, "cut_index": 537, "middle_length": 229}} +{"prefix": "gration(migrations.Migration):\n dependencies = [\n (\"sites\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"FlatPage\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\n ", "suffix": "\"content\", models.TextField(verbose_name=\"content\", blank=True)),\n (\n \"enable_comments\",\n models.BooleanField(default=False, verbose_name=\"enable comments\"),\n ),\n (\n ", "middle": " \"url\",\n models.CharField(max_length=100, verbose_name=\"URL\", db_index=True),\n ),\n (\"title\", models.CharField(max_length=200, verbose_name=\"title\")),\n (", "meta": {"filepath": "django/contrib/flatpages/migrations/0001_initial.py", "language": "python", "file_size": 2408, "cut_index": 563, "middle_length": 229}} +{"prefix": "for SyndicationFeed subclasses\n to produce simple GeoRSS or W3C Geo elements.\n \"\"\"\n\n def georss_coords(self, coords):\n \"\"\"\n In GeoRSS coordinate pairs are ordered by lat/lon and separated by\n a single white space. Given a tuple of coordinates, return a string\n GeoRSS representation.\n \"\"\"\n return \" \".join(\"%f %f\" % (coord[1], coord[0]) for coord in coords)\n\n def add_georss_point(self, handler, coords, w3c_geo=False):\n \"\"\"\n Adds a GeoRSS poin", "suffix": " handler.addQuickElement(\"geo:lat\", \"%f\" % lat)\n handler.addQuickElement(\"geo:lon\", \"%f\" % lon)\n else:\n handler.addQuickElement(\"georss:point\", self.georss_coords((coords,)))\n\n def add_georss_element(self, handler, item, ", "middle": "t with the given coords using the given handler.\n Handles the differences between simple GeoRSS and the more popular\n W3C Geo specification.\n \"\"\"\n if w3c_geo:\n lon, lat = coords[:2]\n ", "meta": {"filepath": "django/contrib/gis/feeds.py", "language": "python", "file_size": 5994, "cut_index": 716, "middle_length": 229}} +{"prefix": "(R) is a registered trademark of MaxMind, Inc.\n\nFor IP-based geolocation, this module requires the GeoLite2 Country and City\ndatasets, in binary format (CSV will not work!). The datasets may be\ndownloaded from MaxMind at https://dev.maxmind.com/geoip/geoip2/geolite2/.\nGrab GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz, and unzip them in the\ndirectory corresponding to settings.GEOIP_PATH.\n\"\"\"\n\nimport ipaddress\nimport socket\n\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationE", "suffix": ": # pragma: no cover\n HAS_GEOIP2 = False\nelse:\n HAS_GEOIP2 = True\n __all__ += [\"GeoIP2\", \"GeoIP2Exception\"]\n\n\n# These are the values stored in the `database_type` field of the metadata.\n# See https://maxmind.github.io/MaxMind-DB/#database_type fo", "middle": "rror\nfrom django.core.validators import validate_ipv46_address\nfrom django.utils._os import to_path\nfrom django.utils.functional import cached_property\n\n__all__ = [\"HAS_GEOIP2\"]\n\ntry:\n import geoip2.database\nexcept ImportError", "meta": {"filepath": "django/contrib/gis/geoip2.py", "language": "python", "file_size": 8743, "cut_index": 716, "middle_length": 229}} +{"prefix": "om django.utils.encoding import filepath_to_uri\nfrom django.utils.functional import cached_property\nfrom django.utils.timezone import now\n\nfrom .base import Storage\nfrom .mixins import StorageSettingsMixin\n\n__all__ = (\"InMemoryStorage\",)\n\n\nclass TimingMixin:\n def _initialize_times(self):\n self.created_time = now()\n self.accessed_time = self.created_time\n self.modified_time = self.created_time\n\n def _update_accessed_time(self):\n self.accessed_time = now()\n\n def _update_mo", "suffix": "d record creation,\n modification, and access times.\n \"\"\"\n\n def __init__(self, content=\"\", name=None):\n super().__init__(content, name)\n self._content_type = type(content)\n self._initialize_times()\n\n def open(self, mode):\n ", "middle": "dified_time(self):\n self.modified_time = now()\n\n\nclass InMemoryFileNode(ContentFile, TimingMixin):\n \"\"\"\n Helper class representing an in-memory file node.\n\n Handle unicode/bytes conversion during I/O operations an", "meta": {"filepath": "django/core/files/storage/memory.py", "language": "python", "file_size": 9875, "cut_index": 921, "middle_length": 229}} +{"prefix": "ail import InvalidMailer\nfrom django.core.mail.backends.base import BaseEmailBackend\nfrom django.core.mail.utils import DNS_NAME\nfrom django.utils.deprecation import RemovedInDjango70Warning, warn_about_external_use\nfrom django.utils.encoding import force_str, punycode\nfrom django.utils.functional import cached_property\n\n\nclass EmailBackend(BaseEmailBackend):\n \"\"\"\n A wrapper that manages the SMTP network connection.\n \"\"\"\n\n def __init__(\n self,\n host=None,\n port=None,\n ", "suffix": "InDjango70Warning.\n if \"alias\" not in kwargs:\n msg = (\n \"Directly creating EmailBackend instances is deprecated. \"\n \"Use mail.mailers instead.\"\n )\n warn_about_external_use(msg, RemovedIn", "middle": " username=None,\n password=None,\n use_tls=None,\n fail_silently=False,\n use_ssl=None,\n timeout=None,\n ssl_keyfile=None,\n ssl_certfile=None,\n **kwargs,\n ):\n # Removed", "meta": {"filepath": "django/core/mail/backends/smtp.py", "language": "python", "file_size": 9122, "cut_index": 716, "middle_length": 229}} +{"prefix": "b.flatpages.models import FlatPage\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.http import Http404, HttpResponse, HttpResponsePermanentRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.template import loader\nfrom django.utils.safestring import mark_safe\nfrom django.views.decorators.csrf import csrf_protect\n\nDEFAULT_TEMPLATE = \"flatpages/default.html\"\n\n# This view is called from FlatpageFallbackMiddleware.process_response\n# when a 404 is raised, which often means", "suffix": "ng flatpage exists,\n# or a redirect is required for authentication, the 404 needs to be returned\n# without any CSRF checks. Therefore, we only\n# CSRF protect the internal implementation.\n\n\ndef flatpage(request, url):\n \"\"\"\n Public interface to the fla", "middle": " CsrfViewMiddleware.process_view\n# has not been called even if CsrfViewMiddleware is installed. So we need\n# to use @csrf_protect, in case the template needs {% csrf_token %}.\n# However, we can't just wrap this view; if no matchi", "meta": {"filepath": "django/contrib/flatpages/views.py", "language": "python", "file_size": 2724, "cut_index": 563, "middle_length": 229}} +{"prefix": "mport re\n\nfrom django.utils.regex_helper import _lazy_re_compile\n\n# Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure\n# to prevent potentially malicious input from reaching the underlying C\n# library. Not a substitute for good web security programming practices.\nhex_regex = _lazy_re_compile(r\"^[0-9A-F]+$\", re.I)\nwkt_regex = _lazy_re_compile(\n r\"^(SRID=(?P\\-?[0-9]+);)?\"\n r\"(?P\"\n r\"(?PPOINT|LINESTRING|LINEARRING|POLYGON|MULTIPOINT|\"\n r\"MULTILINESTRING|MULT", "suffix": "TRYCOLLECTION|CIRCULARSTRING|COMPOUNDCURVE|\"\n r\"CURVEPOLYGON|MULTICURVE|MULTISURFACE|CURVE|SURFACE|POLYHEDRALSURFACE|TIN|\"\n r\"TRIANGLE)\"\n r\"[ACEGIMLONPSRUTYZ0-9,.+() -]+)$\",\n re.I,\n)\njson_regex = _lazy_re_compile(r\"^(\\s+)?\\{.*}(\\s+)?$\", re.DOTA", "middle": "IPOLYGON|GEOME", "meta": {"filepath": "django/contrib/gis/geometry.py", "language": "python", "file_size": 787, "cut_index": 513, "middle_length": 14}} +{"prefix": "ckend that writes messages to console instead of sending them.\n\"\"\"\n\nimport sys\nimport threading\n\nfrom django.core.mail.backends.base import BaseEmailBackend\n\n\nclass EmailBackend(BaseEmailBackend):\n def __init__(self, fail_silently=False, **kwargs):\n self.stream = kwargs.pop(\"stream\", sys.stdout)\n self._lock = threading.RLock()\n super().__init__(**kwargs)\n self.fail_silently = fail_silently\n\n def write_message(self, message):\n msg = message.message()\n msg_data ", "suffix": "self.stream.write(\"-\" * 79)\n self.stream.write(\"\\n\")\n\n def send_messages(self, email_messages):\n \"\"\"Write all messages to the stream in a thread-safe way.\"\"\"\n if not email_messages:\n return\n msg_count = 0\n w", "middle": "= msg.as_bytes()\n charset = (\n msg.get_charset().get_output_charset() if msg.get_charset() else \"utf-8\"\n )\n msg_data = msg_data.decode(charset)\n self.stream.write(\"%s\\n\" % msg_data)\n ", "meta": {"filepath": "django/core/mail/backends/console.py", "language": "python", "file_size": 1477, "cut_index": 524, "middle_length": 229}} +{"prefix": "from django.conf import settings\nfrom django.contrib.flatpages.views import flatpage\nfrom django.http import Http404\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass FlatpageFallbackMiddleware(MiddlewareMixin):\n def process_response(self, request, response):\n if response.status_code != 404:\n return response # No need to check for a flatpage for non-404 responses.\n try:\n return flatpage(request, request.path_info)\n # Return the original response if a", "suffix": "ened. Because this\n # is a middleware, we can't assume the errors will be caught elsewhere.\n except Http404:\n return response\n except Exception:\n if settings.DEBUG:\n raise\n return respons", "middle": "ny errors happ", "meta": {"filepath": "django/contrib/flatpages/middleware.py", "language": "python", "file_size": 784, "cut_index": 512, "middle_length": 14}} +{"prefix": "rt FlatPage\nfrom django.contrib.sites.shortcuts import get_current_site\n\nregister = template.Library()\n\n\nclass FlatpageNode(template.Node):\n def __init__(self, context_name, starts_with=None, user=None):\n self.context_name = context_name\n if starts_with:\n self.starts_with = template.Variable(starts_with)\n else:\n self.starts_with = None\n if user:\n self.user = template.Variable(user)\n else:\n self.user = None\n\n def render(self", "suffix": " # If a prefix was specified, add a filter\n if self.starts_with:\n flatpages = flatpages.filter(\n url__startswith=self.starts_with.resolve(context)\n )\n\n # If the provided user is not authenticated, or no u", "middle": ", context):\n if \"request\" in context:\n site_pk = get_current_site(context[\"request\"]).pk\n else:\n site_pk = settings.SITE_ID\n flatpages = FlatPage.objects.filter(sites__id=site_pk)\n ", "meta": {"filepath": "django/contrib/flatpages/templatetags/flatpages.py", "language": "python", "file_size": 3552, "cut_index": 614, "middle_length": 229}} +{"prefix": "django.core.exceptions import ImproperlyConfigured\nfrom django.db.models import Field\nfrom django.utils.translation import gettext_lazy as _\n\n# Local cache of the spatial_ref_sys table, which holds SRID data for each\n# spatial database alias. This cache exists so that the database isn't queried\n# for SRID info each time a distance query is constructed.\n_srid_cache = defaultdict(dict)\n\n\nSRIDCacheEntry = namedtuple(\n \"SRIDCacheEntry\", [\"units\", \"units_name\", \"spheroid\", \"geodetic\"]\n)\n\n\ndef get_srid_info(sr", "suffix": "are cached.\n \"\"\"\n from django.contrib.gis.gdal import SpatialReference\n\n try:\n # The SpatialRefSys model for the spatial backend.\n SpatialRefSys = connection.ops.spatial_ref_sys()\n except NotImplementedError:\n SpatialRefSys", "middle": "id, connection):\n \"\"\"\n Return the units, unit name, and spheroid WKT associated with the\n given SRID from the `spatial_ref_sys` (or equivalent) spatial database\n table for the given database connection. These results ", "meta": {"filepath": "django/contrib/gis/db/models/fields.py", "language": "python", "file_size": 14314, "cut_index": 921, "middle_length": 229}} +{"prefix": "etry Types.\"\n\n wkb25bit = -2147483648\n\n # Dictionary of acceptable OGRwkbGeometryType s and their string names.\n _types = {\n 0: \"Unknown\",\n 1: \"Point\",\n 2: \"LineString\",\n 3: \"Polygon\",\n 4: \"MultiPoint\",\n 5: \"MultiLineString\",\n 6: \"MultiPolygon\",\n 7: \"GeometryCollection\",\n 8: \"CircularString\",\n 9: \"CompoundCurve\",\n 10: \"CurvePolygon\",\n 11: \"MultiCurve\",\n 12: \"MultiSurface\",\n 15: \"PolyhedralSurface\",\n ", "suffix": "rveZ\",\n 1012: \"MultiSurfaceZ\",\n 1013: \"CurveZ\",\n 1014: \"SurfaceZ\",\n 1015: \"PolyhedralSurfaceZ\",\n 1016: \"TINZ\",\n 1017: \"TriangleZ\",\n 2001: \"PointM\",\n 2002: \"LineStringM\",\n 2003: \"PolygonM\",\n ", "middle": " 16: \"TIN\",\n 17: \"Triangle\",\n 100: \"None\",\n 101: \"LinearRing\",\n 102: \"PointZ\",\n 1008: \"CircularStringZ\",\n 1009: \"CompoundCurveZ\",\n 1010: \"CurvePolygonZ\",\n 1011: \"MultiCu", "meta": {"filepath": "django/contrib/gis/gdal/geomtype.py", "language": "python", "file_size": 4582, "cut_index": 614, "middle_length": 229}} +{"prefix": "ion):\n \"\"\"\n Custom argparse action for the `ogrinspect` `layer_key` keyword option\n which may be an integer or a string.\n \"\"\"\n\n def __call__(self, parser, namespace, value, option_string=None):\n try:\n setattr(namespace, self.dest, int(value))\n except ValueError:\n setattr(namespace, self.dest, value)\n\n\nclass ListOptionAction(argparse.Action):\n \"\"\"\n Custom argparse action for `ogrinspect` keywords that require\n a string list. If the string is 'True'/", "suffix": " else:\n setattr(namespace, self.dest, value.split(\",\"))\n\n\nclass Command(BaseCommand):\n help = (\n \"Inspects the given OGR-compatible data source (e.g., a shapefile) and \"\n \"outputs\\na GeoDjango model with the given model name. F", "middle": "'true' then the option\n value will be a boolean instead.\n \"\"\"\n\n def __call__(self, parser, namespace, value, option_string=None):\n if value.lower() == \"true\":\n setattr(namespace, self.dest, True)\n ", "meta": {"filepath": "django/contrib/gis/management/commands/ogrinspect.py", "language": "python", "file_size": 6071, "cut_index": 716, "middle_length": 229}} +{"prefix": "s.db.models import GeometryField\nfrom django.contrib.gis.db.models.functions import AsKML, Transform\nfrom django.contrib.gis.shortcuts import render_to_kml, render_to_kmz\nfrom django.core.exceptions import FieldDoesNotExist\nfrom django.db import DEFAULT_DB_ALIAS, connections\nfrom django.http import Http404\n\n\ndef kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):\n \"\"\"\n This view generates KML for the given app label, model, and field name.\n\n The field name must be t", "suffix": "s\"'\n % (label, model)\n )\n\n if field_name:\n try:\n field = klass._meta.get_field(field_name)\n if not isinstance(field, GeometryField):\n raise FieldDoesNotExist\n except FieldDoesNotExist:", "middle": "hat of a geographic field.\n \"\"\"\n placemarks = []\n try:\n klass = apps.get_model(label, model)\n except LookupError:\n raise Http404(\n 'You must supply a valid app label and module name. Got \"%s.%", "meta": {"filepath": "django/contrib/gis/sitemaps/views.py", "language": "python", "file_size": 2352, "cut_index": 563, "middle_length": 229}} +{"prefix": "es import BaseSpatialFeatures\nfrom django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures\nfrom django.utils.functional import cached_property\n\n\nclass DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures):\n empty_intersection_returns_none = False\n has_spatialrefsys_table = False\n supports_add_srs_entry = False\n supports_distance_geodetic = False\n supports_length_geodetic = False\n supports_area_geodetic = False\n supports_transform = False\n supports_nu", "suffix": " False\n unsupported_geojson_options = {\"crs\"}\n\n @cached_property\n def supports_geometry_field_unique_index(self):\n # Not supported in MySQL since\n # https://dev.mysql.com/worklog/task/?id=11808\n return self.connection.mysql_is", "middle": "ll_geometries = False\n supports_num_points_poly =", "meta": {"filepath": "django/contrib/gis/db/backends/mysql/features.py", "language": "python", "file_size": 876, "cut_index": 559, "middle_length": 52}} +{"prefix": "trib.gis.db.backends.utils import SpatialOperator\nfrom django.contrib.gis.geos.geometry import GEOSGeometryBase\nfrom django.contrib.gis.geos.prototypes.io import wkb_r\nfrom django.contrib.gis.measure import Distance\nfrom django.db.backends.mysql.operations import DatabaseOperations\nfrom django.utils.functional import cached_property\n\n\nclass MySQLOperations(BaseSpatialOperations, DatabaseOperations):\n name = \"mysql\"\n geom_func_prefix = \"ST_\"\n\n Adapter = WKTAdapter\n\n @cached_property\n def maria", "suffix": "efix + \"AsBinary(%s)\"\n\n @cached_property\n def from_text(self):\n return self.geom_func_prefix + \"GeomFromText\"\n\n @cached_property\n def collect(self):\n if self.connection.features.supports_collect_aggr:\n return self.geom_", "middle": "db(self):\n return self.connection.mysql_is_mariadb\n\n @cached_property\n def mysql(self):\n return not self.connection.mysql_is_mariadb\n\n @cached_property\n def select(self):\n return self.geom_func_pr", "meta": {"filepath": "django/contrib/gis/db/backends/mysql/operations.py", "language": "python", "file_size": 5174, "cut_index": 716, "middle_length": 229}} +{"prefix": "quoting for GEOS geometries into PostgreSQL/PostGIS.\n\"\"\"\n\nfrom django.contrib.gis.db.backends.postgis.pgraster import to_pgraster\nfrom django.contrib.gis.geos import GEOSGeometry\nfrom django.db.backends.postgresql.psycopg_any import sql\n\n\nclass PostGISAdapter:\n def __init__(self, obj, geography=False):\n \"\"\"\n Initialize on the spatial object.\n \"\"\"\n self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter))\n\n # Getting the WKB (in string form, to allow easy pickli", "suffix": " self.geography = geography\n\n def __conform__(self, proto):\n \"\"\"Does the given protocol conform to what Psycopg2 expects?\"\"\"\n from psycopg2.extensions import ISQLQuote\n\n if proto == ISQLQuote:\n return self\n else", "middle": "ng of\n # the adaptor) and the SRID from the geometry or raster.\n if self.is_geometry:\n self.ewkb = bytes(obj.ewkb)\n else:\n self.ewkb = to_pgraster(obj)\n\n self.srid = obj.srid\n ", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/adapter.py", "language": "python", "file_size": 1980, "cut_index": 537, "middle_length": 229}} +{"prefix": "rsion constant definitions\n\"\"\"\n\n# Lookup to convert pixel type values from GDAL to PostGIS\nGDAL_TO_POSTGIS = [None, 4, 6, 5, 8, 7, 10, 11, None, None, None, None]\n\n# Lookup to convert pixel type values from PostGIS to GDAL\nPOSTGIS_TO_GDAL = [1, 1, 1, 3, 1, 3, 2, 5, 4, None, 6, 7, None, None]\n\n# Struct pack structure for raster header, the raster header has the\n# following structure:\n#\n# Endianness, PostGIS raster version, number of bands, scale, origin,\n# skew, srid, width, and height.\n#\n# Scale, origin, an", "suffix": ". This is\n# used to pack and unpack the pixel values of PostGIS raster bands.\nGDAL_TO_STRUCT = [\n None,\n \"B\",\n \"H\",\n \"h\",\n \"L\",\n \"l\",\n \"f\",\n \"d\",\n None,\n None,\n None,\n None,\n]\n\n# Size of the packed value in bytes for dif", "middle": "d skew have x and y values. PostGIS currently uses\n# a fixed endianness (1) and there is only one version (0).\nPOSTGIS_HEADER_STRUCTURE = \"B H H d d d d d d i H H\"\n\n# Lookup values to convert GDAL pixel types to struct characters", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/const.py", "language": "python", "file_size": 2008, "cut_index": 537, "middle_length": 229}} +{"prefix": "import zipfile\nfrom io import BytesIO\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.template import loader\n\n# NumPy supported?\ntry:\n import numpy\nexcept ImportError:\n numpy = False\n\n\ndef compress_kml(kml):\n \"Return compressed KMZ from the given KML string.\"\n kmz = BytesIO()\n with zipfile.ZipFile(kmz, \"a\", zipfile.ZIP_DEFLATED) as zf:\n zf.writestr(\"doc.kml\", kml.encode(settings.DEFAULT_CHARSET))\n kmz.seek(0)\n return kmz.read()\n\n\ndef render_to_k", "suffix": "def render_to_kmz(*args, **kwargs):\n \"\"\"\n Compress the KML content and return as KMZ (using the correct\n MIME type).\n \"\"\"\n return HttpResponse(\n compress_kml(loader.render_to_string(*args, **kwargs)),\n content_type=\"application", "middle": "ml(*args, **kwargs):\n \"Render the response as KML (using the correct MIME type).\"\n return HttpResponse(\n loader.render_to_string(*args, **kwargs),\n content_type=\"application/vnd.google-earth.kml+xml\",\n )\n\n\n", "meta": {"filepath": "django/contrib/gis/shortcuts.py", "language": "python", "file_size": 1027, "cut_index": 512, "middle_length": 229}} +{"prefix": "t DatabaseIntrospection\n\n\nclass PostGISIntrospection(DatabaseIntrospection):\n postgis_oid_lookup = {} # Populated when introspection is performed.\n\n ignored_tables = [\n *DatabaseIntrospection.ignored_tables,\n \"geography_columns\",\n \"geometry_columns\",\n \"raster_columns\",\n \"spatial_ref_sys\",\n \"raster_overviews\",\n ]\n\n def get_field_type(self, data_type, description):\n if not self.postgis_oid_lookup:\n # Query PostgreSQL's pg_type table to d", "suffix": ", the `data_types_reverse`\n # dictionary isn't updated until introspection is performed here.\n with self.connection.cursor() as cursor:\n cursor.execute(\n \"SELECT oid, typname \"\n \"FR", "middle": "etermine the OID integers\n # for the PostGIS data types used in reverse lookup (the integers\n # may be different across versions). To prevent unnecessary\n # requests upon connection initialization", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/introspection.py", "language": "python", "file_size": 3185, "cut_index": 614, "middle_length": 229}} +{"prefix": "s.db.models import GeometryField\nfrom django.contrib.sitemaps import Sitemap\nfrom django.db import models\nfrom django.urls import reverse\n\n\nclass KMLSitemap(Sitemap):\n \"\"\"\n A minimal hook to produce KML sitemaps.\n \"\"\"\n\n geo_format = \"kml\"\n\n def __init__(self, locations=None):\n # If no locations specified, then we try to build for\n # every model in installed applications.\n self.locations = self._build_kml_sources(locations)\n\n def _build_kml_sources(self, sources):\n ", "suffix": "ll models.\n \"\"\"\n kml_sources = []\n if sources is None:\n sources = apps.get_models()\n for source in sources:\n if isinstance(source, models.base.ModelBase):\n for field in source._meta.fields:\n ", "middle": " \"\"\"\n Go through the given sources and return a 3-tuple of the application\n label, module name, and field name of every GeometryField encountered\n in the sources.\n\n If no sources are provided, then a", "meta": {"filepath": "django/contrib/gis/sitemaps/kml.py", "language": "python", "file_size": 2573, "cut_index": 563, "middle_length": 229}} +{"prefix": "\"\nA collection of utility routines and classes used by the spatial\nbackends.\n\"\"\"\n\n\nclass SpatialOperator:\n \"\"\"\n Class encapsulating the behavior specific to a GIS operation (used by\n lookups).\n \"\"\"\n\n sql_template = None\n\n def __init__(self, op=None, func=None):\n self.op = op\n self.func = func\n\n @property\n def default_template(self):\n if self.func:\n return \"%(func)s(%(lhs)s, %(rhs)s)\"\n else:\n return \"%(lhs)s %(op)s %(rhs)s\"\n\n def as", "suffix": "nection, lookup, template_params, sql_params):\n sql_template = self.sql_template or lookup.sql_template or self.default_template\n template_params.update({\"op\": self.op, \"func\": self.func})\n return sql_template % template_params, sql_pa", "middle": "_sql(self, con", "meta": {"filepath": "django/contrib/gis/db/backends/utils.py", "language": "python", "file_size": 789, "cut_index": 514, "middle_length": 14}} +{"prefix": "alError\nfrom django.db.backends.mysql.schema import DatabaseSchemaEditor\n\nlogger = logging.getLogger(\"django.contrib.gis\")\n\n\nclass MySQLGISSchemaEditor(DatabaseSchemaEditor):\n sql_add_spatial_index = \"CREATE SPATIAL INDEX %(index)s ON %(table)s(%(column)s)\"\n\n def quote_value(self, value):\n if isinstance(value, self.connection.ops.Adapter):\n return super().quote_value(str(value))\n return super().quote_value(value)\n\n def _field_indexes_sql(self, model, field):\n if isin", "suffix": "patial_index(\n cursor, model._meta.db_table\n )\n )\n sql = self._create_spatial_index_sql(model, field)\n if supports_spatial_index:\n return [sql]\n else:\n", "middle": "stance(field, GeometryField) and field.spatial_index and not field.null:\n with self.connection.cursor() as cursor:\n supports_spatial_index = (\n self.connection.introspection.supports_s", "meta": {"filepath": "django/contrib/gis/db/backends/mysql/schema.py", "language": "python", "file_size": 3607, "cut_index": 614, "middle_length": 229}} +{"prefix": "import c_void_p\n\n\nclass CPointerBase:\n \"\"\"\n Base class for objects that have a pointer access property\n that controls access to the underlying C pointer.\n \"\"\"\n\n _ptr = None # Initially the pointer is NULL.\n ptr_type = c_void_p\n destructor = None\n null_ptr_exception_class = AttributeError\n\n @property\n def ptr(self):\n # Raise an exception if the pointer isn't valid so that NULL pointers\n # aren't passed to routines -- that's very bad.\n if self._ptr:\n ", "suffix": "with pointers of the compatible\n # type or None (NULL).\n if not (ptr is None or isinstance(ptr, self.ptr_type)):\n raise TypeError(\"Incompatible pointer type: %s.\" % type(ptr))\n self._ptr = ptr\n\n def __del__(self):\n ", "middle": " return self._ptr\n raise self.null_ptr_exception_class(\n \"NULL %s pointer encountered.\" % self.__class__.__name__\n )\n\n @ptr.setter\n def ptr(self, ptr):\n # Only allow the pointer to be set ", "meta": {"filepath": "django/contrib/gis/ptr.py", "language": "python", "file_size": 1312, "cut_index": 524, "middle_length": 229}} +{"prefix": " import wkb_r\nfrom django.contrib.gis.measure import Distance\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import NotSupportedError, ProgrammingError\nfrom django.db.backends.postgresql.operations import DatabaseOperations\nfrom django.db.backends.postgresql.psycopg_any import is_psycopg3\nfrom django.db.models import Func, Value\nfrom django.utils.functional import cached_property\nfrom django.utils.version import get_version_tuple\n\nfrom .adapter import PostGISAdapter\nfrom .models impo", "suffix": "aphy=False, raster=False, **kwargs):\n # Only a subset of the operators and functions are available for the\n # geography type. Lookups that don't support geography will be cast to\n # geometry.\n self.geography = geography\n ", "middle": "rt PostGISGeometryColumns, PostGISSpatialRefSys\nfrom .pgraster import from_pgraster\n\n# Identifier to mark raster lookups as bilateral.\nBILATERAL = \"bilateral\"\n\n\nclass PostGISOperator(SpatialOperator):\n def __init__(self, geogr", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/operations.py", "language": "python", "file_size": 17077, "cut_index": 921, "middle_length": 229}} +{"prefix": "nd SpatialRefSys models for the PostGIS backend.\n\"\"\"\n\nfrom django.contrib.gis.db.backends.base.models import SpatialRefSysMixin\nfrom django.db import models\n\n\nclass PostGISGeometryColumns(models.Model):\n \"\"\"\n The 'geometry_columns' view from PostGIS. See the PostGIS\n documentation at Ch. 4.3.2.\n \"\"\"\n\n f_table_catalog = models.CharField(max_length=256)\n f_table_schema = models.CharField(max_length=256)\n f_table_name = models.CharField(max_length=256)\n f_geometry_column = models.CharFi", "suffix": "olumns\"\n managed = False\n\n def __str__(self):\n return \"%s.%s - %dD %s field (SRID: %d)\" % (\n self.f_table_name,\n self.f_geometry_column,\n self.coord_dimension,\n self.type,\n self.srid,\n", "middle": "eld(max_length=256)\n coord_dimension = models.IntegerField()\n srid = models.IntegerField(primary_key=True)\n type = models.CharField(max_length=30)\n\n class Meta:\n app_label = \"gis\"\n db_table = \"geometry_c", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/models.py", "language": "python", "file_size": 2002, "cut_index": 537, "middle_length": 229}} +{"prefix": "resql.features import (\n DatabaseFeatures as PsycopgDatabaseFeatures,\n)\nfrom django.db.backends.postgresql.introspection import (\n DatabaseIntrospection as PsycopgDatabaseIntrospection,\n)\nfrom django.db.backends.postgresql.operations import (\n DatabaseOperations as PsycopgDatabaseOperations,\n)\nfrom django.db.backends.postgresql.psycopg_any import is_psycopg3\n\nfrom .adapter import PostGISAdapter\nfrom .features import DatabaseFeatures\nfrom .introspection import PostGISIntrospection\nfrom .operations i", "suffix": "extBinaryLoader, TextLoader\n\n class GeometryType:\n pass\n\n class GeographyType:\n pass\n\n class RasterType:\n pass\n\n class BaseTextDumper(Dumper):\n def dump(self, obj):\n # Return bytes as hex for text formatti", "middle": "mport PostGISOperations\nfrom .schema import PostGISSchemaEditor\n\nif is_psycopg3:\n from psycopg.adapt import Dumper\n from psycopg.pq import Format\n from psycopg.types import TypeInfo\n from psycopg.types.string import T", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/base.py", "language": "python", "file_size": 5793, "cut_index": 716, "middle_length": 229}} +{"prefix": "port FIELD_TYPE\n\nfrom django.contrib.gis.gdal import OGRGeomType\nfrom django.db.backends.mysql.introspection import DatabaseIntrospection\n\n\nclass MySQLIntrospection(DatabaseIntrospection):\n # Updating the data_types_reverse dictionary with the appropriate\n # type for Geometry fields.\n data_types_reverse = DatabaseIntrospection.data_types_reverse.copy()\n data_types_reverse[FIELD_TYPE.GEOMETRY] = \"GeometryField\"\n\n def get_geometry_type(self, table_name, description):\n with self.connectio", "suffix": "te_name(table_name))\n # Increment over description info until we get to the geometry\n # column.\n for column, typ, null, key, default, extra in cursor.fetchall():\n if column == description.name:\n ", "middle": "n.cursor() as cursor:\n # In order to get the specific geometry type of the field,\n # we introspect on the table definition using `DESCRIBE`.\n cursor.execute(\"DESCRIBE %s\" % self.connection.ops.quo", "meta": {"filepath": "django/contrib/gis/db/backends/mysql/introspection.py", "language": "python", "file_size": 1602, "cut_index": 537, "middle_length": 229}} +{"prefix": "t DatabaseSchemaEditor\nfrom django.db.models.expressions import Col, Func\n\n\nclass PostGISSchemaEditor(DatabaseSchemaEditor):\n geom_index_type = \"GIST\"\n geom_index_ops_nd = \"GIST_GEOMETRY_OPS_ND\"\n rast_index_template = \"ST_ConvexHull(%(expressions)s)\"\n\n sql_alter_column_to_3d = (\n \"ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force3D(%(column)s)::%(type)s\"\n )\n sql_alter_column_to_2d = (\n \"ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force2D(%(column)s)::%(type)s\"\n )\n\n ", "suffix": "eturn super()._field_should_be_indexed(model, field)\n\n def _create_index_sql(self, model, *, fields=None, **kwargs):\n if fields is None or len(fields) != 1 or not hasattr(fields[0], \"geodetic\"):\n return super()._create_index_sql(model,", "middle": " def geo_quote_name(self, name):\n return self.connection.ops.geo_quote_name(name)\n\n def _field_should_be_indexed(self, model, field):\n if getattr(field, \"spatial_index\", False):\n return True\n r", "meta": {"filepath": "django/contrib/gis/db/backends/postgis/schema.py", "language": "python", "file_size": 4482, "cut_index": 614, "middle_length": 229}} +{"prefix": "g, and MultiPolygon\n\"\"\"\n\nfrom django.contrib.gis.geos import prototypes as capi\nfrom django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin\nfrom django.contrib.gis.geos.libgeos import GEOM_PTR\nfrom django.contrib.gis.geos.linestring import LinearRing, LineString\nfrom django.contrib.gis.geos.point import Point\nfrom django.contrib.gis.geos.polygon import Polygon\n\n\nclass GeometryCollection(GEOSGeometry):\n _typeid = 7\n\n def __init__(self, *args, **kwargs):\n \"Initialize a Geometry", "suffix": " if isinstance(args[0], (tuple, list)):\n init_geoms = args[0]\n else:\n init_geoms = args\n else:\n init_geoms = args\n\n # Ensuring that only the permitted geometries are allowed in thi", "middle": " Collection from a sequence of Geometry objects.\"\n # Checking the arguments\n if len(args) == 1:\n # If only one geometry provided or a list of geometries is provided\n # in the first argument.\n ", "meta": {"filepath": "django/contrib/gis/geos/collections.py", "language": "python", "file_size": 3991, "cut_index": 614, "middle_length": 229}} +{"prefix": "s.base.adapter import WKTAdapter\nfrom django.contrib.gis.geos import GeometryCollection, Polygon\n\n\nclass OracleSpatialAdapter(WKTAdapter):\n input_size = oracledb.CLOB\n\n def __init__(self, geom):\n \"\"\"\n Oracle requires that polygon rings are in proper orientation. This\n affects spatial operations and an invalid orientation may cause\n failures. Correct orientations are:\n * Outer ring - counter clockwise\n * Inner ring(s) - clockwise\n \"\"\"\n if isinst", "suffix": "nd self._polygon_must_be_fixed(g) for g in geom\n ):\n geom = self._fix_geometry_collection(geom)\n\n self.wkt = geom.wkt\n self.srid = geom.srid\n\n @staticmethod\n def _polygon_must_be_fixed(poly):\n return not", "middle": "ance(geom, Polygon):\n if self._polygon_must_be_fixed(geom):\n geom = self._fix_polygon(geom)\n elif isinstance(geom, GeometryCollection):\n if any(\n isinstance(g, Polygon) a", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/adapter.py", "language": "python", "file_size": 2023, "cut_index": 563, "middle_length": 229}} +{"prefix": "ngo.db.backends.oracle.introspection import DatabaseIntrospection\nfrom django.utils.functional import cached_property\n\n\nclass OracleIntrospection(DatabaseIntrospection):\n # Associating any OBJECTVAR instances with GeometryField. This won't work\n # right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, but it is the\n # only object type supported within Django anyways.\n @cached_property\n def data_types_reverse(self):\n return {\n **super().data_types_reverse,\n oracle", "suffix": "\n # information.\n try:\n cursor.execute(\n 'SELECT \"DIMINFO\", \"SRID\" FROM \"USER_SDO_GEOM_METADATA\" '\n 'WHERE \"TABLE_NAME\"=%s AND \"COLUMN_NAME\"=%s',\n (table_name.upp", "middle": "db.DB_TYPE_OBJECT: \"GeometryField\",\n }\n\n def get_geometry_type(self, table_name, description):\n with self.connection.cursor() as cursor:\n # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/introspection.py", "language": "python", "file_size": 1910, "cut_index": 537, "middle_length": 229}} +{"prefix": " on such platforms. Specifically, XE lacks\nsupport for an internal JVM, and Java libraries are required to use\nthe WKT constructors.\n\"\"\"\n\nimport re\n\nfrom django.contrib.gis.db import models\nfrom django.contrib.gis.db.backends.base.operations import BaseSpatialOperations\nfrom django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter\nfrom django.contrib.gis.db.backends.utils import SpatialOperator\nfrom django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase\nfrom django.contrib.g", "suffix": "\"\n\n\nclass SDOOperator(SpatialOperator):\n sql_template = \"%(func)s(%(lhs)s, %(rhs)s) = 'TRUE'\"\n\n\nclass SDODWithin(SpatialOperator):\n sql_template = \"SDO_WITHIN_DISTANCE(%(lhs)s, %(rhs)s, %%s) = 'TRUE'\"\n\n\nclass SDODisjoint(SpatialOperator):\n sql_tem", "middle": "is.geos.prototypes.io import wkb_r\nfrom django.contrib.gis.measure import Distance\nfrom django.db.backends.oracle.operations import DatabaseOperations\nfrom django.utils.functional import cached_property\n\nDEFAULT_TOLERANCE = \"0.05", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/operations.py", "language": "python", "file_size": 9132, "cut_index": 716, "middle_length": 229}} +{"prefix": "ort ImproperlyConfigured\nfrom django.db.backends.sqlite3.base import DatabaseWrapper as SQLiteDatabaseWrapper\n\nfrom .client import SpatiaLiteClient\nfrom .features import DatabaseFeatures\nfrom .introspection import SpatiaLiteIntrospection\nfrom .operations import SpatiaLiteOperations\nfrom .schema import SpatialiteSchemaEditor\n\n\nclass DatabaseWrapper(SQLiteDatabaseWrapper):\n SchemaEditorClass = SpatialiteSchemaEditor\n # Classes instantiated in __init__().\n client_class = SpatiaLiteClient\n features_", "suffix": "Here we are figuring out the path to the SpatiaLite library\n # (`libspatialite`). If it's not in the system library path (e.g., it\n # cannot be found by `ctypes.util.find_library`), then it may be set\n # manually in the settings via th", "middle": "class = DatabaseFeatures\n introspection_class = SpatiaLiteIntrospection\n ops_class = SpatiaLiteOperations\n\n def __init__(self, *args, **kwargs):\n # Trying to find the location of the SpatiaLite library.\n # ", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/base.py", "language": "python", "file_size": 3218, "cut_index": 614, "middle_length": 229}} +{"prefix": "es import BaseSpatialFeatures\nfrom django.db.backends.sqlite3.features import (\n DatabaseFeatures as SQLiteDatabaseFeatures,\n)\nfrom django.utils.functional import cached_property\n\n\nclass DatabaseFeatures(BaseSpatialFeatures, SQLiteDatabaseFeatures):\n can_alter_geometry_field = False # Not implemented\n supports_3d_storage = True\n\n @cached_property\n def supports_area_geodetic(self):\n return bool(self.connection.ops.geom_lib_version())\n\n @cached_property\n def django_test_skips(self", "suffix": " skips.update(\n {\n \"SpatiaLite doesn't support distance lookups with Distance objects.\": {\n \"gis_tests.geogapp.tests.GeographyTest.test02_distance_lookup\",\n },\n }\n )\n retu", "middle": "):\n skips = super().django_test_skips\n ", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/features.py", "language": "python", "file_size": 876, "cut_index": 559, "middle_length": 52}} +{"prefix": "SpatialOperations\nfrom django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter\nfrom django.contrib.gis.db.backends.utils import SpatialOperator\nfrom django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase\nfrom django.contrib.gis.geos.prototypes.io import wkb_r\nfrom django.contrib.gis.measure import Distance\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db.backends.sqlite3.operations import DatabaseOperations\nfrom django.utils.functional import cached_p", "suffix": "on, lookup, template_params, sql_params)\n return \"%s > 0\" % sql, params\n\n\nclass SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations):\n name = \"spatialite\"\n spatialite = True\n\n Adapter = SpatiaLiteAdapter\n\n collect = \"Collect\"\n", "middle": "roperty\nfrom django.utils.version import get_version_tuple\n\n\nclass SpatialiteNullCheckOperator(SpatialOperator):\n def as_sql(self, connection, lookup, template_params, sql_params):\n sql, params = super().as_sql(connecti", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/operations.py", "language": "python", "file_size": 8608, "cut_index": 716, "middle_length": 229}} +{"prefix": "lass BaseSpatialFeatures:\n gis_enabled = True\n\n # Does the database contain a SpatialRefSys model to store SRID\n # information?\n has_spatialrefsys_table = True\n\n # Does the backend support the django.contrib.gis.utils.add_srs_entry()\n # utility?\n supports_add_srs_entry = True\n # Does the backend introspect GeometryField to its subtypes?\n supports_geometry_field_introspection = True\n\n # Does the database have a geography type?\n supports_geography = False\n # Does the backen", "suffix": "s = False\n # Does the database support SRID transform operations?\n supports_transform = True\n # Can geometry fields be null?\n supports_null_geometries = True\n # Are empty geometries supported?\n supports_empty_geometries = False\n # Can ", "middle": "d support storing 3D geometries?\n supports_3d_storage = False\n # Reference implementation of 3D functions is:\n # https://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_3D_Functions\n supports_3d_function", "meta": {"filepath": "django/contrib/gis/db/backends/base/features.py", "language": "python", "file_size": 3748, "cut_index": 614, "middle_length": 229}} +{"prefix": "e import Distance as DistanceMeasure\nfrom django.db import NotSupportedError\nfrom django.utils.functional import cached_property\n\n\nclass BaseSpatialOperations:\n # Quick booleans for the type of this spatial backend, and\n # an attribute for the spatial database version tuple (if applicable)\n postgis = False\n spatialite = False\n mariadb = False\n mysql = False\n oracle = False\n spatial_version = None\n\n # How the geometry column should be selected.\n select = \"%s\"\n\n @cached_proper", "suffix": " used in spatial_function_name().\n function_names = {}\n\n # Set of known unsupported functions of the backend\n unsupported_functions = {\n \"Area\",\n \"AsGeoJSON\",\n \"AsGML\",\n \"AsKML\",\n \"AsSVG\",\n \"AsWKB\",\n ", "middle": "ty\n def select_extent(self):\n return self.select\n\n # Aggregates\n disallowed_aggregates = ()\n\n geom_func_prefix = \"\"\n\n # Mapping between Django function names and backend names, when names do\n # not match;", "meta": {"filepath": "django/contrib/gis/db/backends/base/operations.py", "language": "python", "file_size": 7136, "cut_index": 716, "middle_length": 229}} +{"prefix": "ometryField,\n LineStringField,\n)\nfrom django.db.models import Aggregate, Func, Value\nfrom django.utils.functional import cached_property\n\n__all__ = [\"Collect\", \"Extent\", \"Extent3D\", \"MakeLine\", \"Union\"]\n\n\nclass GeoAggregate(Aggregate):\n function = None\n is_extent = False\n\n @cached_property\n def output_field(self):\n return self.output_field_class(self.source_expressions[0].output_field.srid)\n\n def as_sql(self, compiler, connection, function=None, **extra_context):\n # this will", "suffix": "n,\n function=function or connection.ops.spatial_aggregate_name(self.name),\n **extra_context,\n )\n\n def as_oracle(self, compiler, connection, **extra_context):\n if not self.is_extent:\n tolerance = self.extra.", "middle": " be called again in parent, but it's needed now - before\n # we get the spatial_aggregate_name\n connection.ops.check_expression_support(self)\n return super().as_sql(\n compiler,\n connectio", "meta": {"filepath": "django/contrib/gis/db/models/aggregates.py", "language": "python", "file_size": 3100, "cut_index": 614, "middle_length": 229}} +{"prefix": "r the Oracle spatial\nbackend.\n\nIt should be noted that Oracle Spatial does not have database tables\nnamed according to the OGC standard, so the closest analogs are used.\nFor example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns\nmodel and the `SDO_COORD_REF_SYS` is used for the SpatialRefSys model.\n\"\"\"\n\nfrom django.contrib.gis.db import models\nfrom django.contrib.gis.db.backends.base.models import SpatialRefSysMixin\n\n\nclass OracleGeometryColumns(models.Model):\n \"Maps to the Oracle USER_SDO", "suffix": "S.SDO_DIM_ARRAY).\n\n class Meta:\n app_label = \"gis\"\n db_table = \"USER_SDO_GEOM_METADATA\"\n managed = False\n\n def __str__(self):\n return \"%s - %s (SRID: %s)\" % (self.table_name, self.column_name, self.srid)\n\n @classmethod\n", "middle": "_GEOM_METADATA table.\"\n\n table_name = models.CharField(max_length=32)\n column_name = models.CharField(max_length=1024)\n srid = models.IntegerField(primary_key=True)\n # TODO: Add support for `diminfo` column (type MDSY", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/models.py", "language": "python", "file_size": 2080, "cut_index": 563, "middle_length": 229}} +{"prefix": "chemaEditor(DatabaseSchemaEditor):\n sql_add_geometry_metadata = \"\"\"\n INSERT INTO USER_SDO_GEOM_METADATA\n (\"TABLE_NAME\", \"COLUMN_NAME\", \"DIMINFO\", \"SRID\")\n VALUES (\n %(table)s,\n %(column)s,\n MDSYS.SDO_DIM_ARRAY(\n MDSYS.SDO_DIM_ELEMENT('LONG', %(dim0)s, %(dim2)s, %(tolerance)s),\n MDSYS.SDO_DIM_ELEMENT('LAT', %(dim1)s, %(dim3)s, %(tolerance)s)\n ),\n %(srid)s\n )\"\"\"\n sql_add_spatial_index = (", "suffix": ")\n sql_clear_geometry_field_metadata = (\n \"DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s \"\n \"AND COLUMN_NAME = %(column)s\"\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n ", "middle": "\n \"CREATE INDEX %(index)s ON %(table)s(%(column)s) \"\n \"INDEXTYPE IS MDSYS.SPATIAL_INDEX\"\n )\n sql_clear_geometry_table_metadata = (\n \"DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s\"\n ", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/schema.py", "language": "python", "file_size": 5430, "cut_index": 716, "middle_length": 229}} +{"prefix": " AddGeometryColumn(%(table)s, %(column)s, %(srid)s, \"\n \"%(geom_type)s, %(dim)s, %(null)s)\"\n )\n sql_add_spatial_index = \"SELECT CreateSpatialIndex(%(table)s, %(column)s)\"\n sql_drop_spatial_index = \"DROP TABLE idx_%(table)s_%(column)s\"\n sql_recover_geometry_metadata = (\n \"SELECT RecoverGeometryColumn(%(table)s, %(column)s, %(srid)s, \"\n \"%(geom_type)s, %(dim)s)\"\n )\n sql_remove_geometry_metadata = \"SELECT DiscardGeometryColumn(%(table)s, %(column)s)\"\n sql_discard_geomet", "suffix": "ble)s\"\n )\n\n geometry_tables = [\n \"geometry_columns\",\n \"geometry_columns_auth\",\n \"geometry_columns_time\",\n \"geometry_columns_statistics\",\n ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwa", "middle": "ry_columns = (\n \"DELETE FROM %(geom_table)s WHERE f_table_name = %(table)s\"\n )\n sql_update_geometry_columns = (\n \"UPDATE %(geom_table)s SET f_table_name = %(new_table)s \"\n \"WHERE f_table_name = %(old_ta", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/schema.py", "language": "python", "file_size": 7350, "cut_index": 716, "middle_length": 229}} +{"prefix": "lRefSysMixin:\n \"\"\"\n The SpatialRefSysMixin is a class used by the database-dependent\n SpatialRefSys objects to reduce redundant code.\n \"\"\"\n\n @cached_property\n def srs(self):\n \"\"\"\n Return a GDAL SpatialReference object.\n \"\"\"\n try:\n return gdal.SpatialReference(self.wkt)\n except Exception as e:\n wkt_error = e\n\n try:\n return gdal.SpatialReference(self.proj4text)\n except Exception as e:\n proj4_error = ", "suffix": " def ellipsoid(self):\n \"\"\"\n Return a tuple of the ellipsoid parameters:\n (semimajor axis, semiminor axis, and inverse flattening).\n \"\"\"\n return self.srs.ellipsoid\n\n @property\n def name(self):\n \"Return the p", "middle": "e\n\n raise Exception(\n \"Could not get OSR SpatialReference.\\n\"\n f\"Error for WKT '{self.wkt}': {wkt_error}\\n\"\n f\"Error for PROJ.4 '{self.proj4text}': {proj4_error}\"\n )\n\n @property\n ", "meta": {"filepath": "django/contrib/gis/db/backends/base/models.py", "language": "python", "file_size": 3694, "cut_index": 614, "middle_length": 229}} +{"prefix": "nd SpatialRefSys models for the SpatiaLite backend.\n\"\"\"\n\nfrom django.contrib.gis.db.backends.base.models import SpatialRefSysMixin\nfrom django.db import models\n\n\nclass SpatialiteGeometryColumns(models.Model):\n \"\"\"\n The 'geometry_columns' table from SpatiaLite.\n \"\"\"\n\n f_table_name = models.CharField(max_length=256)\n f_geometry_column = models.CharField(max_length=256)\n coord_dimension = models.IntegerField()\n srid = models.IntegerField(primary_key=True)\n spatial_index_enabled = models", "suffix": "D %s field (SRID: %d)\" % (\n self.f_table_name,\n self.f_geometry_column,\n self.coord_dimension,\n self.type,\n self.srid,\n )\n\n @classmethod\n def table_name_col(cls):\n \"\"\"\n Retur", "middle": ".IntegerField()\n type = models.IntegerField(db_column=\"geometry_type\")\n\n class Meta:\n app_label = \"gis\"\n db_table = \"geometry_columns\"\n managed = False\n\n def __str__(self):\n return \"%s.%s - %d", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/models.py", "language": "python", "file_size": 1930, "cut_index": 537, "middle_length": 229}} +{"prefix": "from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures\nfrom django.db.backends.oracle.features import (\n DatabaseFeatures as OracleDatabaseFeatures,\n)\nfrom django.utils.functional import cached_property\n\n\nclass DatabaseFeatures(BaseSpatialFeatures, OracleDatabaseFeatures):\n supports_add_srs_entry = False\n supports_geometry_field_introspection = False\n supports_geometry_field_unique_index = False\n supports_perimeter_geodetic = True\n supports_dwithin_distance_expr = Fal", "suffix": " {\n \"Oracle doesn't support spatial operators in constraints.\": {\n \"gis_tests.gis_migrations.test_operations.OperationTests.\"\n \"test_add_check_constraint\",\n },\n }\n ", "middle": "se\n supports_tolerance_parameter = True\n unsupported_geojson_options = {\"bbox\", \"crs\", \"precision\"}\n\n @cached_property\n def django_test_skips(self):\n skips = super().django_test_skips\n skips.update(\n ", "meta": {"filepath": "django/contrib/gis/db/backends/oracle/features.py", "language": "python", "file_size": 1021, "cut_index": 512, "middle_length": 229}} +{"prefix": " **extra)\n\n # Ensure that value expressions are geometric.\n for pos in self.geom_param_pos:\n expr = self.source_expressions[pos]\n if not isinstance(expr, Value):\n continue\n try:\n output_field = expr.output_field\n except FieldError:\n output_field = None\n geom = expr.value\n if (\n not isinstance(geom, GEOSGeometry)\n or output_field\n and not is", "suffix": " if not geom.srid and not output_field:\n raise ValueError(\"SRID is required for all geometries.\")\n if not output_field:\n self.source_expressions[pos] = Value(\n geom, output_field=Geometry", "middle": "instance(output_field, GeometryField)\n ):\n raise TypeError(\n \"%s function requires a geometric argument in position %d.\"\n % (self.name, pos + 1)\n )\n ", "meta": {"filepath": "django/contrib/gis/db/models/functions.py", "language": "python", "file_size": 21181, "cut_index": 1331, "middle_length": 229}} +{"prefix": "tors for instantiating and setting Geometry or Raster\nobjects corresponding to geographic model fields.\n\nThanks to Robert Coup for providing this functionality (see #4322).\n\"\"\"\n\nfrom django.db.models.query_utils import DeferredAttribute\n\n\nclass SpatialProxy(DeferredAttribute):\n def __init__(self, klass, field, load_func=None):\n \"\"\"\n Initialize on the given Geometry or Raster class (not an instance)\n and the corresponding field.\n \"\"\"\n self._klass = klass\n self._lo", "suffix": "initialization and the value of\n the field. Currently, GEOS or OGR geometries as well as GDALRasters are\n supported.\n \"\"\"\n if instance is None:\n # Accessed on a class, not an instance\n return self\n\n ", "middle": "ad_func = load_func or klass\n super().__init__(field)\n\n def __get__(self, instance, cls=None):\n \"\"\"\n Retrieve the geometry or raster, initializing it using the\n corresponding class specified during ", "meta": {"filepath": "django/contrib/gis/db/models/proxy.py", "language": "python", "file_size": 3174, "cut_index": 614, "middle_length": 229}} +{"prefix": "ore.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .widgets import OpenLayersWidget\n\n\nclass GeometryField(forms.Field):\n \"\"\"\n This is the basic form field for a Geometry. Any textual input that is\n accepted by GEOSGeometry is accepted by this form. By default,\n this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.\n \"\"\"\n\n widget = OpenLayersWidget\n geom_type = \"GEOMETRY\"\n\n default_error_messages = {\n \"required\": _(\"No geomet", "suffix": " \"to the SRID of the geometry form field.\"\n ),\n }\n\n def __init__(self, *, srid=None, geom_type=None, **kwargs):\n self.srid = srid\n if geom_type is not None:\n self.geom_type = geom_type\n super().__init_", "middle": "ry value provided.\"),\n \"invalid_geom\": _(\"Invalid geometry value.\"),\n \"invalid_geom_type\": _(\"Invalid geometry type.\"),\n \"transform_error\": _(\n \"An error occurred when transforming the geometry \"\n ", "meta": {"filepath": "django/contrib/gis/forms/fields.py", "language": "python", "file_size": 4460, "cut_index": 614, "middle_length": 229}} +{"prefix": "ypes interfaces for GDAL objects. The following GDAL\nobjects are supported:\n\nCoordTransform: Used for coordinate transformations from one spatial\n reference system to another.\n\nDriver: Wraps an OGR data source driver.\n\nDataSource: Wrapper for the OGR data source object, supports\n OGR-supported data sources.\n\nEnvelope: A ctypes structure for bounding boxes (GDAL library\n not required).\n\nOGRGeometry: Object for accessing OGR Geometry functionality.\n\nOGRGeomType: A class for representing the different OGR Geom", "suffix": "path may be overridden\nby setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C\nlibrary on your system.\n\"\"\"\n\nfrom django.contrib.gis.gdal.datasource import DataSource\nfrom django.contrib.gis.gdal.driver import Driver\nfrom django.contrib.", "middle": "etry\n types (GDAL library not required).\n\nSpatialReference: Represents OSR Spatial Reference objects.\n\nThe GDAL library will be imported from the system path using the default\nlibrary name for the current OS. The default library ", "meta": {"filepath": "django/contrib/gis/gdal/__init__.py", "language": "python", "file_size": 1810, "cut_index": 537, "middle_length": 229}} +{"prefix": ".gdal.error import GDALException\nfrom django.contrib.gis.gdal.libgdal import GDAL_VERSION\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.utils.encoding import force_bytes, force_str\n\n\nclass Driver(GDALBase):\n \"\"\"\n Wrap a GDAL/OGR Data Source Driver.\n For more information, see the C API documentation:\n https://gdal.org/api/vector_c_api.html\n https://gdal.org/api/raster_c_api.html\n \"\"\"\n\n # Case-insensitive aliases for some GDAL/OGR Drivers.\n # For a complete list", "suffix": " Shapefile\",\n # raster\n \"tiff\": \"GTiff\",\n \"tif\": \"GTiff\",\n \"jpeg\": \"JPEG\",\n \"jpg\": \"JPEG\",\n }\n\n if GDAL_VERSION[:2] <= (3, 10):\n _alias.update(\n {\n \"tiger\": \"TIGER\",\n ", "middle": " of original driver names see\n # https://gdal.org/drivers/vector/\n # https://gdal.org/drivers/raster/\n _alias = {\n # vector\n \"esri\": \"ESRI Shapefile\",\n \"shp\": \"ESRI Shapefile\",\n \"shape\": \"ESRI", "meta": {"filepath": "django/contrib/gis/gdal/driver.py", "language": "python", "file_size": 3154, "cut_index": 614, "middle_length": 229}} +{"prefix": "e GDAL & SRS Exception objects, and the\ncheck_err() routine which checks the status code returned by\nGDAL/OGR methods.\n\"\"\"\n\n\n# #### GDAL & SRS Exceptions ####\nclass GDALException(Exception):\n pass\n\n\nclass SRSException(Exception):\n pass\n\n\n# #### GDAL/OGR error checking codes and routine ####\n\n# OGR Error Codes\nOGRERR_DICT = {\n 1: (GDALException, \"Not enough data.\"),\n 2: (GDALException, \"Not enough memory.\"),\n 3: (GDALException, \"Unsupported geometry type.\"),\n 4: (GDALException, \"Unsupported", "suffix": ".html#cpl-error-h\nCPLERR_DICT = {\n 1: (GDALException, \"AppDefined\"),\n 2: (GDALException, \"OutOfMemory\"),\n 3: (GDALException, \"FileIO\"),\n 4: (GDALException, \"OpenFailed\"),\n 5: (GDALException, \"IllegalArg\"),\n 6: (GDALException, \"NotSupporte", "middle": " operation.\"),\n 5: (GDALException, \"Corrupt data.\"),\n 6: (GDALException, \"OGR failure.\"),\n 7: (SRSException, \"Unsupported SRS.\"),\n 8: (GDALException, \"Invalid handle.\"),\n}\n\n# CPL Error Codes\n# https://gdal.org/api/cpl", "meta": {"filepath": "django/contrib/gis/gdal/error.py", "language": "python", "file_size": 1575, "cut_index": 537, "middle_length": 229}} +{"prefix": ".gdal.prototypes import ds as capi\nfrom django.utils.encoding import force_str\n\n\n# For more information, see the OGR C API source code:\n# https://gdal.org/api/vector_c_api.html\n#\n# The OGR_Fld_* routines are relevant here.\nclass Field(GDALBase):\n \"\"\"\n Wrap an OGR Field. Needs to be instantiated from a Feature object.\n \"\"\"\n\n def __init__(self, feat, index):\n \"\"\"\n Initialize on the feature object and the integer index of\n the field within the feature.\n \"\"\"\n # Set", "suffix": " raise GDALException(\"Cannot create OGR Field, invalid pointer given.\")\n self.ptr = fld_ptr\n\n # Setting the class depending upon the OGR Field Type (OFT)\n self.__class__ = OGRFieldTypes[self.type]\n\n def __str__(self):\n \"Re", "middle": "ting the feature pointer and index.\n self._feat = feat\n self._index = index\n\n # Getting the pointer for this field.\n fld_ptr = capi.get_feat_field_defn(feat.ptr, index)\n if not fld_ptr:\n ", "meta": {"filepath": "django/contrib/gis/gdal/field.py", "language": "python", "file_size": 6886, "cut_index": 716, "middle_length": 229}} +{"prefix": "dels import * # NOQA isort:skip\nfrom django.db.models import __all__ as models_all # isort:skip\nimport django.contrib.gis.db.models.functions # NOQA\nimport django.contrib.gis.db.models.lookups # NOQA\nfrom django.contrib.gis.db.models.aggregates import * # NOQA\nfrom django.contrib.gis.db.models.aggregates import __all__ as aggregates_all\nfrom django.contrib.gis.db.models.fields import (\n GeometryCollectionField,\n GeometryField,\n LineStringField,\n MultiLineStringField,\n MultiPointField,\n ", "suffix": "d,\n RasterField,\n)\n\n__all__ = models_all + aggregates_all\n__all__ += [\n \"GeometryCollectionField\",\n \"GeometryField\",\n \"LineStringField\",\n \"MultiLineStringField\",\n \"MultiPointField\",\n \"MultiPolygonField\",\n \"PointField\",\n \"PolygonF", "middle": " MultiPolygonField,\n PointField,\n PolygonFiel", "meta": {"filepath": "django/contrib/gis/db/models/__init__.py", "language": "python", "file_size": 865, "cut_index": 529, "middle_length": 52}} +{"prefix": "n compiler.compile(self.lhs)\n\n\nclass GISLookup(Lookup):\n sql_template = None\n transform_func = None\n distance = False\n band_rhs = None\n band_lhs = None\n\n def __init__(self, lhs, rhs):\n rhs, *self.rhs_params = rhs if isinstance(rhs, (list, tuple)) else (rhs,)\n super().__init__(lhs, rhs)\n self.template_params = {}\n self.process_rhs_params()\n\n def process_rhs_params(self):\n if self.rhs_params:\n # Check if a band index was passed in the query ar", "suffix": "r lookup %s.\" % self.lookup_name)\n elif isinstance(self.lhs, RasterBandTransform):\n self.process_band_indices(only_lhs=True)\n\n def process_band_indices(self, only_lhs=False):\n \"\"\"\n Extract the lhs band index from the band", "middle": "gument.\n if len(self.rhs_params) == (2 if self.lookup_name == \"relate\" else 1):\n self.process_band_indices()\n elif len(self.rhs_params) > 1:\n raise ValueError(\"Tuple too long fo", "meta": {"filepath": "django/contrib/gis/db/models/lookups.py", "language": "python", "file_size": 11744, "cut_index": 921, "middle_length": 229}} +{"prefix": "from django.contrib.gis.geometry import json_regex\nfrom django.contrib.gis.geos import GEOSException, GEOSGeometry\nfrom django.forms.widgets import Widget\n\nlogger = logging.getLogger(\"django.contrib.gis\")\n\n\nclass BaseGeometryWidget(Widget):\n \"\"\"\n The base class for rich geometry widgets.\n Render a map using the WKT of the geometry.\n \"\"\"\n\n base_layer = None\n geom_type = \"GEOMETRY\"\n map_srid = 4326\n display_raw = False\n\n supports_3d = False\n template_name = \"\" # set on subclasse", "suffix": "date(attrs)\n\n def serialize(self, value):\n return value.wkt if value else \"\"\n\n def deserialize(self, value):\n try:\n return GEOSGeometry(value)\n except (GEOSException, GDALException, ValueError, TypeError) as err:\n ", "middle": "s\n\n def __init__(self, attrs=None):\n self.attrs = {\n key: getattr(self, key)\n for key in (\"base_layer\", \"geom_type\", \"map_srid\", \"display_raw\")\n }\n if attrs:\n self.attrs.up", "meta": {"filepath": "django/contrib/gis/forms/widgets.py", "language": "python", "file_size": 3639, "cut_index": 614, "middle_length": 229}} +{"prefix": "d one\nfor the upper right coordinate:\n\n +----------o Upper right; (max_x, max_y)\n | |\n | |\n | |\nLower left (min_x, min_y) o----------+\n\"\"\"\n\nfrom ctypes import Structure, c_double\n\nfrom django.contrib.gis.gdal.error import GDALException\n\n\n# The OGR definition of an Envelope is a C structure containing four doubles.\n# See the 'ogr_core.h' source file for more information:\n# https://gd", "suffix": "xY\", c_double),\n ]\n\n\nclass Envelope:\n \"\"\"\n The Envelope object is a C structure that contains the minimum and\n maximum X, Y coordinates for a rectangle bounding box. The naming\n of the variables is compatible with the OGR Envelope structure.", "middle": "al.org/doxygen/ogr__core_8h_source.html\nclass OGREnvelope(Structure):\n \"Represent the OGREnvelope C Structure.\"\n\n _fields_ = [\n (\"MinX\", c_double),\n (\"MaxX\", c_double),\n (\"MinY\", c_double),\n (\"Ma", "meta": {"filepath": "django/contrib/gis/gdal/envelope.py", "language": "python", "file_size": 7309, "cut_index": 716, "middle_length": 229}} +{"prefix": ", SpatialReference('WGS84'))\n >>> mpnt.add(wkt1)\n >>> mpnt.add(wkt1)\n >>> print(mpnt)\n MULTIPOINT (-90 30,-90 30)\n >>> print(mpnt.srs.name)\n WGS 84\n >>> print(mpnt.srs.proj)\n +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\n >>> mpnt.transform(SpatialReference('NAD27'))\n >>> print(mpnt.proj)\n +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs\n >>> print(mpnt)\n MULTIPOINT (-89.99993037860248 29.99979788655764,-89.99993037860248\n 29.99979788655764)\n\n The OGRGeomType class is to make it easy to specify an OGR g", "suffix": "tive\n >>> # Equivalence works w/non-OGRGeomType objects:\n >>> print(gt1 == 3, gt1 == 'Polygon')\n True True\n\"\"\"\n\nimport sys\nfrom binascii import b2a_hex\nfrom ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at\n\nfrom django.contrib.gis.gdal", "middle": "eometry type:\n >>> from django.contrib.gis.gdal import OGRGeomType\n >>> gt1 = OGRGeomType(3) # Using an integer for the type\n >>> gt2 = OGRGeomType('Polygon') # Using a string\n >>> gt3 = OGRGeomType('POLYGON') # It's case-insensi", "meta": {"filepath": "django/contrib/gis/gdal/geometries.py", "language": "python", "file_size": 28848, "cut_index": 1331, "middle_length": 229}} +{"prefix": "ordTransform, SpatialReference\nfrom django.core.serializers.base import SerializerDoesNotExist\nfrom django.core.serializers.json import Serializer as JSONSerializer\n\n\nclass Serializer(JSONSerializer):\n \"\"\"\n Convert a queryset to GeoJSON, http://geojson.org/\n \"\"\"\n\n def _init_options(self):\n super()._init_options()\n self.geometry_field = self.json_kwargs.pop(\"geometry_field\", None)\n self.id_field = self.json_kwargs.pop(\"id_field\", None)\n self.srid = self.json_kwargs.pop", "suffix": "= [*self.selected_fields, self.geometry_field]\n\n def start_serialization(self):\n self._init_options()\n self._cts = {} # cache of CoordTransform's\n self.stream.write('{\"type\": \"FeatureCollection\", \"features\": [')\n\n def end_serial", "middle": "(\"srid\", 4326)\n if (\n self.selected_fields is not None\n and self.geometry_field is not None\n and self.geometry_field not in self.selected_fields\n ):\n self.selected_fields ", "meta": {"filepath": "django/contrib/gis/serializers/geojson.py", "language": "python", "file_size": 2876, "cut_index": 563, "middle_length": 229}} +{"prefix": "ctor geometry data from many different file\nformats (including ESRI shapefiles).\n\nWhen instantiating a DataSource object, use the filename of a\nGDAL-supported data source. For example, an SHP file.\n\nThe ds_driver keyword is used internally when a ctypes pointer\nis passed in directly.\n\nExample:\n ds = DataSource('/home/foo/bar.shp')\n for layer in ds:\n for feature in layer:\n # Getting the geometry for the feature.\n g = feature.geom\n\n # Getting the 'description' field for the feature", "suffix": "')\n nm = field.name\n\n # Get the type (integer) of the field, e.g. 0 => OFTInteger\n t = field.type\n\n # Returns the value the field; OFTIntegers return ints,\n # OFTReal returns floats, all else ret", "middle": ".\n desc = feature['description']\n\n # We can also increment through all of the fields\n # attached to this feature.\n for field in feature:\n # Get the name of the field (e.g. 'description", "meta": {"filepath": "django/contrib/gis/gdal/datasource.py", "language": "python", "file_size": 4603, "cut_index": 614, "middle_length": 229}} +{"prefix": "ion\nfrom django.contrib.gis.gdal.field import Field\nfrom django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.utils.encoding import force_bytes, force_str\n\n\n# For more information, see the OGR C API source code:\n# https://gdal.org/api/vector_c_api.html\n#\n# The OGR_F_* routines are relevant here.\nclass Feature(GDALBase):\n \"\"\"\n This class that wraps an OGR F", "suffix": "\"\n if not feat:\n raise GDALException(\"Cannot create OGR Feature, invalid pointer given.\")\n self.ptr = feat\n self._layer = layer\n\n def __getitem__(self, index):\n \"\"\"\n Get the Field object at the specified ind", "middle": "eature, needs to be instantiated\n from a Layer object.\n \"\"\"\n\n destructor = capi.destroy_feature\n\n def __init__(self, feat, layer):\n \"\"\"\n Initialize Feature from a pointer and its Layer object.\n \"\"", "meta": {"filepath": "django/contrib/gis/gdal/feature.py", "language": "python", "file_size": 4014, "cut_index": 614, "middle_length": 229}} +{"prefix": "tion, SRSException\nfrom django.contrib.gis.gdal.feature import Feature\nfrom django.contrib.gis.gdal.field import OGRFieldTypes\nfrom django.contrib.gis.gdal.geometries import OGRGeometry\nfrom django.contrib.gis.gdal.geomtype import OGRGeomType\nfrom django.contrib.gis.gdal.prototypes import ds as capi\nfrom django.contrib.gis.gdal.prototypes import geom as geom_api\nfrom django.contrib.gis.gdal.prototypes import srs as srs_api\nfrom django.contrib.gis.gdal.srs import SpatialReference\nfrom django.utils.encoding i", "suffix": "OGR Layer, needs to be instantiated from a DataSource\n object.\n \"\"\"\n\n def __init__(self, layer_ptr, ds):\n \"\"\"\n Initialize on an OGR C pointer to the Layer and the `DataSource` object\n that owns this layer. The `DataSource` obj", "middle": "mport force_bytes, force_str\n\n\n# For more information, see the OGR C API source code:\n# https://gdal.org/api/vector_c_api.html\n#\n# The OGR_L_* routines are relevant here.\nclass Layer(GDALBase):\n \"\"\"\n A class that wraps an ", "meta": {"filepath": "django/contrib/gis/gdal/layer.py", "language": "python", "file_size": 8820, "cut_index": 716, "middle_length": 229}} +{"prefix": ",0,\n AUTHORITY[\"EPSG\",\"8901\"]],\n UNIT[\"degree\",0.01745329251994328,\n AUTHORITY[\"EPSG\",\"9122\"]],\n AUTHORITY[\"EPSG\",\"4326\"]]\n>>> print(srs.proj)\n+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\n>>> print(srs.ellipsoid)\n(6378137.0, 6356752.3142451793, 298.25722356300003)\n>>> print(srs.projected, srs.geographic)\nFalse True\n>>> srs.import_epsg(32140)\n>>> print(srs.name)\nNAD83 / Texas South Central\n\"\"\"\n\nfrom ctypes import byref, c_char_p, c_int\nfrom enum import IntEnum\nfrom types import NoneTy", "suffix": "ass AxisOrder(IntEnum):\n TRADITIONAL = 0\n AUTHORITY = 1\n\n\nclass SpatialReference(GDALBase):\n \"\"\"\n A wrapper for the OGRSpatialReference object. According to the GDAL web\n site, the SpatialReference object \"provide[s] services to represent\n ", "middle": "pe\n\nfrom django.contrib.gis.gdal.base import GDALBase\nfrom django.contrib.gis.gdal.error import SRSException\nfrom django.contrib.gis.gdal.prototypes import srs as capi\nfrom django.utils.encoding import force_bytes, force_str\n\n\ncl", "meta": {"filepath": "django/contrib/gis/gdal/srs.py", "language": "python", "file_size": 12392, "cut_index": 921, "middle_length": 229}} +{"prefix": "s import c_void_p, string_at\n\nfrom django.contrib.gis.gdal.error import GDALException, SRSException, check_err\nfrom django.contrib.gis.gdal.libgdal import lgdal\n\n\n# Helper routines for retrieving pointers and/or values from\n# arguments passed in by reference.\ndef arg_byref(args, offset=-1):\n \"Return the pointer argument's by-reference value.\"\n return args[offset]._obj.value\n\n\ndef ptr_byref(args, offset=-1):\n \"Return the pointer argument passed in by-reference.\"\n return args[offset]._obj\n\n\n# ### ", "suffix": ", cpl=cpl)\n ptr = ptr_byref(cargs, offset)\n return ptr.value\n else:\n return result\n\n\ndef check_string(result, func, cargs, offset=-1, str_result=False):\n \"\"\"\n Check the string output returned from the given function, and free\n", "middle": "String checking Routines ###\ndef check_const_string(result, func, cargs, offset=None, cpl=False):\n \"\"\"\n Similar functionality to `check_string`, but does not free the pointer.\n \"\"\"\n if offset:\n check_err(result", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/errcheck.py", "language": "python", "file_size": 4169, "cut_index": 614, "middle_length": 229}} +{"prefix": "totypes.errcheck import check_envelope\nfrom django.contrib.gis.gdal.prototypes.generation import (\n bool_output,\n const_string_output,\n double_output,\n geom_output,\n int_output,\n srs_output,\n string_output,\n void_output,\n)\n\n\n# ### Generation routines specific to this module ###\ndef env_func(f, argtypes):\n \"For getting OGREnvelopes.\"\n f.argtypes = argtypes\n f.restype = None\n f.errcheck = check_envelope\n return f\n\n\ndef pnt_func(f):\n \"For accessing point information.\"\n", "suffix": "on prototypes ###\n\n# GeoJSON routines.\nfrom_json = geom_output(lgdal.OGR_G_CreateGeometryFromJson, [c_char_p])\nto_json = string_output(\n lgdal.OGR_G_ExportToJson, [c_void_p], str_result=True, decoding=\"ascii\"\n)\nto_kml = string_output(\n lgdal.OGR_G_Ex", "middle": " return double_output(f, [c_void_p, c_int])\n\n\ndef topology_func(f):\n f.argtypes = [c_void_p, c_void_p]\n f.restype = c_int\n f.errcheck = lambda result, func, cargs: bool(result)\n return f\n\n\n# ### OGR_G ctypes functi", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/geom.py", "language": "python", "file_size": 5923, "cut_index": 716, "middle_length": 229}} +{"prefix": "al, std_call\nfrom django.contrib.gis.gdal.prototypes.generation import (\n const_string_output,\n double_output,\n int_output,\n srs_output,\n string_output,\n void_output,\n)\n\n\n# Shortcut generation for routines with known parameters.\ndef srs_double(f):\n \"\"\"\n Create a function prototype for the OSR routines that take\n the OSRSpatialReference object and return a double value.\n \"\"\"\n return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True)\n\n\ndef units_func(f):\n \"\"\"\n C", "suffix": "rs_output(std_call(\"OSRClone\"), [c_void_p])\nnew_srs = srs_output(std_call(\"OSRNewSpatialReference\"), [c_char_p])\nrelease_srs = void_output(lgdal.OSRRelease, [c_void_p], errcheck=False)\ndestroy_srs = void_output(\n std_call(\"OSRDestroySpatialReference\"), ", "middle": "reate a ctypes function prototype for OSR units functions, e.g.,\n OSRGetAngularUnits, OSRGetLinearUnits.\n \"\"\"\n return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True)\n\n\n# Creation & destruction.\nclone_srs = s", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/srs.py", "language": "python", "file_size": 3677, "cut_index": 614, "middle_length": 229}} +{"prefix": "rom django.contrib.gis.gdal.prototypes import raster as capi\n\n\nclass GDALRasterBase(GDALBase):\n \"\"\"\n Attributes that exist on both GDALRaster and GDALBand.\n \"\"\"\n\n @property\n def metadata(self):\n \"\"\"\n Return the metadata for this raster or band. The return value is a\n nested dictionary, where the first-level key is the metadata domain and\n the second-level is the metadata item names and values for that domain.\n \"\"\"\n # The initial metadata domain list c", "suffix": "ist(self._ptr)\n if meta_list:\n # The number of domains is unknown, so retrieve data until there\n # are no more values in the ctypes array.\n counter = 0\n domain = meta_list[counter]\n while domain", "middle": "ontains the default domain.\n # The default is returned if domain name is None.\n domain_list = [\"DEFAULT\"]\n\n # Get additional metadata domains from the raster.\n meta_list = capi.get_ds_metadata_domain_l", "meta": {"filepath": "django/contrib/gis/gdal/raster/base.py", "language": "python", "file_size": 2882, "cut_index": 563, "middle_length": 229}} +{"prefix": "rom django.utils.encoding import force_bytes, force_str\nfrom django.utils.functional import cached_property\n\n\nclass TransformPoint(list):\n indices = {\n \"origin\": (0, 3),\n \"scale\": (1, 5),\n \"skew\": (2, 4),\n }\n\n def __init__(self, raster, prop):\n x = raster.geotransform[self.indices[prop][0]]\n y = raster.geotransform[self.indices[prop][1]]\n super().__init__([x, y])\n self._raster = raster\n self._prop = prop\n\n @property\n def x(self):\n ", "suffix": "n self[1]\n\n @y.setter\n def y(self, value):\n gtf = self._raster.geotransform\n gtf[self.indices[self._prop][1]] = value\n self._raster.geotransform = gtf\n\n\nclass GDALRaster(GDALRasterBase):\n \"\"\"\n Wrap a raster GDAL Data Source", "middle": " return self[0]\n\n @x.setter\n def x(self, value):\n gtf = self._raster.geotransform\n gtf[self.indices[self._prop][0]] = value\n self._raster.geotransform = gtf\n\n @property\n def y(self):\n retur", "meta": {"filepath": "django/contrib/gis/gdal/raster/source.py", "language": "python", "file_size": 18418, "cut_index": 1331, "middle_length": 229}} +{"prefix": "spatial values from the\ndatabase.\n\"\"\"\n\nfrom decimal import Decimal\n\nfrom django.contrib.gis.measure import Area, Distance\nfrom django.db import models\n\n\nclass AreaField(models.FloatField):\n \"Wrapper for Area values.\"\n\n def __init__(self, geo_field):\n super().__init__()\n self.geo_field = geo_field\n\n def get_prep_value(self, value):\n if not isinstance(value, Area):\n raise ValueError(\"AreaField only accepts Area measurement objects.\")\n return value\n\n def get_d", "suffix": " value\n\n def from_db_value(self, value, expression, connection):\n if value is None:\n return\n # If the database returns a Decimal, convert it to a float as expected\n # by the Python geometric objects.\n if isinstance", "middle": "b_prep_value(self, value, connection, prepared=False):\n if value is None:\n return\n area_att = connection.ops.get_area_att_for_field(self.geo_field)\n return getattr(value, area_att) if area_att else", "meta": {"filepath": "django/contrib/gis/db/models/sql/conversion.py", "language": "python", "file_size": 2433, "cut_index": 563, "middle_length": 229}} +{"prefix": "\n DatabaseIntrospection,\n FlexibleFieldLookupDict,\n)\n\n\nclass GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):\n \"\"\"\n Subclass that includes updates the `base_data_types_reverse` dict\n for geometry field types.\n \"\"\"\n\n base_data_types_reverse = {\n **FlexibleFieldLookupDict.base_data_types_reverse,\n \"point\": \"GeometryField\",\n \"linestring\": \"GeometryField\",\n \"polygon\": \"GeometryField\",\n \"multipoint\": \"GeometryField\",\n \"multilinestring\": \"Geometry", "suffix": "etry_type(self, table_name, description):\n with self.connection.cursor() as cursor:\n # Querying the `geometry_columns` table to get additional metadata.\n cursor.execute(\n \"SELECT coord_dimension, srid, geometry_t", "middle": "Field\",\n \"multipolygon\": \"GeometryField\",\n \"geometrycollection\": \"GeometryField\",\n }\n\n\nclass SpatiaLiteIntrospection(DatabaseIntrospection):\n data_types_reverse = GeoFlexibleFieldLookupDict()\n\n def get_geom", "meta": {"filepath": "django/contrib/gis/db/backends/spatialite/introspection.py", "language": "python", "file_size": 3132, "cut_index": 614, "middle_length": 229}} +{"prefix": "Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*,\nOGR_Fld_* routines are relevant here.\n\"\"\"\n\nfrom ctypes import POINTER, c_char_p, c_double, c_int, c_long, c_uint, c_void_p\n\nfrom django.contrib.gis.gdal.envelope import OGREnvelope\nfrom django.contrib.gis.gdal.libgdal import lgdal\nfrom django.contrib.gis.gdal.prototypes.generation import (\n bool_output,\n const_string_output,\n double_output,\n geom_output,\n int64_output,\n int_output,\n srs_output,\n void_output,\n voidptr_output,\n)\n\nc_int_p = POINTER(c", "suffix": "p_all = void_output(lgdal.GDALDestroyDriverManager, [], errcheck=False)\nget_driver = voidptr_output(lgdal.GDALGetDriver, [c_int])\nget_driver_by_name = voidptr_output(\n lgdal.GDALGetDriverByName, [c_char_p], errcheck=False\n)\nget_driver_count = int_output", "middle": "_int) # shortcut type\n\nGDAL_OF_READONLY = 0x00\nGDAL_OF_UPDATE = 0x01\n\nGDAL_OF_ALL = 0x00\nGDAL_OF_RASTER = 0x02\nGDAL_OF_VECTOR = 0x04\n\n# Driver Routines\nregister_all = void_output(lgdal.GDALAllRegister, [], errcheck=False)\ncleanu", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/ds.py", "language": "python", "file_size": 4725, "cut_index": 614, "middle_length": 229}} +{"prefix": "rt partial\n\nfrom django.contrib.gis.gdal.libgdal import std_call\nfrom django.contrib.gis.gdal.prototypes.generation import (\n chararray_output,\n const_string_output,\n double_output,\n int_output,\n void_output,\n voidptr_output,\n)\n\n# For more detail about c function names and definitions see\n# https://gdal.org/api/raster_c_api.html\n# https://gdal.org/doxygen/gdalwarper_8h.html\n# https://gdal.org/api/gdal_utils.html\n\n# Prepare partial functions that use cpl error codes\nvoid_output = partial(vo", "suffix": "c_char_p, c_int, c_int, c_int, c_int, c_void_p]\n)\nopen_ds = voidptr_output(std_call(\"GDALOpen\"), [c_char_p, c_int])\nclose_ds = void_output(std_call(\"GDALClose\"), [c_void_p], errcheck=False)\nflush_ds = int_output(std_call(\"GDALFlushCache\"), [c_void_p])\ncopy", "middle": "id_output, cpl=True)\nconst_string_output = partial(const_string_output, cpl=True)\ndouble_output = partial(double_output, cpl=True)\n\n# Raster Data Source Routines\ncreate_ds = voidptr_output(\n std_call(\"GDALCreate\"), [c_void_p, ", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/raster.py", "language": "python", "file_size": 5571, "cut_index": 716, "middle_length": 229}} +{"prefix": "_int16,\n c_int32,\n c_int64,\n c_ubyte,\n c_uint16,\n c_uint32,\n c_uint64,\n)\n\n# See https://gdal.org/api/raster_c_api.html#_CPPv412GDALDataType\nGDAL_PIXEL_TYPES = {\n 0: \"GDT_Unknown\", # Unknown or unspecified type\n 1: \"GDT_Byte\", # Eight bit unsigned integer\n 2: \"GDT_UInt16\", # Sixteen bit unsigned integer\n 3: \"GDT_Int16\", # Sixteen bit signed integer\n 4: \"GDT_UInt32\", # Thirty-two bit unsigned integer\n 5: \"GDT_Int32\", # Thirty-two bit signed integer\n 6: \"GDT_Float32", "suffix": "64\", # Complex Float64\n 12: \"GDT_UInt64\", # 64 bit unsigned integer (GDAL 3.5+).\n 13: \"GDT_Int64\", # 64 bit signed integer (GDAL 3.5+).\n 14: \"GDT_Int8\", # 8 bit signed integer (GDAL 3.7+).\n}\n\n# A list of gdal datatypes that are integers.\nGDAL_", "middle": "\", # Thirty-two bit floating point\n 7: \"GDT_Float64\", # Sixty-four bit floating point\n 8: \"GDT_CInt16\", # Complex Int16\n 9: \"GDT_CInt32\", # Complex Int32\n 10: \"GDT_CFloat32\", # Complex Float32\n 11: \"GDT_CFloat", "meta": {"filepath": "django/contrib/gis/gdal/raster/const.py", "language": "python", "file_size": 3283, "cut_index": 614, "middle_length": 229}} +{"prefix": "l import find_library\n\nfrom django.contrib.gis.gdal.error import GDALException\nfrom django.core.exceptions import ImproperlyConfigured\n\nlogger = logging.getLogger(\"django.contrib.gis\")\n\n# Custom library path set?\ntry:\n from django.conf import settings\n\n lib_path = settings.GDAL_LIBRARY_PATH\nexcept (AttributeError, ImportError, ImproperlyConfigured, OSError):\n lib_path = None\n\nif lib_path:\n lib_names = None\nelif os.name == \"nt\":\n # Windows NT shared libraries\n lib_names = [\n \"gdal313", "suffix": " *NIX library names.\n lib_names = [\n \"gdal\",\n \"GDAL\",\n \"gdal3.13.0\",\n \"gdal3.12.0\",\n \"gdal3.11.0\",\n \"gdal3.10.0\",\n \"gdal3.9.0\",\n \"gdal3.8.0\",\n \"gdal3.7.0\",\n \"gdal3.6.0\",\n \"gdal", "middle": "\",\n \"gdal312\",\n \"gdal311\",\n \"gdal310\",\n \"gdal309\",\n \"gdal308\",\n \"gdal307\",\n \"gdal306\",\n \"gdal305\",\n \"gdal304\",\n \"gdal303\",\n ]\nelif os.name == \"posix\":\n #", "meta": {"filepath": "django/contrib/gis/gdal/libgdal.py", "language": "python", "file_size": 3660, "cut_index": 614, "middle_length": 229}} +{"prefix": "er.base import GDALRasterBase\nfrom django.contrib.gis.shortcuts import numpy\nfrom django.utils.encoding import force_str\n\nfrom .const import (\n GDAL_COLOR_TYPES,\n GDAL_INTEGER_TYPES,\n GDAL_PIXEL_TYPES,\n GDAL_TO_CTYPES,\n)\n\n\nclass GDALBand(GDALRasterBase):\n \"\"\"\n Wrap a GDAL raster band, needs to be obtained from a GDALRaster object.\n \"\"\"\n\n def __init__(self, source, index):\n self.source = source\n self._ptr = capi.get_ds_raster_band(source._ptr, index)\n\n def _flush(self", "suffix": " True\n\n @property\n def description(self):\n \"\"\"\n Return the description string of the band.\n \"\"\"\n return force_str(capi.get_band_description(self._ptr))\n\n @property\n def width(self):\n \"\"\"\n Width (X axis)", "middle": "):\n \"\"\"\n Call the flush method on the Band's parent raster and force a refresh\n of the statistics attribute when requested the next time.\n \"\"\"\n self.source._flush()\n self._stats_refresh =", "meta": {"filepath": "django/contrib/gis/gdal/raster/band.py", "language": "python", "file_size": 8343, "cut_index": 716, "middle_length": 229}} +{"prefix": "ypes import POINTER, c_bool, c_char_p, c_double, c_int, c_int64, c_void_p\nfrom functools import partial\n\nfrom django.contrib.gis.gdal.prototypes.errcheck import (\n check_arg_errcode,\n check_const_string,\n check_errcode,\n check_geom,\n check_geom_offset,\n check_pointer,\n check_srs,\n check_str_arg,\n check_string,\n)\n\n\nclass gdal_char_p(c_char_p):\n pass\n\n\ndef bool_output(func, argtypes, errcheck=None):\n \"\"\"Generate a ctypes function that returns a boolean value.\"\"\"\n func.argty", "suffix": " a double value.\"\n func.argtypes = argtypes\n func.restype = c_double\n if errcheck:\n func.errcheck = partial(check_arg_errcode, cpl=cpl)\n if strarg:\n func.errcheck = check_str_arg\n return func\n\n\ndef geom_output(func, argtypes, o", "middle": "pes = argtypes\n func.restype = c_bool\n if errcheck:\n func.errcheck = errcheck\n return func\n\n\ndef double_output(func, argtypes, errcheck=False, strarg=False, cpl=False):\n \"Generate a ctypes function that returns", "meta": {"filepath": "django/contrib/gis/gdal/prototypes/generation.py", "language": "python", "file_size": 4888, "cut_index": 614, "middle_length": 229}} +{"prefix": "jango.db.models.query_utils import PathInfo\nfrom django.db.models.sql import AND\nfrom django.db.models.sql.where import WhereNode\nfrom django.db.models.utils import AltersData\nfrom django.utils.functional import cached_property\n\n\nclass GenericForeignKey(FieldCacheMixin, Field):\n \"\"\"\n Provide a generic many-to-one relation through the ``content_type`` and\n ``object_id`` fields.\n\n This class also doubles as an accessor to the related object (similar to\n ForwardManyToOneDescriptor) by adding its", "suffix": "True\n ):\n super().__init__(editable=False)\n self.ct_field = ct_field\n self.fk_field = fk_field\n self.for_concrete_model = for_concrete_model\n self.is_relation = True\n\n def contribute_to_class(self, cls, name, **kwar", "middle": "elf as a model attribute.\n \"\"\"\n\n many_to_many = False\n many_to_one = True\n one_to_many = False\n one_to_one = False\n\n def __init__(\n self, ct_field=\"content_type\", fk_field=\"object_id\", for_concrete_model=", "meta": {"filepath": "django/contrib/contenttypes/fields.py", "language": "python", "file_size": 32976, "cut_index": 1331, "middle_length": 229}} +{"prefix": " c_byte, c_double, c_uint\n\nfrom django.contrib.gis.geos import prototypes as capi\nfrom django.contrib.gis.geos.base import GEOSBase\nfrom django.contrib.gis.geos.error import GEOSException\nfrom django.contrib.gis.geos.libgeos import CS_PTR, geos_version_tuple\nfrom django.contrib.gis.shortcuts import numpy\n\n\nclass GEOSCoordSeq(GEOSBase):\n \"The internal representation of a list of coordinates inside a Geometry.\"\n\n ptr_type = CS_PTR\n\n def __init__(self, ptr, z=False):\n \"Initialize from a GEOS po", "suffix": "rdinate sequence should initialize with a CS_PTR.\")\n self._ptr = ptr\n self._z = z\n\n def __iter__(self):\n \"Iterate over each point in the coordinate sequence.\"\n for i in range(self.size):\n yield self[i]\n\n def __l", "middle": "inter.\"\n # TODO when dropping support for GEOS 3.13 the z argument can be\n # deprecated in favor of using the GEOS function GEOSCoordSeq_hasZ.\n if not isinstance(ptr, CS_PTR):\n raise TypeError(\"Coo", "meta": {"filepath": "django/contrib/gis/geos/coordseq.py", "language": "python", "file_size": 8812, "cut_index": 716, "middle_length": 229}} +{"prefix": "uctible\nfrom django.utils.encoding import force_bytes, force_str\n\n\nclass GEOSGeometryBase(GEOSBase):\n _GEOS_CLASSES = None\n\n ptr_type = GEOM_PTR\n destructor = capi.destroy_geom\n has_cs = False # Only Point, LineString, LinearRing have coordinate sequences\n\n def __init__(self, ptr, cls):\n self._ptr = ptr\n\n # Setting the class type (e.g., Point, Polygon, etc.)\n if type(self) in (GEOSGeometryBase, GEOSGeometry):\n if cls is None:\n if GEOSGeometryBas", "suffix": "ring,\n MultiPoint,\n MultiPolygon,\n )\n from .linestring import LinearRing, LineString\n from .point import Point\n from .polygon import P", "middle": "e._GEOS_CLASSES is None:\n # Inner imports avoid import conflicts with GEOSGeometry.\n from .collections import (\n GeometryCollection,\n MultiLineSt", "meta": {"filepath": "django/contrib/gis/geos/geometry.py", "language": "python", "file_size": 27034, "cut_index": 1331, "middle_length": 229}} +{"prefix": "odule that holds classes for performing I/O operations on GEOS geometry\nobjects. Specifically, this has Python implementations of WKB/WKT\nreader and writer classes.\n\"\"\"\n\nfrom django.contrib.gis.geos.geometry import GEOSGeometry\nfrom django.contrib.gis.geos.prototypes.io import (\n WKBWriter,\n WKTWriter,\n _WKBReader,\n _WKTReader,\n)\n\n__all__ = [\"WKBWriter\", \"WKTWriter\", \"WKBReader\", \"WKTReader\"]\n\n\n# Public classes for (WKB|WKT)Reader, which return GEOSGeometry\nclass WKBReader(_WKBReader):\n def r", "suffix": ":\n \"Return a GEOSGeometry for the given WKB buffer.\"\n return GEOSGeometry(super().read(wkb))\n\n\nclass WKTReader(_WKTReader):\n def read(self, wkt):\n \"Return a GEOSGeometry for the given WKT string.\"\n return GEOSGeometry(super()", "middle": "ead(self, wkb)", "meta": {"filepath": "django/contrib/gis/geos/io.py", "language": "python", "file_size": 799, "cut_index": 517, "middle_length": 14}} +{"prefix": " which provides complete list interface.\n Derived classes must call ListMixin's __init__() function\n and implement the following:\n\n function _get_single_external(self, i):\n Return single item with index i for general use.\n The index i will always satisfy 0 <= i < len(self).\n\n function _get_single_internal(self, i):\n Same as above, but for use within the class [Optional]\n Note that if _get_single_internal and _get_single_internal return\n different types of objec", "suffix": "le_internal.\n Therefore, it is necessary to cache the values in a temporary:\n temp = list(items)\n before clobbering the original storage.\n\n function _set_single(self, i, value):\n Set the single item at index i to value [O", "middle": "ts, _set_list must distinguish\n between the two and handle each appropriately.\n\n function _set_list(self, length, items):\n Recreate the entire object.\n\n NOTE: items may be a generator which calls _get_sing", "meta": {"filepath": "django/contrib/gis/geos/mutable_list.py", "language": "python", "file_size": 10122, "cut_index": 921, "middle_length": 229}} +{"prefix": "g import LinearRing\n\n\nclass Polygon(GEOSGeometry):\n _minlength = 1\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize on an exterior ring and a sequence of holes (both\n instances may be either LinearRing instances, or a tuple/list\n that may be constructed into a LinearRing).\n\n Examples of initialization, where shell, hole1, and hole2 are\n valid LinearRing geometries:\n >>> from django.contrib.gis.geos import LinearRing, Polygon\n >>> shell = h", "suffix": "(10, 10), (10, 0), (0, 0)),\n ... ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))\n \"\"\"\n if not args:\n super().__init__(self._create_polygon(0, None), **kwargs)\n return\n\n # Getting the ext_ring and i", "middle": "ole1 = hole2 = LinearRing()\n >>> poly = Polygon(shell, hole1, hole2)\n >>> poly = Polygon(shell, (hole1, hole2))\n\n >>> # Example where a tuple parameters are used:\n >>> poly = Polygon(((0, 0), (0, 10), ", "meta": {"filepath": "django/contrib/gis/geos/polygon.py", "language": "python", "file_size": 6710, "cut_index": 716, "middle_length": 229}} +{"prefix": "ule contains all of the GEOS ctypes function prototypes. Each\nprototype handles the interaction between the GEOS library and Python\nvia ctypes.\n\"\"\"\n\nfrom django.contrib.gis.geos.prototypes.coordseq import ( # NOQA\n create_cs,\n cs_clone,\n cs_getdims,\n cs_getm,\n cs_getordinate,\n cs_getsize,\n cs_getx,\n cs_gety,\n cs_getz,\n cs_hasm,\n cs_is_ccw,\n cs_setm,\n cs_setordinate,\n cs_setx,\n cs_sety,\n cs_setz,\n get_cs,\n)\nfrom django.contrib.gis.geos.prototypes.geom impor", "suffix": "rmalize,\n geos_set_srid,\n geos_type,\n geos_typeid,\n get_dims,\n get_extring,\n get_geomn,\n get_intring,\n get_nrings,\n get_num_coords,\n get_num_geoms,\n)\nfrom django.contrib.gis.geos.prototypes.misc import * # NOQA\nfrom django.co", "middle": "t ( # NOQA\n create_collection,\n create_empty_polygon,\n create_linearring,\n create_linestring,\n create_point,\n create_polygon,\n destroy_geom,\n geom_clone,\n geos_get_srid,\n geos_makevalid,\n geos_no", "meta": {"filepath": "django/contrib/gis/geos/prototypes/__init__.py", "language": "python", "file_size": 1489, "cut_index": 524, "middle_length": 229}} +{"prefix": "rt (\n CS_PTR,\n GEOM_PTR,\n GEOSFuncFactory,\n)\nfrom django.contrib.gis.geos.prototypes.errcheck import (\n GEOSException,\n check_predicate,\n last_arg_byref,\n)\n\n\n# ## Error-checking routines specific to coordinate sequences. ##\ndef check_cs_op(result, func, cargs):\n \"Check the status code of a coordinate sequence operation.\"\n if result == 0:\n raise GEOSException(\"Could not set value on coordinate sequence\")\n else:\n return result\n\n\ndef check_cs_get(result, func, cargs):\n ", "suffix": "Int(GEOSFuncFactory):\n \"For coordinate sequence routines that return an integer.\"\n\n argtypes = [CS_PTR, POINTER(c_uint)]\n restype = c_int\n errcheck = staticmethod(check_cs_get)\n\n\nclass CsOperation(GEOSFuncFactory):\n \"For coordinate sequence ", "middle": " \"Check the coordinate sequence retrieval.\"\n check_cs_op(result, func, cargs)\n # Object in by reference, return its value.\n return last_arg_byref(cargs)\n\n\n# ## Coordinate sequence prototype factory classes. ##\nclass Cs", "meta": {"filepath": "django/contrib/gis/geos/prototypes/coordseq.py", "language": "python", "file_size": 3478, "cut_index": 614, "middle_length": 229}} +{"prefix": "pes.geom import c_uchar_p, geos_char_p\nfrom django.utils.encoding import force_bytes\nfrom django.utils.functional import SimpleLazyObject\n\n\n# ### The WKB/WKT Reader/Writer structures and pointers ###\nclass WKTReader_st(Structure):\n pass\n\n\nclass WKTWriter_st(Structure):\n pass\n\n\nclass WKBReader_st(Structure):\n pass\n\n\nclass WKBWriter_st(Structure):\n pass\n\n\nWKT_READ_PTR = POINTER(WKTReader_st)\nWKT_WRITE_PTR = POINTER(WKTWriter_st)\nWKB_READ_PTR = POINTER(WKBReader_st)\nWKB_WRITE_PTR = POINTER(WKBReade", "suffix": "ry(\n \"GEOSWKTReader_read\",\n argtypes=[WKT_READ_PTR, c_char_p],\n restype=GEOM_PTR,\n errcheck=check_geom,\n)\n# WKTWriter routines\nwkt_writer_create = GEOSFuncFactory(\"GEOSWKTWriter_create\", restype=WKT_WRITE_PTR)\nwkt_writer_destroy = GEOSFuncFacto", "middle": "r_st)\n\n# WKTReader routines\nwkt_reader_create = GEOSFuncFactory(\"GEOSWKTReader_create\", restype=WKT_READ_PTR)\nwkt_reader_destroy = GEOSFuncFactory(\"GEOSWKTReader_destroy\", argtypes=[WKT_READ_PTR])\n\nwkt_reader_read = GEOSFuncFacto", "meta": {"filepath": "django/contrib/gis/geos/prototypes/io.py", "language": "python", "file_size": 11469, "cut_index": 921, "middle_length": 229}} +{"prefix": "e GEOS ctypes prototype functions for the\nunary and binary predicate operations on geometries.\n\"\"\"\n\nfrom ctypes import c_byte, c_char_p, c_double\n\nfrom django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory\nfrom django.contrib.gis.geos.prototypes.errcheck import check_predicate\n\n\n# ## Binary & unary predicate factories ##\nclass UnaryPredicate(GEOSFuncFactory):\n \"For GEOS unary predicate functions.\"\n\n argtypes = [GEOM_PTR]\n restype = c_byte\n errcheck = staticmethod(check_predicate)\n\n\ncl", "suffix": "closed = UnaryPredicate(\"GEOSisClosed\")\ngeos_isempty = UnaryPredicate(\"GEOSisEmpty\")\ngeos_isring = UnaryPredicate(\"GEOSisRing\")\ngeos_issimple = UnaryPredicate(\"GEOSisSimple\")\ngeos_isvalid = UnaryPredicate(\"GEOSisValid\")\n\n# ## Binary Predicates ##\ngeos_cont", "middle": "ass BinaryPredicate(UnaryPredicate):\n \"For GEOS binary predicate functions.\"\n\n argtypes = [GEOM_PTR, GEOM_PTR]\n\n\n# ## Unary Predicates ##\ngeos_hasz = UnaryPredicate(\"GEOSHasZ\")\ngeos_hasm = UnaryPredicate(\"GEOSHasM\")\ngeos_is", "meta": {"filepath": "django/contrib/gis/geos/prototypes/predicates.py", "language": "python", "file_size": 1701, "cut_index": 537, "middle_length": 229}} +{"prefix": "wkt_regex\n\n\ndef fromfile(file_h):\n \"\"\"\n Given a string file name, returns a GEOSGeometry. The file may contain WKB,\n WKT, or HEX.\n \"\"\"\n # If given a file name, get a real handle.\n if isinstance(file_h, str):\n with open(file_h, \"rb\") as file_h:\n buf = file_h.read()\n else:\n buf = file_h.read()\n\n # If we get WKB need to wrap in memoryview(), so run through regexes.\n if isinstance(buf, bytes):\n try:\n decoded = buf.decode()\n except Unic", "suffix": " if wkt_regex.match(decoded) or hex_regex.match(decoded):\n return GEOSGeometry(decoded)\n else:\n return GEOSGeometry(buf)\n\n return GEOSGeometry(memoryview(buf))\n\n\ndef fromstr(string, **kwargs):\n \"Given a string value, re", "middle": "odeDecodeError:\n pass\n else:\n ", "meta": {"filepath": "django/contrib/gis/geos/factory.py", "language": "python", "file_size": 961, "cut_index": 582, "middle_length": 52}} +{"prefix": "ry import GEOSGeometry, LinearGeometryMixin\nfrom django.contrib.gis.geos.point import Point\nfrom django.contrib.gis.shortcuts import numpy\n\n\nclass LineString(LinearGeometryMixin, GEOSGeometry):\n _init_func = capi.create_linestring\n _minlength = 2\n has_cs = True\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize on the given sequence: may take lists, tuples, NumPy arrays\n of X,Y pairs, or Point objects. If Point objects are used, ownership is\n _not_ transferred to", "suffix": " \"\"\"\n # If only one argument provided, set the coords array appropriately\n if len(args) == 1:\n coords = args[0]\n else:\n coords = args\n\n if not (\n isinstance(coords, (tuple, list))\n ", "middle": " the LineString object.\n\n Examples:\n ls = LineString((1, 1), (2, 2))\n ls = LineString([(1, 1), (2, 2)])\n ls = LineString(array([(1, 1), (2, 2)]))\n ls = LineString(Point(1, 1), Point(2, 2))\n ", "meta": {"filepath": "django/contrib/gis/geos/linestring.py", "language": "python", "file_size": 6367, "cut_index": 716, "middle_length": 229}} +{"prefix": "e\nfrom .prototypes import prepared as capi\n\n\nclass PreparedGeometry(GEOSBase):\n \"\"\"\n A geometry that is prepared for performing certain operations.\n At the moment this includes the contains covers, and intersects\n operations.\n \"\"\"\n\n ptr_type = capi.PREPGEOM_PTR\n destructor = capi.prepared_destroy\n\n def __init__(self, geom):\n # Keeping a reference to the original geometry object to prevent it\n # from being garbage collected which could then crash the prepared one\n ", "suffix": "self, other):\n return capi.prepared_contains(self.ptr, other.ptr)\n\n def contains_properly(self, other):\n return capi.prepared_contains_properly(self.ptr, other.ptr)\n\n def covers(self, other):\n return capi.prepared_covers(self.ptr", "middle": " # See #21662\n self._base_geom = geom\n from .geometry import GEOSGeometry\n\n if not isinstance(geom, GEOSGeometry):\n raise TypeError\n self.ptr = capi.geos_prepare(geom.ptr)\n\n def contains(", "meta": {"filepath": "django/contrib/gis/geos/prepared.py", "language": "python", "file_size": 1577, "cut_index": 537, "middle_length": 229}} +{"prefix": "ort CS_PTR, GEOM_PTR, GEOSFuncFactory\nfrom django.contrib.gis.geos.prototypes.errcheck import (\n check_geom,\n check_minus_one,\n check_string,\n)\n\n# This is the return type used by binary output (WKB, HEX) routines.\nc_uchar_p = POINTER(c_ubyte)\n\n\n# We create a simple subclass of c_char_p here because when the response\n# type is set to c_char_p, you get a _Python_ string and there's no way\n# to access the string's address inside the error checking function.\n# In other words, you can't free the memory ", "suffix": "ss geos_char_p(c_char_p):\n pass\n\n\n# ### ctypes factory classes ###\nclass GeomOutput(GEOSFuncFactory):\n \"For GEOS routines that return a geometry.\"\n\n restype = GEOM_PTR\n errcheck = staticmethod(check_geom)\n\n\nclass IntFromGeom(GEOSFuncFactory):\n ", "middle": "allocated inside GEOS. Previously,\n# the return type would just be omitted and the integer address would be\n# used -- but this allows us to be specific in the function definition and\n# keeps the reference so it may be free'd.\ncla", "meta": {"filepath": "django/contrib/gis/geos/prototypes/geom.py", "language": "python", "file_size": 3400, "cut_index": 614, "middle_length": 229}} +{"prefix": "types import c_byte\n\nfrom django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory\nfrom django.contrib.gis.geos.prototypes.errcheck import check_predicate\n\n# Prepared geometry constructor and destructors.\ngeos_prepare = GEOSFuncFactory(\"GEOSPrepare\", argtypes=[GEOM_PTR], restype=PREPGEOM_PTR)\nprepared_destroy = GEOSFuncFactory(\"GEOSPreparedGeom_destroy\", argtypes=[PREPGEOM_PTR])\n\n\n# Prepared geometry binary predicate support.\nclass PreparedPredicate(GEOSFuncFactory):\n argtypes = [PR", "suffix": ")\nprepared_covers = PreparedPredicate(\"GEOSPreparedCovers\")\nprepared_crosses = PreparedPredicate(\"GEOSPreparedCrosses\")\nprepared_disjoint = PreparedPredicate(\"GEOSPreparedDisjoint\")\nprepared_intersects = PreparedPredicate(\"GEOSPreparedIntersects\")\nprepared", "middle": "EPGEOM_PTR, GEOM_PTR]\n restype = c_byte\n errcheck = staticmethod(check_predicate)\n\n\nprepared_contains = PreparedPredicate(\"GEOSPreparedContains\")\nprepared_contains_properly = PreparedPredicate(\"GEOSPreparedContainsProperly\"", "meta": {"filepath": "django/contrib/gis/geos/prototypes/prepared.py", "language": "python", "file_size": 1175, "cut_index": 518, "middle_length": 229}} +{"prefix": "lities, including\nget_pointer_arr(), and GEOM_PTR.\n\"\"\"\n\nimport logging\nimport os\nfrom ctypes import CDLL, CFUNCTYPE, POINTER, Structure, c_char_p\nfrom ctypes.util import find_library\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.functional import SimpleLazyObject, cached_property\nfrom django.utils.version import get_version_tuple\n\nlogger = logging.getLogger(\"django.contrib.gis\")\n\n\ndef load_geos():\n # Custom library path set?\n try:\n from django.conf import settings\n\n", "suffix": "lib_names = None\n elif os.name == \"nt\":\n # Windows NT libraries\n lib_names = [\"geos_c\", \"libgeos_c-1\"]\n elif os.name == \"posix\":\n # *NIX libraries\n lib_names = [\"geos_c\", \"GEOS\"]\n else:\n raise ImportError('Unsupp", "middle": " lib_path = settings.GEOS_LIBRARY_PATH\n except (AttributeError, ImportError, ImproperlyConfigured, OSError):\n lib_path = None\n\n # Setting the appropriate names for the GEOS-C library.\n if lib_path:\n ", "meta": {"filepath": "django/contrib/gis/geos/libgeos.py", "language": "python", "file_size": 5186, "cut_index": 716, "middle_length": 229}} +{"prefix": "ype functions.\n\"\"\"\n\nfrom ctypes import c_void_p, string_at\n\nfrom django.contrib.gis.geos.error import GEOSException\nfrom django.contrib.gis.geos.libgeos import GEOSFuncFactory\n\n# Getting the `free` routine used to free the memory allocated for\n# string pointers returned by GEOS.\nfree = GEOSFuncFactory(\"GEOSFree\")\nfree.argtypes = [c_void_p]\n\n\ndef last_arg_byref(args):\n \"Return the last C argument's value by reference.\"\n return args[-1]._obj.value\n\n\ndef check_dbl(result, func, cargs):\n \"\"\"\n Check ", "suffix": "cargs)\n\n\ndef check_geom(result, func, cargs):\n \"Error checking on routines that return Geometries.\"\n if not result:\n raise GEOSException(\n 'Error encountered checking Geometry returned from GEOS C function \"%s\".'\n % func.", "middle": "the status code and returns the double value passed in by reference.\n \"\"\"\n # Checking the status code\n if result != 1:\n return None\n # Double passed in by reference, return its value.\n return last_arg_byref(", "meta": {"filepath": "django/contrib/gis/geos/prototypes/errcheck.py", "language": "python", "file_size": 2802, "cut_index": 563, "middle_length": 229}} +{"prefix": "totypes as capi\nfrom django.contrib.gis.geos.error import GEOSException\nfrom django.contrib.gis.geos.geometry import GEOSGeometry\n\n\nclass Point(GEOSGeometry):\n _minlength = 2\n _maxlength = 3\n has_cs = True\n\n def __init__(self, x=None, y=None, z=None, srid=None):\n \"\"\"\n The Point object may be initialized with either a tuple, or individual\n parameters.\n\n For example:\n >>> p = Point((5, 23)) # 2D point, passed in as a tuple\n >>> p = Point(5, 23, 8) # 3D p", "suffix": "ds = x\n elif isinstance(x, (float, int)) and isinstance(y, (float, int)):\n # Here X, Y, and (optionally) Z were passed in individually, as\n # parameters.\n if isinstance(z, (float, int)):\n coords = [x, ", "middle": "oint, passed as individual parameters\n \"\"\"\n if x is None:\n coords = []\n elif isinstance(x, (tuple, list)):\n # Here a tuple or list was passed in under the `x` parameter.\n coor", "meta": {"filepath": "django/contrib/gis/geos/point.py", "language": "python", "file_size": 4790, "cut_index": 614, "middle_length": 229}} +{"prefix": "eString, mark_safe\nfrom django.utils.text import capfirst\nfrom django.utils.translation import gettext as _\n\nfrom .base import InclusionAdminNode\n\nregister = Library()\n\n\n@register.simple_tag\ndef paginator_number(cl, i):\n \"\"\"\n Generate an individual page index link in a paginated list.\n \"\"\"\n if i == cl.paginator.ELLIPSIS:\n return format_html(\"{} \", cl.paginator.ELLIPSIS)\n elif i == cl.page_num:\n return format_html(\n '{} ", "suffix": "te the series of links to the pages in a paginated list.\n \"\"\"\n pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page\n page_range = (\n cl.paginator.get_elided_page_range(cl.page_num) if pagination_required else []\n", "middle": "',\n i,\n )\n else:\n return format_html(\n '{} ',\n cl.get_query_string({PAGE_VAR: i}),\n i,\n )\n\n\ndef pagination(cl):\n \"\"\"\n Genera", "meta": {"filepath": "django/contrib/admin/templatetags/admin_list.py", "language": "python", "file_size": 19476, "cut_index": 1331, "middle_length": 229}} +{"prefix": ",\n)\nfrom django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist\nfrom django.db import connections, models, router, transaction\nfrom django.utils.encoding import force_str\n\n\n# LayerMapping exceptions.\nclass LayerMapError(Exception):\n pass\n\n\nclass InvalidString(LayerMapError):\n pass\n\n\nclass InvalidDecimal(LayerMapError):\n pass\n\n\nclass InvalidInteger(LayerMapError):\n pass\n\n\nclass MissingForeignKey(LayerMapError):\n pass\n\n\nclass LayerMapping:\n \"A class that maps OGR Layers to GeoDj", "suffix": "ype(\"Point25D\").num: OGRGeomType(\"MultiPoint25D\"),\n OGRGeomType(\"LineString25D\").num: OGRGeomType(\"MultiLineString25D\"),\n OGRGeomType(\"Polygon25D\").num: OGRGeomType(\"MultiPolygon25D\"),\n }\n # Acceptable Django field types and correspondi", "middle": "ango Models.\"\n\n # Acceptable 'base' types for a multi-geometry type.\n MULTI_TYPES = {\n 1: OGRGeomType(\"MultiPoint\"),\n 2: OGRGeomType(\"MultiLineString\"),\n 3: OGRGeomType(\"MultiPolygon\"),\n OGRGeomT", "meta": {"filepath": "django/contrib/gis/utils/layermapping.py", "language": "python", "file_size": 29093, "cut_index": 1331, "middle_length": 229}} +{"prefix": "DataSource\nfrom django.contrib.gis.gdal.field import (\n OFTDate,\n OFTDateTime,\n OFTInteger,\n OFTInteger64,\n OFTReal,\n OFTString,\n OFTTime,\n)\n\n\ndef mapping(data_source, geom_name=\"geom\", layer_key=0, multi_geom=False):\n \"\"\"\n Given a DataSource, generate a dictionary that may be used\n for invoking the LayerMapping utility.\n\n Keyword Arguments:\n `geom_name` => The name of the geometry field to use for the model.\n\n `layer_key` => The key specifying which layer in the Dat", "suffix": "a_source, str):\n # Instantiating the DataSource from the string.\n data_source = DataSource(data_source)\n elif isinstance(data_source, DataSource):\n pass\n else:\n raise TypeError(\n \"Data source parameter must be a", "middle": "aSource to use;\n defaults to 0 (the first layer). May be an integer index or a string\n identifier for the layer.\n\n `multi_geom` => Boolean (default: False) - specify as multigeometry.\n \"\"\"\n if isinstance(dat", "meta": {"filepath": "django/contrib/gis/utils/ogrinspect.py", "language": "python", "file_size": 9157, "cut_index": 716, "middle_length": 229}} +{"prefix": "pps\nfrom django.conf import settings\nfrom django.contrib.redirects.models import Redirect\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponseGone, HttpResponsePermanentRedirect\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass RedirectFallbackMiddleware(MiddlewareMixin):\n # Defined as class-level attributes to be subclassing-friendly.\n response_gone_class = HttpResponseGone\n response_redi", "suffix": "iddleware when \"\n \"django.contrib.sites is not installed.\"\n )\n super().__init__(get_response)\n\n def process_response(self, request, response):\n # No need to check for a redirect for non-404 responses.\n if r", "middle": "rect_class = HttpResponsePermanentRedirect\n\n def __init__(self, get_response):\n if not apps.is_installed(\"django.contrib.sites\"):\n raise ImproperlyConfigured(\n \"You cannot use RedirectFallbackM", "meta": {"filepath": "django/contrib/redirects/middleware.py", "language": "python", "file_size": 1921, "cut_index": 537, "middle_length": 229}} +{"prefix": "gration(migrations.Migration):\n dependencies = [\n (\"sites\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"Redirect\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\n ", "suffix": " ),\n (\n \"old_path\",\n models.CharField(\n help_text=(\n \"This should be an absolute path, excluding the domain \"\n \"name. Ex", "middle": " \"site\",\n models.ForeignKey(\n to=\"sites.Site\",\n on_delete=models.CASCADE,\n verbose_name=\"site\",\n ),\n ", "meta": {"filepath": "django/contrib/redirects/migrations/0001_initial.py", "language": "python", "file_size": 2101, "cut_index": 563, "middle_length": 229}} +{"prefix": "contrib.admindocs import views\nfrom django.urls import path, re_path\n\nurlpatterns = [\n path(\n \"\",\n views.BaseAdminDocsView.as_view(template_name=\"admin_doc/index.html\"),\n name=\"django-admindocs-docroot\",\n ),\n path(\n \"bookmarklets/\",\n views.BookmarkletsView.as_view(),\n name=\"django-admindocs-bookmarklets\",\n ),\n path(\n \"tags/\",\n views.TemplateTagIndexView.as_view(),\n name=\"django-admindocs-tags\",\n ),\n path(\n \"filters/\",", "suffix": " \"views//\",\n views.ViewDetailView.as_view(),\n name=\"django-admindocs-views-detail\",\n ),\n path(\n \"models/\",\n views.ModelIndexView.as_view(),\n name=\"django-admindocs-models-index\",\n ),\n re_path(\n ", "middle": "\n views.TemplateFilterIndexView.as_view(),\n name=\"django-admindocs-filters\",\n ),\n path(\n \"views/\",\n views.ViewIndexView.as_view(),\n name=\"django-admindocs-views-index\",\n ),\n path(\n ", "meta": {"filepath": "django/contrib/admindocs/urls.py", "language": "python", "file_size": 1309, "cut_index": 524, "middle_length": 229}} +{"prefix": "ls import reverse\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.safestring import mark_safe\n\ntry:\n import docutils.core\n import docutils.nodes\n import docutils.parsers.rst.roles\n import docutils.writers\nexcept ImportError:\n docutils_is_available = False\nelse:\n docutils_is_available = True\n\n\ndef get_view_name(view_func):\n if hasattr(view_func, \"view_class\"):\n klass = view_func.view_class\n return f\"{klass.__module__}.{klass.__qualname__}\"\n mod_n", "suffix": "eturn (title, body, metadata).\n \"\"\"\n if not docstring:\n return \"\", \"\", {}\n docstring = cleandoc(docstring)\n parts = re.split(r\"\\n{2,}\", docstring)\n title = parts[0]\n if len(parts) == 1:\n body = \"\"\n metadata = {}\n e", "middle": "ame = view_func.__module__\n view_name = getattr(view_func, \"__qualname__\", view_func.__class__.__name__)\n return mod_name + \".\" + view_name\n\n\ndef parse_docstring(docstring):\n \"\"\"\n Parse out the parts of a docstring. R", "meta": {"filepath": "django/contrib/admindocs/utils.py", "language": "python", "file_size": 8400, "cut_index": 716, "middle_length": 229}} +{"prefix": " import GEOSBase\nfrom django.contrib.gis.geos.libgeos import CONTEXT_PTR, error_h, lgeos, notice_h\n\n\nclass GEOSContextHandle(GEOSBase):\n \"\"\"Represent a GEOS context handle.\"\"\"\n\n ptr_type = CONTEXT_PTR\n destructor = lgeos.GEOS_finish_r\n\n def __init__(self):\n self.ptr = lgeos.GEOS_init_r()\n lgeos.GEOSContext_setNoticeHandler_r(self.ptr, notice_h)\n lgeos.GEOSContext_setErrorHandler_r(self.ptr, error_h)\n\n\n# Defining a thread-local object and creating an instance\n# to hold a refe", "suffix": " variants when available.\n \"\"\"\n\n def __init__(self, func_name):\n # GEOS thread-safe function signatures end with '_r' and take an\n # additional context handle parameter.\n self.cfunc = getattr(lgeos, func_name + \"_r\")\n # C", "middle": "rence to GEOSContextHandle for this thread.\nclass GEOSContext(threading.local):\n handle = None\n\n\nthread_context = GEOSContext()\n\n\nclass GEOSFunc:\n \"\"\"\n Serve as a wrapper for GEOS C Functions. Use thread-safe function\n ", "meta": {"filepath": "django/contrib/gis/geos/prototypes/threadsafe.py", "language": "python", "file_size": 2311, "cut_index": 563, "middle_length": 229}} +{"prefix": "nctions for the\ntopological operations on geometries.\n\"\"\"\n\nfrom ctypes import c_double, c_int\n\nfrom django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory\nfrom django.contrib.gis.geos.prototypes.errcheck import (\n check_geom,\n check_minus_one,\n check_string,\n)\nfrom django.contrib.gis.geos.prototypes.geom import geos_char_p\n\n\nclass Topology(GEOSFuncFactory):\n \"For GEOS unary topology functions.\"\n\n argtypes = [GEOM_PTR]\n restype = GEOM_PTR\n errcheck = staticmethod(check_geom)\n\n\n", "suffix": "nt, c_int, c_int, c_double]\n)\ngeos_centroid = Topology(\"GEOSGetCentroid\")\ngeos_convexhull = Topology(\"GEOSConvexHull\")\ngeos_difference = Topology(\"GEOSDifference\", argtypes=[GEOM_PTR, GEOM_PTR])\ngeos_envelope = Topology(\"GEOSEnvelope\")\ngeos_intersection = ", "middle": "# Topology Routines\ngeos_boundary = Topology(\"GEOSBoundary\")\ngeos_buffer = Topology(\"GEOSBuffer\", argtypes=[GEOM_PTR, c_double, c_int])\ngeos_bufferwithstyle = Topology(\n \"GEOSBufferWithStyle\", argtypes=[GEOM_PTR, c_double, c_i", "meta": {"filepath": "django/contrib/gis/geos/prototypes/topology.py", "language": "python", "file_size": 2327, "cut_index": 563, "middle_length": 229}} +{"prefix": "es.shortcuts import get_current_site\nfrom django.core.paginator import EmptyPage, PageNotAnInteger\nfrom django.http import Http404\nfrom django.template.response import TemplateResponse\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.http import http_date\n\n\n@dataclass\nclass SitemapIndexItem:\n location: str\n last_mod: bool = None\n\n\ndef x_robots_tag(func):\n @wraps(func)\n def inner(request, *args, **kwargs):\n response = func(request, *args, **kwargs)\n ", "suffix": "ither a date or a\n datetime.\n \"\"\"\n if not isinstance(new_lastmod, datetime.datetime):\n new_lastmod = datetime.datetime.combine(new_lastmod, datetime.time.min)\n if timezone.is_naive(new_lastmod):\n new_lastmod = timezone.make_aware(", "middle": " response.headers[\"X-Robots-Tag\"] = \"noindex, noodp, noarchive\"\n return response\n\n return inner\n\n\ndef _get_latest_lastmod(current_lastmod, new_lastmod):\n \"\"\"\n Returns the latest `lastmod` where `lastmod` can be e", "meta": {"filepath": "django/contrib/sitemaps/views.py", "language": "python", "file_size": 4648, "cut_index": 614, "middle_length": 229}} +{"prefix": "fields import GenericForeignKey\nfrom django.contrib.contenttypes.forms import (\n BaseGenericInlineFormSet,\n generic_inlineformset_factory,\n)\nfrom django.core import checks\nfrom django.core.exceptions import FieldDoesNotExist\nfrom django.forms import ALL_FIELDS\nfrom django.forms.models import modelform_defines_fields\n\n\nclass GenericInlineModelAdminChecks(InlineModelAdminChecks):\n def _check_exclude_of_parent_model(self, obj, parent_model):\n # There's no FK to exclude, so no exclusion checks a", "suffix": "nKey.\n\n gfks = [\n f\n for f in obj.model._meta.private_fields\n if isinstance(f, GenericForeignKey)\n ]\n if not gfks:\n return [\n checks.Error(\n \"'%s' has no Gen", "middle": "re required.\n return []\n\n def _check_relation(self, obj, parent_model):\n # There's no FK, but we do need to confirm that the ct_field and\n # ct_fk_field are valid, and that they are part of a GenericForeig", "meta": {"filepath": "django/contrib/contenttypes/admin.py", "language": "python", "file_size": 5858, "cut_index": 716, "middle_length": 229}} +{"prefix": "some utility functions for inspecting the layout\nof a GDAL data source -- the functionality is analogous to the output\nproduced by the `ogrinfo` utility.\n\"\"\"\n\nfrom django.contrib.gis.gdal import DataSource\nfrom django.contrib.gis.gdal.geometries import GEO_CLASSES\n\n\ndef ogrinfo(data_source, num_features=10):\n \"\"\"\n Walk the available layers in the supplied `data_source`, displaying\n the fields for the first `num_features` features.\n \"\"\"\n\n # Checking the parameters.\n if isinstance(data_sourc", "suffix": " )\n\n for i, layer in enumerate(data_source):\n print(\"data source : %s\" % data_source.name)\n print(\"==== layer %s\" % i)\n print(\" shape type: %s\" % GEO_CLASSES[layer.geom_type.num].__name__)\n print(\" # features: %s\" % len", "middle": "e, str):\n data_source = DataSource(data_source)\n elif isinstance(data_source, DataSource):\n pass\n else:\n raise Exception(\n \"Data source parameter must be a string or a DataSource object.\"\n ", "meta": {"filepath": "django/contrib/gis/utils/ogrinfo.py", "language": "python", "file_size": 1956, "cut_index": 537, "middle_length": 229}} +{"prefix": "m django.contrib.sites.models import Site\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Redirect(models.Model):\n site = models.ForeignKey(Site, models.CASCADE, verbose_name=_(\"site\"))\n old_path = models.CharField(\n _(\"redirect from\"),\n max_length=200,\n db_index=True,\n help_text=_(\n \"This should be an absolute path, excluding the domain name. Example: \"\n \"“/events/search/”.\"\n ),\n )\n new_path = m", "suffix": "https://”.\"\n ),\n )\n\n class Meta:\n verbose_name = _(\"redirect\")\n verbose_name_plural = _(\"redirects\")\n db_table = \"django_redirect\"\n unique_together = [[\"site\", \"old_path\"]]\n ordering = [\"old_path\"]\n\n def _", "middle": "odels.CharField(\n _(\"redirect to\"),\n max_length=200,\n blank=True,\n help_text=_(\n \"This can be either an absolute path (as above) or a full URL \"\n \"starting with a scheme such as “", "meta": {"filepath": "django/contrib/redirects/models.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229}} +{"prefix": "m django.utils.decorators import method_decorator\nfrom django.utils.functional import cached_property\nfrom django.utils.inspect import (\n func_accepts_kwargs,\n func_accepts_var_args,\n get_func_full_args,\n method_has_no_args,\n)\nfrom django.utils.translation import gettext as _\nfrom django.views.generic import TemplateView\n\nfrom .utils import get_view_name, strip_p_tags\n\n# Exclude methods starting with these strings from documentation\nMODEL_METHODS_EXCLUDE = (\"_\", \"add_\", \"delete\", \"save\", \"set_\")", "suffix": "le:\n # Display an error message for people without docutils\n self.template_name = \"admin_doc/missing_docutils.html\"\n return self.render_to_response(admin.site.each_context(request))\n return super().dispatch(request, ", "middle": "\n\n\nclass BaseAdminDocsView(TemplateView):\n \"\"\"\n Base view for admindocs views.\n \"\"\"\n\n @method_decorator(staff_member_required)\n def dispatch(self, request, *args, **kwargs):\n if not utils.docutils_is_availab", "meta": {"filepath": "django/contrib/admindocs/views.py", "language": "python", "file_size": 19572, "cut_index": 1331, "middle_length": 229}} +{"prefix": "is module is for the miscellaneous GEOS routines, particularly the\nones that return the area, distance, and length.\n\"\"\"\n\nfrom ctypes import POINTER, c_double, c_int\n\nfrom django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory\nfrom django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string\nfrom django.contrib.gis.geos.prototypes.geom import geos_char_p\n\n__all__ = [\"geos_area\", \"geos_distance\", \"geos_length\", \"geos_isvalidreason\"]\n\n\nclass DblFromGeom(GEOSFuncFactory):\n \"\"\"\n Arg", "suffix": ", distance, and length prototypes.\ngeos_area = DblFromGeom(\"GEOSArea\", argtypes=[GEOM_PTR, POINTER(c_double)])\ngeos_distance = DblFromGeom(\n \"GEOSDistance\", argtypes=[GEOM_PTR, GEOM_PTR, POINTER(c_double)]\n)\ngeos_length = DblFromGeom(\"GEOSLength\", argty", "middle": "ument is a Geometry, return type is double that is passed\n in by reference as the last argument.\n \"\"\"\n\n restype = c_int # Status code returned\n errcheck = staticmethod(check_dbl)\n\n\n# ### ctypes prototypes ###\n\n# Area", "meta": {"filepath": "django/contrib/gis/geos/prototypes/misc.py", "language": "python", "file_size": 1167, "cut_index": 518, "middle_length": 229}} +{"prefix": " AppConfig\nfrom django.contrib.contenttypes.checks import (\n check_generic_foreign_keys,\n check_model_name_lengths,\n)\nfrom django.core import checks\nfrom django.db.models.signals import post_migrate, pre_migrate\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .management import create_contenttypes, inject_rename_contenttypes_operations\n\n\nclass ContentTypesConfig(AppConfig):\n default_auto_field = \"django.db.models.AutoField\"\n name = \"django.contrib.contenttypes\"\n verbose_name = _(", "suffix": "igrate.connect(inject_rename_contenttypes_operations, sender=self)\n post_migrate.connect(create_contenttypes)\n checks.register(check_generic_foreign_keys, checks.Tags.models)\n checks.register(check_model_name_lengths, checks.Tags.model", "middle": "\"Content Types\")\n\n def ready(self):\n pre_m", "meta": {"filepath": "django/contrib/contenttypes/apps.py", "language": "python", "file_size": 846, "cut_index": 535, "middle_length": 52}} +{"prefix": "ls import chain\n\nfrom django.apps import apps\nfrom django.core.checks import Error\n\n\ndef check_generic_foreign_keys(app_configs, **kwargs):\n from .fields import GenericForeignKeyDescriptor\n\n if app_configs is None:\n models = apps.get_models()\n else:\n models = chain.from_iterable(\n app_config.get_models() for app_config in app_configs\n )\n errors = []\n descriptors = (\n obj\n for model in models\n for obj in vars(model).values()\n if isins", "suffix": "\n models = apps.get_models()\n else:\n models = chain.from_iterable(\n app_config.get_models() for app_config in app_configs\n )\n errors = []\n for model in models:\n if len(model._meta.model_name) > 100:\n ", "middle": "tance(obj, GenericForeignKeyDescriptor)\n )\n for descriptor in descriptors:\n errors.extend(descriptor.field.check())\n return errors\n\n\ndef check_model_name_lengths(app_configs, **kwargs):\n if app_configs is None:", "meta": {"filepath": "django/contrib/contenttypes/checks.py", "language": "python", "file_size": 1304, "cut_index": 524, "middle_length": 229}} +{"prefix": "rms import ModelForm, modelformset_factory\nfrom django.forms.models import BaseModelFormSet\n\n\nclass BaseGenericInlineFormSet(BaseModelFormSet):\n \"\"\"\n A formset for generic inline objects to a parent.\n \"\"\"\n\n def __init__(\n self,\n data=None,\n files=None,\n instance=None,\n save_as_new=False,\n prefix=None,\n queryset=None,\n **kwargs,\n ):\n opts = self.model._meta\n self.instance = instance\n self.rel_name = (\n opts", "suffix": "instance is None or not self.instance._is_pk_set():\n qs = self.model._default_manager.none()\n else:\n if queryset is None:\n queryset = self.model._default_manager\n qs = queryset.filter(\n ", "middle": ".app_label\n + \"-\"\n + opts.model_name\n + \"-\"\n + self.ct_field.name\n + \"-\"\n + self.ct_fk_field.name\n )\n self.save_as_new = save_as_new\n if self.", "meta": {"filepath": "django/contrib/contenttypes/forms.py", "language": "python", "file_size": 3950, "cut_index": 614, "middle_length": 229}} +{"prefix": "db.models import Prefetch\nfrom django.db.models.query import ModelIterable, RawQuerySet\n\n\nclass GenericPrefetch(Prefetch):\n def __init__(self, lookup, querysets, to_attr=None):\n for queryset in querysets:\n if queryset is not None and (\n isinstance(queryset, RawQuerySet)\n or (\n hasattr(queryset, \"_iterable_class\")\n and not issubclass(queryset._iterable_class, ModelIterable)\n )\n ):\n ", "suffix": "e__(self):\n obj_dict = self.__dict__.copy()\n obj_dict[\"querysets\"] = []\n for queryset in self.querysets:\n if queryset is not None:\n queryset = queryset._chain()\n # Prevent the QuerySet from bein", "middle": " raise ValueError(\n \"Prefetch querysets cannot use raw(), values(), and values_list().\"\n )\n self.querysets = querysets\n super().__init__(lookup, to_attr=to_attr)\n\n def __getstat", "meta": {"filepath": "django/contrib/contenttypes/prefetch.py", "language": "python", "file_size": 1358, "cut_index": 524, "middle_length": 229}} +{"prefix": "ntegrityError, migrations, router, transaction\n\n\nclass RenameContentType(migrations.RunPython):\n def __init__(self, app_label, old_model, new_model):\n self.app_label = app_label\n self.old_model = old_model\n self.new_model = new_model\n super().__init__(self.rename_forward, self.rename_backward)\n\n def _rename(self, apps, schema_editor, old_model, new_model):\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n db = schema_editor.connection.alias\n ", "suffix": " except ContentType.DoesNotExist:\n pass\n else:\n content_type.model = new_model\n try:\n with transaction.atomic(using=db):\n content_type.save(using=db, update_fields={\"model\"})\n ", "middle": " if not router.allow_migrate_model(db, ContentType):\n return\n\n try:\n content_type = ContentType.objects.db_manager(db).get_by_natural_key(\n self.app_label, old_model\n )\n ", "meta": {"filepath": "django/contrib/contenttypes/management/__init__.py", "language": "python", "file_size": 5012, "cut_index": 614, "middle_length": 229}} +{"prefix": "o.contrib.contenttypes.models\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = []\n\n operations = [\n migrations.CreateModel(\n name=\"ContentType\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),", "suffix": "\n max_length=100, verbose_name=\"python model class name\"\n ),\n ),\n ],\n options={\n \"ordering\": (\"name\",),\n \"db_table\": \"django_content_type\",\n ", "middle": "\n ),\n (\"name\", models.CharField(max_length=100)),\n (\"app_label\", models.CharField(max_length=100)),\n (\n \"model\",\n models.CharField(", "meta": {"filepath": "django/contrib/contenttypes/migrations/0001_initial.py", "language": "python", "file_size": 1434, "cut_index": 524, "middle_length": 229}} +{"prefix": "conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponse\nfrom django.utils.deprecation import MiddlewareMixin\n\nfrom .utils import get_view_name\n\n\nclass XViewMiddleware(MiddlewareMixin):\n \"\"\"\n Add an X-View header to internal HEAD requests.\n \"\"\"\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n \"\"\"\n If the request method is HEAD and either the IP is internal or the\n user is a logged-in staff member,", "suffix": "rlyConfigured(\n \"The XView middleware requires authentication middleware to \"\n \"be installed. Edit your MIDDLEWARE setting to insert \"\n \"'django.contrib.auth.middleware.AuthenticationMiddleware'.\"\n )\n", "middle": " return a response with an x-view\n header indicating the view function. This is used to lookup the view\n function for an arbitrary page.\n \"\"\"\n if not hasattr(request, \"user\"):\n raise Imprope", "meta": {"filepath": "django/contrib/admindocs/middleware.py", "language": "python", "file_size": 1329, "cut_index": 524, "middle_length": 229}} +{"prefix": "\n\nclass Sitemap:\n # This limit is defined by Google. See the index documentation at\n # https://www.sitemaps.org/protocol.html#index.\n limit = 50000\n\n # If protocol is None, the URLs in the sitemap will use the protocol\n # with which the sitemap was requested.\n protocol = None\n\n # Enables generating URLs for all languages.\n i18n = False\n\n # Override list of languages to use.\n languages = None\n\n # Enables generating alternate/hreflang links.\n alternates = False\n\n # Add a", "suffix": " if callable(attr):\n if self.i18n:\n # Split the (item, lang_code) tuples again for the location,\n # priority, lastmod and changefreq method calls.\n item, lang_code = item\n return att", "middle": "n alternate/hreflang link with value 'x-default'.\n x_default = False\n\n def _get(self, name, item, default=None):\n try:\n attr = getattr(self, name)\n except AttributeError:\n return default\n", "meta": {"filepath": "django/contrib/sitemaps/__init__.py", "language": "python", "file_size": 6951, "cut_index": 716, "middle_length": 229}} +{"prefix": "e\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\n\ndef add_srs_entry(\n srs, auth_name=\"EPSG\", auth_srid=None, ref_sys_name=None, database=None\n):\n \"\"\"\n Take a GDAL SpatialReference system and add its information to the\n `spatial_ref_sys` table of the spatial backend. Doing this enables\n database-level spatial transformations for the backend. Thus, this utility\n is useful for adding spatial reference systems not included by default with\n the backend:\n\n >>> from django.contrib.gis", "suffix": "s keyword may be customized with the value of the `auth_srid` field.\n Defaults to the SRID determined by GDAL.\n\n ref_sys_name:\n For SpatiaLite users only, sets the value of the `ref_sys_name` field.\n Defaults to the name determined by", "middle": ".utils import add_srs_entry\n >>> add_srs_entry(3857)\n\n Keyword Arguments:\n auth_name:\n This keyword may be customized with the value of the `auth_name` field.\n Defaults to 'EPSG'.\n\n auth_srid:\n Thi", "meta": {"filepath": "django/contrib/gis/utils/srs.py", "language": "python", "file_size": 2961, "cut_index": 563, "middle_length": 229}} +{"prefix": "ntrib.sites.shortcuts import get_current_site\nfrom django.core.exceptions import ObjectDoesNotExist, ValidationError\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.utils.translation import gettext as _\n\n\ndef shortcut(request, content_type_id, object_id):\n \"\"\"\n Redirect to an object's page based on a content-type ID and an object ID.\n \"\"\"\n # Look up the object, making sure it's got a get_absolute_url() function.\n try:\n content_type = ContentType.objects.get(pk=content", "suffix": "ontent_type.get_object_for_this_type(pk=object_id)\n except (ObjectDoesNotExist, ValueError, ValidationError):\n raise Http404(\n _(\"Content type %(ct_id)s object %(obj_id)s doesn’t exist\")\n % {\"ct_id\": content_type_id, \"obj_id", "middle": "_type_id)\n if not content_type.model_class():\n raise Http404(\n _(\"Content type %(ct_id)s object has no associated model\")\n % {\"ct_id\": content_type_id}\n )\n obj = c", "meta": {"filepath": "django/contrib/contenttypes/views.py", "language": "python", "file_size": 3583, "cut_index": 614, "middle_length": 229}} +{"prefix": "jango.db import migrations, models\n\n\ndef add_legacy_name(apps, schema_editor):\n alias = schema_editor.connection.alias\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n for ct in ContentType.objects.using(alias):\n try:\n ct.name = apps.get_model(ct.app_label, ct.model)._meta.object_name\n except LookupError:\n ct.name = ct.model\n ct.save()\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"contenttypes\", \"0001_initial\"),\n ]", "suffix": "},\n ),\n migrations.AlterField(\n model_name=\"contenttype\",\n name=\"name\",\n field=models.CharField(max_length=100, null=True),\n ),\n migrations.RunPython(\n migrations.RunPython.noop,\n ", "middle": "\n\n operations = [\n migrations.AlterModelOptions(\n name=\"contenttype\",\n options={\n \"verbose_name\": \"content type\",\n \"verbose_name_plural\": \"content types\",\n ", "meta": {"filepath": "django/contrib/contenttypes/migrations/0002_remove_content_type_name.py", "language": "python", "file_size": 1199, "cut_index": 518, "middle_length": 229}} +{"prefix": "django.utils.http import http_date\nfrom django.utils.timezone import get_default_timezone, is_naive, make_aware\nfrom django.utils.translation import get_language\n\n\ndef add_domain(domain, url, secure=False):\n protocol = \"https\" if secure else \"http\"\n if url.startswith(\"//\"):\n # Support network-path reference (see #16753) - RSS requires a protocol\n url = \"%s:%s\" % (protocol, url)\n elif not url.startswith((\"http://\", \"https://\", \"mailto:\")):\n url = iri_to_uri(\"%s://%s%s\" % (protoc", "suffix": "f __call__(self, request, *args, **kwargs):\n try:\n obj = self.get_object(request, *args, **kwargs)\n except ObjectDoesNotExist:\n raise Http404(\"Feed object does not exist.\")\n feedgen = self.get_feed(obj, request)\n ", "middle": "ol, domain, url))\n return url\n\n\nclass FeedDoesNotExist(ObjectDoesNotExist):\n pass\n\n\nclass Feed:\n feed_type = feedgenerator.DefaultFeed\n title_template = None\n description_template = None\n language = None\n\n de", "meta": {"filepath": "django/contrib/syndication/views.py", "language": "python", "file_size": 9371, "cut_index": 921, "middle_length": 229}} +{"prefix": "ype\nfrom django.core.management import BaseCommand\nfrom django.db import DEFAULT_DB_ALIAS, connections, router\nfrom django.db.models.deletion import Collector\n\n\nclass Command(BaseCommand):\n help = \"Deletes stale content types in the database.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--noinput\",\n \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=\"Tells Django to NOT prompt the user for input of any kind.\",\n ", "suffix": " )\n parser.add_argument(\n \"--include-stale-apps\",\n action=\"store_true\",\n default=False,\n help=(\n \"Deletes stale content types including ones from previously \"\n \"installe", "middle": " )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(connections),\n help='Nominates the database to use. Defaults to the \"default\" database.',\n ", "meta": {"filepath": "django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py", "language": "python", "file_size": 4494, "cut_index": 614, "middle_length": 229}} +{"prefix": "ontrib.admin import helpers\nfrom django.contrib.admin.decorators import action\nfrom django.contrib.admin.utils import model_ngettext\nfrom django.core.exceptions import PermissionDenied\nfrom django.template.response import TemplateResponse\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy\n\n\n@action(\n permissions=[\"delete\"],\n description=gettext_lazy(\"Delete selected %(verbose_name_plural)s\"),\n)\ndef delete_selected(modeladmin, request, queryset):\n \"\"\"", "suffix": " a \"permission denied\" message.\n\n Next, it deletes all selected objects and redirects back to the change\n list.\n \"\"\"\n opts = modeladmin.model._meta\n app_label = opts.app_label\n\n # Populate deletable_objects, a data structure of all relate", "middle": "\n Default action which deletes the selected objects.\n\n This action first displays a confirmation page which shows all the\n deletable objects, or, if the user has no permission one of the related\n childs (foreignkeys),", "meta": {"filepath": "django/contrib/admin/actions.py", "language": "python", "file_size": 3272, "cut_index": 614, "middle_length": 229}} +{"prefix": "ngo.apps import AppConfig\nfrom django.contrib.admin.checks import check_admin_app, check_dependencies\nfrom django.core import checks\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass SimpleAdminConfig(AppConfig):\n \"\"\"Simple AppConfig which does not do automatic discovery.\"\"\"\n\n default_auto_field = \"django.db.models.AutoField\"\n default_site = \"django.contrib.admin.sites.AdminSite\"\n name = \"django.contrib.admin\"\n verbose_name = _(\"Administration\")\n\n def ready(self):\n chec", "suffix": " checks.register(check_admin_app, checks.Tags.admin)\n\n\nclass AdminConfig(SimpleAdminConfig):\n \"\"\"The default AppConfig for admin which does autodiscovery.\"\"\"\n\n default = True\n\n def ready(self):\n super().ready()\n self.module.aut", "middle": "ks.register(check_dependencies, checks.Tags.admin)\n ", "meta": {"filepath": "django/contrib/admin/apps.py", "language": "python", "file_size": 840, "cut_index": 520, "middle_length": 52}} +{"prefix": "rmissions=None,\n description=None,\n description_plural=None,\n location=ActionLocation.CHANGE_LIST,\n):\n \"\"\"\n Conveniently add attributes to an action function::\n\n @admin.action(\n permissions=['publish'],\n description='Mark selected stories as published',\n )\n def make_published(self, request, queryset):\n queryset.update(status='p')\n\n This is equivalent to setting some attributes (with the original, longer\n names) on the function direct", "suffix": "ished'\n \"\"\"\n\n def decorator(func):\n if permissions is not None:\n func.allowed_permissions = permissions\n if description is not None:\n func.short_description = description\n if description_plural is not None:\n", "middle": "ly::\n\n def make_published(self, request, queryset):\n queryset.update(status='p')\n make_published.allowed_permissions = ['publish']\n make_published.short_description = 'Mark selected stories as publ", "meta": {"filepath": "django/contrib/admin/decorators.py", "language": "python", "file_size": 3930, "cut_index": 614, "middle_length": 229}} +{"prefix": "from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass AdminAuthenticationForm(AuthenticationForm):\n \"\"\"\n A custom authentication form used in the admin app.\n \"\"\"\n\n error_messages = {\n **AuthenticationForm.error_messages,\n \"invalid_login\": _(\n \"Please enter the correct %(username)s and password for a staff \"\n \"account. Note th", "suffix": "alidationError(\n self.error_messages[\"invalid_login\"],\n code=\"invalid_login\",\n params={\"username\": self.username_field.verbose_name},\n )\n\n\nclass AdminPasswordChangeForm(PasswordChangeForm):\n requir", "middle": "at both fields may be case-sensitive.\"\n ),\n }\n required_css_class = \"required\"\n\n def confirm_login_allowed(self, user):\n super().confirm_login_allowed(user)\n if not user.is_staff:\n raise V", "meta": {"filepath": "django/contrib/admin/forms.py", "language": "python", "file_size": 1023, "cut_index": 512, "middle_length": 229}} +{"prefix": "oReverseMatch, reverse\nfrom django.utils import timezone\nfrom django.utils.text import get_text_list\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\n\nADDITION = 1\nCHANGE = 2\nDELETION = 3\n\nACTION_FLAG_CHOICES = [\n (ADDITION, _(\"Addition\")),\n (CHANGE, _(\"Change\")),\n (DELETION, _(\"Deletion\")),\n]\n\n\nclass LogEntryManager(models.Manager):\n use_in_migrations = True\n\n def log_actions(\n self, user_id, queryset, action_flag, change_message=\"\", ", "suffix": " content_type_id=ContentType.objects.get_for_model(\n obj, for_concrete_model=False\n ).id,\n object_id=obj.pk,\n object_repr=str(obj)[:200],\n action_flag=action_flag,\n ", "middle": "*, single_object=False\n ):\n if isinstance(change_message, list):\n change_message = json.dumps(change_message)\n\n log_entry_list = [\n self.model(\n user_id=user_id,\n ", "meta": {"filepath": "django/contrib/admin/models.py", "language": "python", "file_size": 6867, "cut_index": 716, "middle_length": 229}} +{"prefix": "rse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.utils.functional import LazyObject\nfrom django.utils.module_loading import import_string\nfrom django.utils.text import capfirst\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.common import no_append_slash\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.i18n import JavaScriptCat", "suffix": "g the register() method, and the get_urls() method\n can then be used to access Django view functions that present a full admin\n interface for the collection of registered models.\n \"\"\"\n\n # Text to put at the end of each page's .\n site_", "middle": "alog\n\nall_sites = WeakSet()\n\n\nclass AdminSite:\n \"\"\"\n An AdminSite object encapsulates an instance of the Django admin\n application, ready to be hooked in to your URLconf. Models are registered\n with the AdminSite usin", "meta": {"filepath": "django/contrib/admin/sites.py", "language": "python", "file_size": 23478, "cut_index": 1331, "middle_length": 229}} +{"prefix": "om django.utils.text import capfirst\nfrom django.utils.translation import ngettext\nfrom django.utils.translation import override as translation_override\n\nQUOTE_MAP = {i: \"_%02X\" % i for i in b'\":/_#?;@&=+$,\"[]<>%\\n\\\\'}\nUNQUOTE_MAP = {v: chr(k) for k, v in QUOTE_MAP.items()}\nUNQUOTE_RE = _lazy_re_compile(\"_(?:%s)\" % \"|\".join([x[1:] for x in UNQUOTE_MAP]))\n\n\nclass FieldIsAForeignKeyColumnName(Exception):\n \"\"\"A field is a foreign key attname, i.e. <FK>_id.\"\"\"\n\n pass\n\n\ndef lookup_spawns_duplicates(opts, l", "suffix": "ame in lookup_fields:\n if field_name == \"pk\":\n field_name = opts.pk.name\n try:\n field = opts.get_field(field_name)\n except FieldDoesNotExist:\n # Ignore query lookups.\n continue\n else:\n", "middle": "ookup_path):\n \"\"\"\n Return True if the given lookup path spawns duplicates.\n \"\"\"\n lookup_fields = lookup_path.split(LOOKUP_SEP)\n # Go through the fields (following all relations) and look for an m2m.\n for field_n", "meta": {"filepath": "django/contrib/admin/utils.py", "language": "python", "file_size": 22600, "cut_index": 1331, "middle_length": 229}} +{"prefix": "e.exceptions import FieldDoesNotExist, PermissionDenied\nfrom django.http import Http404, JsonResponse\nfrom django.views.generic.list import BaseListView\n\n\nclass AutocompleteJsonView(BaseListView):\n \"\"\"Handle AutocompleteWidget's AJAX requests for data.\"\"\"\n\n paginate_by = 20\n admin_site = None\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Return a JsonResponse with search results as defined in\n serialize_result(), by default:\n {\n results: [{id: \"123\" text", "suffix": "st)\n\n if not self.has_perm(request):\n raise PermissionDenied\n\n self.object_list = self.get_queryset()\n context = self.get_context_data()\n return JsonResponse(\n {\n \"results\": [\n ", "middle": ": \"foo\"}],\n pagination: {more: true}\n }\n \"\"\"\n (\n self.term,\n self.model_admin,\n self.source_field,\n to_field_name,\n ) = self.process_request(reque", "meta": {"filepath": "django/contrib/admin/views/autocomplete.py", "language": "python", "file_size": 4385, "cut_index": 614, "middle_length": 229}} +{"prefix": " import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n (\"contenttypes\", \"__first__\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"LogEntry\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n ", "suffix": "se_name=\"action time\"),\n ),\n (\n \"object_id\",\n models.TextField(null=True, verbose_name=\"object id\", blank=True),\n ),\n (\n \"object_repr\",\n ", "middle": " auto_created=True,\n primary_key=True,\n ),\n ),\n (\n \"action_time\",\n models.DateTimeField(auto_now=True, verbo", "meta": {"filepath": "django/contrib/admin/migrations/0001_initial.py", "language": "python", "file_size": 2507, "cut_index": 563, "middle_length": 229}} +{"prefix": "in.options import EMPTY_VALUE_STRING\nfrom django.contrib.admin.utils import display_for_value\nfrom django.template.defaultfilters import _walk_items, stringfilter\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ngettext\n\nregister = template.Library()\n\n\n@register.filter\n@stringfilter\ndef to_object_display_value(value):\n return display_for_value(str(value), EMPTY_VALUE_STRING)\n\n\n@register.filter(is_safe=True, needs_autoesca", "suffix": "ted_objects|truncated_unordered_list:100 }}\n \"\"\"\n\n has_unlimited_items = max_items is None\n if not has_unlimited_items:\n max_items = int(max_items)\n if max_items <= 0:\n return mark_safe(\"\")\n\n if autoescape:\n esca", "middle": "pe=True)\ndef truncated_unordered_list(value, max_items, autoescape=True):\n \"\"\"\n Render an unordered list, showing at most ``max_items`` items and a\n \"...and N more objects.\" item at the end.\n\n Usage::\n\n {{ dele", "meta": {"filepath": "django/contrib/admin/templatetags/admin_filters.py", "language": "python", "file_size": 2422, "cut_index": 563, "middle_length": 229}} +{"prefix": "jango.contrib.admin.decorators import action, display, register\nfrom django.contrib.admin.filters import (\n AllValuesFieldListFilter,\n BooleanFieldListFilter,\n ChoicesFieldListFilter,\n DateFieldListFilter,\n EmptyFieldListFilter,\n FieldListFilter,\n ListFilter,\n RelatedFieldListFilter,\n RelatedOnlyFieldListFilter,\n SimpleListFilter,\n)\nfrom django.contrib.admin.options import (\n HORIZONTAL,\n VERTICAL,\n ActionLocation,\n ModelAdmin,\n ShowFacets,\n StackedInline,\n ", "suffix": "\",\n \"HORIZONTAL\",\n \"VERTICAL\",\n \"StackedInline\",\n \"TabularInline\",\n \"AdminSite\",\n \"site\",\n \"ListFilter\",\n \"SimpleListFilter\",\n \"FieldListFilter\",\n \"BooleanFieldListFilter\",\n \"RelatedFieldListFilter\",\n \"ChoicesFieldListFi", "middle": " TabularInline,\n)\nfrom django.contrib.admin.sites import AdminSite, site\nfrom django.utils.module_loading import autodiscover_modules\n\n__all__ = [\n \"action\",\n \"ActionLocation\",\n \"display\",\n \"register\",\n \"ModelAdmin", "meta": {"filepath": "django/contrib/admin/__init__.py", "language": "python", "file_size": 1245, "cut_index": 518, "middle_length": 229}} +{"prefix": "s\n\n\ndef check_dependencies(**kwargs):\n \"\"\"\n Check that the admin's dependencies are correctly installed.\n \"\"\"\n from django.contrib.admin.sites import all_sites\n\n if not apps.is_installed(\"django.contrib.admin\"):\n return []\n errors = []\n app_dependencies = (\n (\"django.contrib.contenttypes\", 401),\n (\"django.contrib.auth\", 405),\n (\"django.contrib.messages\", 406),\n )\n for app_name, error_code in app_dependencies:\n if not apps.is_installed(app_name):\n", "suffix": "de,\n )\n )\n for engine in engines.all():\n if isinstance(engine, DjangoTemplates):\n django_templates_instance = engine.engine\n break\n else:\n django_templates_instance = None\n if not djang", "middle": " errors.append(\n checks.Error(\n \"'%s' must be in INSTALLED_APPS in order to use the admin \"\n \"application.\" % app_name,\n id=\"admin.E%d\" % error_co", "meta": {"filepath": "django/contrib/admin/checks.py", "language": "python", "file_size": 52481, "cut_index": 2151, "middle_length": 229}} +{"prefix": "\n\n\nclass ActionForm(forms.Form):\n action = forms.ChoiceField(label=_(\"Action:\"))\n select_across = forms.BooleanField(\n label=\"\",\n required=False,\n initial=0,\n widget=forms.HiddenInput({\"class\": \"select-across\"}),\n )\n\n\nclass AdminForm:\n def __init__(\n self,\n form,\n fieldsets,\n prepopulated_fields,\n readonly_fields=None,\n model_admin=None,\n ):\n self.form, self.fieldsets = form, fieldsets\n self.prepopulated_field", "suffix": "adonly_fields is None:\n readonly_fields = ()\n self.readonly_fields = readonly_fields\n\n def __repr__(self):\n return (\n f\"<{self.__class__.__qualname__}: \"\n f\"form={self.form.__class__.__qualname__} \"\n ", "middle": "s = [\n {\"field\": form[field_name], \"dependencies\": [form[f] for f in dependencies]}\n for field_name, dependencies in prepopulated_fields.items()\n ]\n self.model_admin = model_admin\n if re", "meta": {"filepath": "django/contrib/admin/helpers.py", "language": "python", "file_size": 18435, "cut_index": 1331, "middle_length": 229}} +{"prefix": "s(\n MIDDLEWARE={\"append\": \"django.middleware.csp.ContentSecurityPolicyMiddleware\"}\n)\n@override_settings(\n SECURE_CSP={\n \"default-src\": [CSP.NONE],\n \"connect-src\": [CSP.SELF],\n \"img-src\": [CSP.SELF],\n \"script-src\": [CSP.SELF],\n \"style-src\": [CSP.SELF],\n },\n)\nclass AdminSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):\n available_apps = [\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"dja", "suffix": " super().tearDown()\n\n def wait_until(self, callback, timeout=10):\n \"\"\"\n Block the execution of the tests until the specified callback returns a\n value that is not falsy. This method can be called, for example, after\n click", "middle": "ngo.contrib.sessions\",\n \"django.contrib.sites\",\n ]\n\n def tearDown(self):\n # Ensure that no CSP violations were logged in the browser.\n self.assertEqual(self.get_browser_logs(source=\"security\"), [])\n ", "meta": {"filepath": "django/contrib/admin/tests.py", "language": "python", "file_size": 9400, "cut_index": 921, "middle_length": 229}} +{"prefix": ".models import F, Field, ManyToOneRel, OrderBy\nfrom django.db.models.constants import LOOKUP_SEP\nfrom django.db.models.expressions import Combinable\nfrom django.urls import reverse\nfrom django.utils.http import urlencode\nfrom django.utils.timezone import make_aware\nfrom django.utils.translation import gettext\n\n# Changelist settings\nALL_VAR = \"all\"\nORDER_VAR = \"o\"\nPAGE_VAR = \"p\"\nSEARCH_VAR = \"q\"\nERROR_FLAG = \"e\"\n\nIGNORED_PARAMS = (\n ALL_VAR,\n ORDER_VAR,\n SEARCH_VAR,\n IS_FACETS_VAR,\n IS_POPUP_V", "suffix": " is a variable:\n self.fields = {\n SEARCH_VAR: forms.CharField(required=False, strip=False),\n }\n\n\nclass ChangeList:\n search_form_class = ChangeListSearchForm\n\n def __init__(\n self,\n request,\n model,\n ", "middle": "AR,\n SOURCE_MODEL_VAR,\n TO_FIELD_VAR,\n)\n\n\nclass ChangeListSearchForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Populate \"fields\" dynamically because SEARCH_VAR", "meta": {"filepath": "django/contrib/admin/views/main.py", "language": "python", "file_size": 22542, "cut_index": 1331, "middle_length": 229}} +{"prefix": "istFilter:\n title = None # Human-readable title to appear in the right sidebar.\n template = \"admin/filter.html\"\n\n def __init__(self, request, params, model, model_admin):\n self.request = request\n # This dictionary will eventually contain the request's query string\n # parameters actually used by this filter.\n self.used_parameters = {}\n if self.title is None:\n raise ImproperlyConfigured(\n \"The list filter '%s' does not specify a 'title'.\"\n", "suffix": "asses of ListFilter must provide a has_output() method\"\n )\n\n def choices(self, changelist):\n \"\"\"\n Return choices ready to be output in the template.\n\n `changelist` is the ChangeList to be displayed.\n \"\"\"\n raise ", "middle": " % self.__class__.__name__\n )\n\n def has_output(self):\n \"\"\"\n Return True if some choices would be output for this filter.\n \"\"\"\n raise NotImplementedError(\n \"subcl", "meta": {"filepath": "django/contrib/admin/filters.py", "language": "python", "file_size": 27668, "cut_index": 1331, "middle_length": 229}} +{"prefix": "arnings.warn(\n \"Unpacking an action tuple is deprecated. Use Action attributes instead.\",\n RemovedInDjango70Warning,\n skip_file_prefixes=django_file_prefixes(),\n )\n return iter(self._as_tuple())\n\n # RemovedInDjango70Warning.\n def __getitem__(self, index):\n warnings.warn(\n \"Using indexes on an action tuple is deprecated. \"\n \"Use Action attributes instead.\",\n RemovedInDjango70Warning,\n skip_file_prefixes=dj", "suffix": "import models from other applications at the module level.\n from django.contrib.contenttypes.models import ContentType\n\n return ContentType.objects.get_for_model(obj, for_concrete_model=False)\n\n\ndef get_ul_class(radio_style):\n return \"radiolist\" i", "middle": "ango_file_prefixes(),\n )\n return self._as_tuple()[index]\n\n\nHORIZONTAL, VERTICAL = 1, 2\n\n\ndef get_content_type_for_model(obj):\n # Since this module gets imported in the application's root package,\n # it cannot ", "meta": {"filepath": "django/contrib/admin/options.py", "language": "python", "file_size": 113731, "cut_index": 3790, "middle_length": 229}} +{"prefix": "\nfrom asgiref.sync import async_to_sync, sync_to_async\n\nfrom django.conf import settings\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import resolve_url\n\n\ndef user_passes_test(\n test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME\n):\n \"\"\"\n Decorator for views that checks that the user passes the given test,\n redirecting to the log-in page if necessary. The test should be a callable\n that takes the u", "suffix": "l or settings.LOGIN_URL)\n # If the login url is the same scheme and net location then just\n # use the path as the \"next\" url.\n login_scheme, login_netloc = urlsplit(resolved_login_url)[:2]\n current_scheme, curren", "middle": "ser object and returns True if the user passes.\n \"\"\"\n\n def decorator(view_func):\n def _redirect_to_login(request):\n path = request.build_absolute_uri()\n resolved_login_url = resolve_url(login_ur", "meta": {"filepath": "django/contrib/auth/decorators.py", "language": "python", "file_size": 4779, "cut_index": 614, "middle_length": 229}} +{"prefix": "ger(models.Manager):\n use_in_migrations = True\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # Cache shared by all the get_for_* methods to speed up\n # ContentType retrieval.\n self._cache = {}\n\n def get_by_natural_key(self, app_label, model):\n try:\n ct = self._cache[self.db][(app_label, model)]\n except KeyError:\n ct = self.get(app_label=app_label, model=model)\n self._add_to_cache(self.db, ct)\n ", "suffix": "s.app_label, opts.model_name)\n return self._cache[self.db][key]\n\n def get_for_model(self, model, for_concrete_model=True):\n \"\"\"\n Return the ContentType object for a given model, creating the\n ContentType if necessary. Lookups", "middle": " return ct\n\n def _get_opts(self, model, for_concrete_model):\n if for_concrete_model:\n model = model._meta.concrete_model\n return model._meta\n\n def _get_from_cache(self, opts):\n key = (opt", "meta": {"filepath": "django/contrib/contenttypes/models.py", "language": "python", "file_size": 6874, "cut_index": 716, "middle_length": 229}} +{"prefix": "i18n\n catalog has been loaded in the page\n \"\"\"\n\n use_fieldset = True\n\n class Media:\n js = [\n \"admin/js/core.js\",\n \"admin/js/SelectBox.js\",\n \"admin/js/SelectFilter2.js\",\n ]\n\n def __init__(self, verbose_name, is_stacked, attrs=None, choices=()):\n self.verbose_name = verbose_name\n self.is_stacked = is_stacked\n super().__init__(attrs, choices)\n\n def get_context(self, name, value, attrs):\n context = super().get_context(n", "suffix": ".verbose_name\n context[\"widget\"][\"attrs\"][\"data-is-stacked\"] = int(self.is_stacked)\n return context\n\n\nclass DateTimeWidgetContextMixin:\n def get_context(self, name, value, attrs):\n context = super().get_context(name, value, attrs)\n ", "middle": "ame, value, attrs)\n context[\"widget\"][\"attrs\"][\"class\"] = \"selectfilter\"\n if self.is_stacked:\n context[\"widget\"][\"attrs\"][\"class\"] += \"stacked\"\n context[\"widget\"][\"attrs\"][\"data-field-name\"] = self", "meta": {"filepath": "django/contrib/admin/widgets.py", "language": "python", "file_size": 20576, "cut_index": 1331, "middle_length": 229}} +{"prefix": "it, urlunsplit\n\nfrom django import template\nfrom django.contrib.admin.utils import quote\nfrom django.urls import Resolver404, get_script_prefix, resolve\nfrom django.utils.http import urlencode\n\nregister = template.Library()\n\n\n@register.filter\ndef admin_urlname(value, arg):\n return \"admin:%s_%s_%s\" % (value.app_label, value.model_name, arg)\n\n\n@register.filter\ndef admin_urlquote(value):\n return quote(value)\n\n\n@register.simple_tag(takes_context=True)\ndef add_preserved_filters(context, url, popup=False, t", "suffix": "rl[3]))\n merged_qs = {}\n\n if preserved_qsl:\n merged_qs.update(preserved_qsl)\n\n if opts and preserved_filters:\n preserved_filters = dict(parse_qsl(preserved_filters))\n\n match_url = \"/%s\" % unquote(url).partition(get_script_pref", "middle": "o_field=None):\n opts = context.get(\"opts\")\n preserved_filters = context.get(\"preserved_filters\")\n preserved_qsl = context.get(\"preserved_qsl\")\n\n parsed_url = list(urlsplit(url))\n parsed_qs = dict(parse_qsl(parsed_u", "meta": {"filepath": "django/contrib/admin/templatetags/admin_urls.py", "language": "python", "file_size": 2038, "cut_index": 563, "middle_length": 229}} +{"prefix": "brary()\n\n\nclass AdminLogNode(template.Node):\n def __init__(self, limit, varname, user):\n self.limit = limit\n self.varname = varname\n self.user = user\n\n def __repr__(self):\n return \"<GetAdminLog Node>\"\n\n def render(self, context):\n entries = context[\"log_entries\"]\n if self.user is not None:\n user_id = self.user\n if not user_id.isdigit():\n user_id = context[self.user].pk\n entries = entries.filter(user__pk=user_i", "suffix": " {% get_admin_log [limit] as [varname] for_user [user_id_or_varname] %}\n\n Examples::\n\n {% get_admin_log 10 as admin_log for_user 23 %}\n {% get_admin_log 10 as admin_log for_user user %}\n {% get_admin_log 10 as admin_log %}\n\n ", "middle": "d)\n context[self.varname] = entries[: int(self.limit)]\n return \"\"\n\n\n@register.tag\ndef get_admin_log(parser, token):\n \"\"\"\n Populate a template variable with the admin log for the given criteria.\n\n Usage::\n\n ", "meta": {"filepath": "django/contrib/admin/templatetags/log.py", "language": "python", "file_size": 2030, "cut_index": 563, "middle_length": 229}} +{"prefix": "t connections\nfrom django.db.backends.postgresql.psycopg_any import RANGE_TYPES\nfrom django.db.backends.signals import connection_created\nfrom django.db.migrations.writer import MigrationWriter\nfrom django.db.models import CharField, OrderBy, TextField\nfrom django.db.models.functions import Collate\nfrom django.db.models.indexes import IndexExpression\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .indexes import OpClass\nfrom .lookups import (\n SearchLookup,\n TrigramSimilar,\n TrigramSt", "suffix": "s of PostgresConfig.ready() when django.contrib.postgres\n is \"uninstalled\" by override_settings().\n \"\"\"\n if (\n not enter\n and setting == \"INSTALLED_APPS\"\n and \"django.contrib.postgres\" not in set(value)\n ):\n connecti", "middle": "rictWordSimilar,\n TrigramWordSimilar,\n Unaccent,\n)\nfrom .serializers import RangeSerializer\nfrom .signals import register_type_handlers\n\n\ndef uninstall_if_needed(setting, value, enter, **kwargs):\n \"\"\"\n Undo the effect", "meta": {"filepath": "django/contrib/postgres/apps.py", "language": "python", "file_size": 4062, "cut_index": 614, "middle_length": 229}} +{"prefix": "ort Transform\nfrom django.db.models.lookups import PostgresOperatorLookup\nfrom django.db.models.sql.query import Query\n\nfrom .search import SearchVector, SearchVectorExact, SearchVectorField\n\n\nclass DataContains(PostgresOperatorLookup):\n lookup_name = \"contains\"\n postgres_operator = \"@>\"\n\n\nclass ContainedBy(PostgresOperatorLookup):\n lookup_name = \"contained_by\"\n postgres_operator = \"<@\"\n\n\nclass Overlap(PostgresOperatorLookup):\n lookup_name = \"overlap\"\n postgres_operator = \"&&\"\n\n def get", "suffix": "okup):\n lookup_name = \"has_key\"\n postgres_operator = \"?\"\n prepare_rhs = False\n\n\nclass HasKeys(PostgresOperatorLookup):\n lookup_name = \"has_keys\"\n postgres_operator = \"?&\"\n\n def get_prep_lookup(self):\n return [str(item) for item in ", "middle": "_prep_lookup(self):\n from .expressions import ArraySubquery\n\n if isinstance(self.rhs, Query):\n self.rhs = ArraySubquery(self.rhs)\n return super().get_prep_lookup()\n\n\nclass HasKey(PostgresOperatorLo", "meta": {"filepath": "django/contrib/postgres/lookups.py", "language": "python", "file_size": 1991, "cut_index": 537, "middle_length": 229}} +{"prefix": " reversible = True\n category = OperationCategory.ADDITION\n\n def __init__(self, name, hints=None):\n self.name = name\n self.hints = hints or {}\n\n def state_forwards(self, app_label, state):\n pass\n\n def database_forwards(self, app_label, schema_editor, from_state, to_state):\n if schema_editor.connection.vendor != \"postgresql\" or not router.allow_migrate(\n schema_editor.connection.alias, app_label, **self.hints\n ):\n return\n if not self", "suffix": " oids.\n get_hstore_oids.cache_clear()\n get_citext_oids.cache_clear()\n # Registering new type handlers cannot be done before the extension is\n # installed, otherwise a subsequent data migration would use the same\n # connec", "middle": ".extension_exists(schema_editor, self.name):\n schema_editor.execute(\n \"CREATE EXTENSION IF NOT EXISTS %s\"\n % schema_editor.quote_name(self.name)\n )\n # Clear cached, stale", "meta": {"filepath": "django/contrib/postgres/operations.py", "language": "python", "file_size": 12668, "cut_index": 921, "middle_length": 229}} +{"prefix": "\nfrom django.db.backends.base.base import NO_DB_ALIAS\nfrom django.db.backends.postgresql.psycopg_any import is_psycopg3\n\n\ndef get_type_oids(connection_alias, type_name):\n with connections[connection_alias].cursor() as cursor:\n cursor.execute(\n \"SELECT oid, typarray FROM pg_type WHERE typname = %s\", (type_name,)\n )\n oids = []\n array_oids = []\n for row in cursor:\n oids.append(row[0])\n array_oids.append(row[1])\n return tuple(oids), t", "suffix": "ion_alias):\n \"\"\"Return citext and citext array OIDs.\"\"\"\n return get_type_oids(connection_alias, \"citext\")\n\n\nif is_psycopg3:\n from psycopg.types import TypeInfo, hstore\n\n def register_type_handlers(connection, **kwargs):\n if connection.ve", "middle": "uple(array_oids)\n\n\n@functools.lru_cache\ndef get_hstore_oids(connection_alias):\n \"\"\"Return hstore and hstore array OIDs.\"\"\"\n return get_type_oids(connection_alias, \"hstore\")\n\n\n@functools.lru_cache\ndef get_citext_oids(connect", "meta": {"filepath": "django/contrib/postgres/signals.py", "language": "python", "file_size": 2880, "cut_index": 563, "middle_length": 229}} +{"prefix": "from django.core.validators import (\n MaxLengthValidator,\n MaxValueValidator,\n MinLengthValidator,\n MinValueValidator,\n)\nfrom django.utils.deconstruct import deconstructible\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\n\nclass ArrayMaxLengthValidator(MaxLengthValidator):\n message = ngettext_lazy(\n \"List contains %(show_value)d item, it should contain no more than \"\n \"%(limit_value)d.\",\n \"List contains %(show_val", "suffix": " should contain no fewer than \"\n \"%(limit_value)d.\",\n \"List contains %(show_value)d items, it should contain no fewer than \"\n \"%(limit_value)d.\",\n \"show_value\",\n )\n\n\n@deconstructible\nclass KeysValidator:\n \"\"\"A validator de", "middle": "ue)d items, it should contain no more than \"\n \"%(limit_value)d.\",\n \"show_value\",\n )\n\n\nclass ArrayMinLengthValidator(MinLengthValidator):\n message = ngettext_lazy(\n \"List contains %(show_value)d item, it", "meta": {"filepath": "django/contrib/postgres/validators.py", "language": "python", "file_size": 2801, "cut_index": 563, "middle_length": 229}} +{"prefix": "import forms\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\n__all__ = [\"HStoreField\"]\n\n\nclass HStoreField(forms.CharField):\n \"\"\"\n A field for HStore data which accepts dictionary JSON input.\n \"\"\"\n\n widget = forms.Textarea\n default_error_messages = {\n \"invalid_json\": _(\"Could not load JSON data.\"),\n \"invalid_format\": _(\"Input must be a JSON dictionary.\"),\n }\n\n def prepare_value(self, value):\n if isinstance(v", "suffix": " value = json.loads(value)\n except json.JSONDecodeError:\n raise ValidationError(\n self.error_messages[\"invalid_json\"],\n code=\"invalid_json\",\n )\n\n if not isinst", "middle": "alue, dict):\n return json.dumps(value, ensure_ascii=False)\n return value\n\n def to_python(self, value):\n if not value:\n return {}\n if not isinstance(value, dict):\n try:\n ", "meta": {"filepath": "django/contrib/postgres/forms/hstore.py", "language": "python", "file_size": 1787, "cut_index": 537, "middle_length": 229}} +{"prefix": "e\nfrom django.db.models.fields.mixins import CheckFieldDefaultMixin\nfrom django.db.models.lookups import Exact, In\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .utils import AttributeSetter\n\n__all__ = [\"ArrayField\"]\n\n\nclass ArrayField(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field):\n empty_strings_allowed = False\n default_error_messages = {\n \"item_invalid\": _(\"Item %(nth)s in the array did not validate:\"),\n \"nested_array_mismatch\": _(\"Nested arrays must have t", "suffix": "\n self.size = size\n if self.size:\n self.default_validators = [\n *self.default_validators,\n ArrayMaxLengthValidator(self.size),\n ]\n # For performance, only add a from_db_value() method", "middle": "he same length.\"),\n }\n _default_hint = (\"list\", \"[]\")\n\n def __init__(self, base_field, size=None, **kwargs):\n self.base_field = base_field\n self.db_collation = getattr(self.base_field, \"db_collation\", None)", "meta": {"filepath": "django/contrib/postgres/fields/array.py", "language": "python", "file_size": 13205, "cut_index": 921, "middle_length": 229}} +{"prefix": " Create a list of prepopulated_fields that should render JavaScript for\n the prepopulated fields for both the admin form and inlines.\n \"\"\"\n prepopulated_fields = []\n if \"adminform\" in context:\n prepopulated_fields.extend(context[\"adminform\"].prepopulated_fields)\n if \"inline_admin_formsets\" in context:\n for inline_admin_formset in context[\"inline_admin_formsets\"]:\n for inline_admin_form in inline_admin_formset:\n if inline_admin_form.original is None:\n ", "suffix": "d\": \"#%s\" % field[\"field\"].auto_id,\n \"name\": field[\"field\"].name,\n \"dependency_ids\": [\n \"#%s\" % dependency.auto_id for dependency in field[\"dependencies\"]\n ],\n \"dependency_list\"", "middle": " prepopulated_fields.extend(inline_admin_form.prepopulated_fields)\n\n prepopulated_fields_json = []\n for field in prepopulated_fields:\n prepopulated_fields_json.append(\n {\n \"i", "meta": {"filepath": "django/contrib/admin/templatetags/admin_modify.py", "language": "python", "file_size": 5343, "cut_index": 716, "middle_length": 229}} +{"prefix": " PostgresOperatorLookup\nfrom django.db.models.sql import Query\n\nfrom .fields import RangeOperators\nfrom .utils import CheckPostgresInstalledMixin\n\n__all__ = [\"ExclusionConstraint\"]\n\n\nclass ExclusionConstraintExpression(IndexExpression):\n template = \"%(expressions)s WITH %(operator)s\"\n\n\nclass ExclusionConstraint(CheckPostgresInstalledMixin, BaseConstraint):\n template = (\n \"CONSTRAINT %(name)s EXCLUDE USING %(index_type)s \"\n \"(%(expressions)s)%(include)s%(where)s%(deferrable)s\"\n )\n\n ", "suffix": "message=None,\n ):\n if index_type and index_type.lower() not in {\"gist\", \"hash\", \"spgist\"}:\n raise ValueError(\n \"Exclusion constraints only support GiST, Hash, or SP-GiST indexes.\"\n )\n if not expressions", "middle": "def __init__(\n self,\n *,\n name,\n expressions,\n index_type=None,\n condition=None,\n deferrable=None,\n include=None,\n violation_error_code=None,\n violation_error_", "meta": {"filepath": "django/contrib/postgres/constraints.py", "language": "python", "file_size": 10255, "cut_index": 921, "middle_length": 229}} +{"prefix": "\",\n \"GinIndex\",\n \"GistIndex\",\n \"HashIndex\",\n \"SpGistIndex\",\n]\n\n\nclass PostgresIndex(CheckPostgresInstalledMixin, Index):\n @cached_property\n def max_name_length(self):\n # Allow an index name longer than 30 characters when the suffix is\n # longer than the usual 3 character limit. The 30 character limit for\n # cross-database compatibility isn't applicable to PostgreSQL-specific\n # indexes.\n return Index.max_name_length - len(Index.suffix) + len(self.suffix)\n", "suffix": ", **kwargs\n )\n with_params = self.get_with_params()\n if with_params:\n statement.parts[\"extra\"] = \" WITH (%s)%s\" % (\n \", \".join(with_params),\n statement.parts[\"extra\"],\n )\n retu", "middle": "\n def create_sql(self, model, schema_editor, using=\"\", **kwargs):\n self.check_supported(schema_editor)\n statement = super().create_sql(\n model, schema_editor, using=\" USING %s\" % (using or self.suffix)", "meta": {"filepath": "django/contrib/postgres/indexes.py", "language": "python", "file_size": 8301, "cut_index": 716, "middle_length": 229}} +{"prefix": "utils import CheckPostgresInstalledMixin\n\nif is_psycopg3:\n from psycopg.adapt import Dumper\n\n class UTF8Dumper(Dumper):\n def dump(self, obj):\n return bytes(obj, \"utf-8\")\n\n def quote_lexeme(value):\n return UTF8Dumper(str).quote(psql_escape(value)).decode()\n\nelse:\n from psycopg2.extensions import adapt\n\n def quote_lexeme(value):\n adapter = adapt(psql_escape(value))\n adapter.encoding = \"utf-8\"\n return adapter.getquoted().decode()\n\n\nspec_chars_re = _l", "suffix": " return None\n return multiple_spaces_re.sub(\" \", val)\n\n\ndef psql_escape(query):\n \"\"\"Replace chars not fit for use in search queries with a single space.\"\"\"\n query = spec_chars_re.sub(\" \", query)\n return normalize_spaces(query)\n\n\nclass SearchVe", "middle": "azy_re_compile(r\"['\\0\\[\\]()|&:*!@<>\\\\]\")\nmultiple_spaces_re = _lazy_re_compile(r\"\\s{2,}\")\n\n\ndef normalize_spaces(val):\n \"\"\"Convert multiple spaces to single and strip from both sides.\"\"\"\n if not (val := val.strip()):\n ", "meta": {"filepath": "django/contrib/postgres/search.py", "language": "python", "file_size": 16079, "cut_index": 921, "middle_length": 229}} +{"prefix": "ator,\n ArrayMinLengthValidator,\n)\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass SimpleArrayField(forms.CharField):\n default_error_messages = {\n \"item_invalid\": _(\"Item %(nth)s in the array did not validate:\"),\n }\n\n def __init__(\n self, base_field, *, delimiter=\",\", max_length=None, min_length=None, **kwargs\n ):\n self.base_field = base_field\n self.delimiter = delimiter\n super().__init__(**kwa", "suffix": "ngth\n self.validators.append(ArrayMaxLengthValidator(int(max_length)))\n\n def clean(self, value):\n value = super().clean(value)\n return [self.base_field.clean(val) for val in value]\n\n def prepare_value(self, value):\n if", "middle": "rgs)\n if min_length is not None:\n self.min_length = min_length\n self.validators.append(ArrayMinLengthValidator(int(min_length)))\n if max_length is not None:\n self.max_length = max_le", "meta": {"filepath": "django/contrib/postgres/forms/array.py", "language": "python", "file_size": 8422, "cut_index": 716, "middle_length": 229}} +{"prefix": "_any import (\n DateRange,\n DateTimeTZRange,\n NumericRange,\n)\nfrom django.forms.widgets import HiddenInput, MultiWidget\nfrom django.utils.translation import gettext_lazy as _\n\n__all__ = [\n \"BaseRangeField\",\n \"IntegerRangeField\",\n \"DecimalRangeField\",\n \"DateTimeRangeField\",\n \"DateRangeField\",\n \"HiddenRangeWidget\",\n \"RangeWidget\",\n]\n\n\nclass RangeWidget(MultiWidget):\n def __init__(self, base_widget, attrs=None):\n widgets = (base_widget, base_widget)\n super().__init", "suffix": "input type=\"hidden\"> inputs.\"\"\"\n\n def __init__(self, attrs=None):\n super().__init__(HiddenInput, attrs)\n\n\nclass BaseRangeField(forms.MultiValueField):\n default_error_messages = {\n \"invalid\": _(\"Enter two valid values.\"),\n \"bound_", "middle": "__(widgets, attrs)\n\n def decompress(self, value):\n if value:\n return (value.lower, value.upper)\n return (None, None)\n\n\nclass HiddenRangeWidget(RangeWidget):\n \"\"\"A widget that splits input into two <", "meta": {"filepath": "django/contrib/postgres/forms/ranges.py", "language": "python", "file_size": 3652, "cut_index": 614, "middle_length": 229}} +{"prefix": "ptions import TemplateSyntaxError\nfrom django.template.library import InclusionNode, parse_bits\nfrom django.utils.inspect import getfullargspec\n\n\nclass InclusionAdminNode(InclusionNode):\n \"\"\"\n Template tag that allows its template to be overridden per model, per app,\n or globally.\n \"\"\"\n\n def __init__(self, name, parser, token, func, template_name, takes_context=True):\n self.template_name = template_name\n params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = getfullargsp", "suffix": "teSyntaxError(\n f\"{name!r} sets takes_context=True so {function_name!r} \"\n \"must have a first argument of 'context'\"\n )\n bits = token.split_contents()\n args, kwargs = parse_bits(\n ", "middle": "ec(\n func\n )\n if takes_context:\n if params and params[0] == \"context\":\n del params[0]\n else:\n function_name = func.__name__\n raise Templa", "meta": {"filepath": "django/contrib/admin/templatetags/base.py", "language": "python", "file_size": 1886, "cut_index": 537, "middle_length": 229}} +{"prefix": "t checks\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.text import format_lazy\n\n\ndef prefix_validation_error(error, prefix, code, params):\n \"\"\"\n Prefix a validation error message while maintaining the existing\n validation data structure.\n \"\"\"\n if error.error_list == [error]:\n error_params = error.params or {}\n return ValidationError(\n # We can't simply concatenate messages since they might req", "suffix": " # to an empty string if they are missing it.\n message=format_lazy(\n \"{} {}\",\n SimpleLazyObject(lambda: prefix % params),\n SimpleLazyObject(lambda: error.message % error_params),\n ),\n", "middle": "uire\n # their associated parameters to be expressed correctly which\n # is not something `format_lazy` does. For example, proxied\n # ngettext calls require a count parameter and are converted\n ", "meta": {"filepath": "django/contrib/postgres/utils.py", "language": "python", "file_size": 2021, "cut_index": 563, "middle_length": 229}} +{"prefix": "m django.utils.safestring import SafeData, mark_safe\n\n\nclass MessageEncoder(json.JSONEncoder):\n \"\"\"\n Compactly serialize instances of the ``Message`` class as JSON.\n \"\"\"\n\n message_key = \"__json_message\"\n\n def default(self, obj):\n if isinstance(obj, Message):\n # Using 0/1 here instead of False/True to produce more compact json\n is_safedata = 1 if isinstance(obj.message, SafeData) else 0\n message = [self.message_key, is_safedata, obj.level, obj.message]\n ", "suffix": "es serialized ``Message`` instances.\n \"\"\"\n\n def process_messages(self, obj):\n if isinstance(obj, list) and obj:\n if obj[0] == MessageEncoder.message_key:\n if obj[1]:\n obj[3] = mark_safe(obj[3])\n ", "middle": " if obj.extra_tags is not None:\n message.append(obj.extra_tags)\n return message\n return super().default(obj)\n\n\nclass MessageDecoder(json.JSONDecoder):\n \"\"\"\n Decode JSON that includ", "meta": {"filepath": "django/contrib/messages/storage/cookie.py", "language": "python", "file_size": 8678, "cut_index": 716, "middle_length": 229}} +{"prefix": "gregate\nfrom django.db.models import BitAnd as _BitAnd\nfrom django.db.models import BitOr as _BitOr\nfrom django.db.models import BitXor as _BitXor\nfrom django.db.models import BooleanField, JSONField\nfrom django.db.models import StringAgg as _StringAgg\nfrom django.db.models import Value\nfrom django.utils.deprecation import RemovedInDjango70Warning\n\n__all__ = [\n \"ArrayAgg\",\n \"BitAnd\", # RemovedInDjango70Warning\n \"BitOr\", # RemovedInDjango70Warning\n \"BitXor\", # RemovedInDjango70Warning\n \"Boo", "suffix": "self):\n return ArrayField(self.source_expressions[0].output_field)\n\n\nclass BitAnd(_BitAnd):\n def __init__(self, expression, **extra):\n warnings.warn(\n \"The PostgreSQL-specific BitAnd function is deprecated. Use \"\n \"dj", "middle": "lAnd\",\n \"BoolOr\",\n \"JSONBAgg\",\n \"StringAgg\", # RemovedInDjango70Warning.\n]\n\n\nclass ArrayAgg(Aggregate):\n function = \"ARRAY_AGG\"\n allow_distinct = True\n allow_order_by = True\n\n @property\n def output_field(", "meta": {"filepath": "django/contrib/postgres/aggregates/general.py", "language": "python", "file_size": 3187, "cut_index": 614, "middle_length": 229}} +{"prefix": "ule allows importing AbstractBaseSession even\nwhen django.contrib.sessions is not in INSTALLED_APPS.\n\"\"\"\n\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass BaseSessionManager(models.Manager):\n def encode(self, session_dict):\n \"\"\"\n Return the given session dictionary serialized and encoded as a string.\n \"\"\"\n session_store_class = self.model.get_session_store_class()\n return session_store_class().encode(session_dict)\n\n def save", "suffix": " no data.\n return s\n\n\nclass AbstractBaseSession(models.Model):\n session_key = models.CharField(_(\"session key\"), max_length=40, primary_key=True)\n session_data = models.TextField(_(\"session data\"))\n expire_date = models.DateTimeField(_(\"exp", "middle": "(self, session_key, session_dict, expire_date):\n s = self.model(session_key, self.encode(session_dict), expire_date)\n if session_dict:\n s.save()\n else:\n s.delete() # Clear sessions with", "meta": {"filepath": "django/contrib/sessions/base_session.py", "language": "python", "file_size": 1491, "cut_index": 524, "middle_length": 229}} +{"prefix": "jango.contrib.sessions.base_session import AbstractBaseSession, BaseSessionManager\n\n\nclass SessionManager(BaseSessionManager):\n use_in_migrations = True\n\n\nclass Session(AbstractBaseSession):\n \"\"\"\n Django provides full support for anonymous sessions. The session\n framework lets you store and retrieve arbitrary data on a\n per-site-visitor basis. It stores data on the server side and\n abstracts the sending and receiving of cookies. Cookies contain a\n session ID -- not the data itself.\n\n ", "suffix": "nerable to session-ID theft via the \"Referer\" header.\n\n For complete documentation on using Sessions in your code, consult\n the sessions documentation that is shipped with Django (also available\n on the Django web site).\n \"\"\"\n\n objects = Ses", "middle": " The Django sessions framework is entirely cookie-based. It does\n not fall back to putting session IDs in URLs. This is an intentional\n design decision. Not only does that behavior make URLs ugly, it makes\n your site vul", "meta": {"filepath": "django/contrib/sessions/models.py", "language": "python", "file_size": 1250, "cut_index": 518, "middle_length": 229}} +{"prefix": "nBase, UpdateError\nfrom django.core.cache import caches\n\nKEY_PREFIX = \"django.contrib.sessions.cache\"\n\n\nclass SessionStore(SessionBase):\n \"\"\"\n A cache-based session store.\n \"\"\"\n\n cache_key_prefix = KEY_PREFIX\n\n def __init__(self, session_key=None):\n self._cache = caches[settings.SESSION_CACHE_ALIAS]\n super().__init__(session_key)\n\n @property\n def cache_key(self):\n return self.cache_key_prefix + self._get_or_create_session_key()\n\n async def acache_key(self):\n ", "suffix": "emcache) raise an exception on invalid\n # cache keys. If this happens, reset the session. See #17810.\n session_data = None\n if session_data is not None:\n return session_data\n self._session_key = None\n r", "middle": " return self.cache_key_prefix + await self._aget_or_create_session_key()\n\n def load(self):\n try:\n session_data = self._cache.get(self.cache_key)\n except Exception:\n # Some backends (e.g. m", "meta": {"filepath": "django/contrib/sessions/backends/cache.py", "language": "python", "file_size": 4674, "cut_index": 614, "middle_length": 229}} +{"prefix": "django.db import DatabaseError, IntegrityError, router, transaction\nfrom django.utils import timezone\nfrom django.utils.functional import cached_property\n\n\nclass SessionStore(SessionBase):\n \"\"\"\n Implement database session store.\n \"\"\"\n\n def __init__(self, session_key=None):\n super().__init__(session_key)\n\n @classmethod\n def get_model_class(cls):\n # Avoids a circular import and allows importing SessionStore when\n # django.contrib.sessions is not in INSTALLED_APPS.\n ", "suffix": "lf.model.objects.get(\n session_key=self.session_key, expire_date__gt=timezone.now()\n )\n except (self.model.DoesNotExist, SuspiciousOperation) as e:\n if isinstance(e, SuspiciousOperation):\n logger =", "middle": " from django.contrib.sessions.models import Session\n\n return Session\n\n @cached_property\n def model(self):\n return self.get_model_class()\n\n def _get_session_from_db(self):\n try:\n return se", "meta": {"filepath": "django/contrib/sessions/backends/db.py", "language": "python", "file_size": 6907, "cut_index": 716, "middle_length": 229}} +{"prefix": "SessionStore(SessionBase):\n def load(self):\n \"\"\"\n Load the data from the key itself instead of fetching from some\n external data store. Opposite of _get_session_key(), raise BadSignature\n if signature fails.\n \"\"\"\n try:\n return signing.loads(\n self.session_key,\n serializer=self.serializer,\n # This doesn't handle non-default expiry dates, see #19201\n max_age=self.get_session_cookie_age(),\n ", "suffix": " self.create()\n return {}\n\n async def aload(self):\n return self.load()\n\n def create(self):\n \"\"\"\n To create a new key, set the modified flag so that the cookie is set\n on the client for the current request", "middle": " salt=\"django.contrib.sessions.backends.signed_cookies\",\n )\n except Exception:\n # BadSignature, ValueError, or unpickling exceptions. If any of\n # these happen, reset the session.\n", "meta": {"filepath": "django/contrib/sessions/backends/signed_cookies.py", "language": "python", "file_size": 3218, "cut_index": 614, "middle_length": 229}} +{"prefix": "ngo.views.decorators.debug import sensitive_variables\n\nfrom .signals import user_logged_in, user_logged_out, user_login_failed\n\nSESSION_KEY = \"_auth_user_id\"\nBACKEND_SESSION_KEY = \"_auth_user_backend\"\nHASH_SESSION_KEY = \"_auth_user_hash\"\nREDIRECT_FIELD_NAME = \"next\"\n\n\ndef load_backend(path):\n return import_string(path)()\n\n\ndef _get_backends(return_tuples=False):\n backends = []\n for backend_path in settings.AUTHENTICATION_BACKENDS:\n backend = load_backend(backend_path)\n backends.append", "suffix": "ing?\"\n )\n return backends\n\n\ndef get_backends():\n return _get_backends(return_tuples=False)\n\n\ndef _get_compatible_backends(request, **credentials):\n for backend, backend_path in _get_backends(return_tuples=True):\n backend_signature = ", "middle": "((backend, backend_path) if return_tuples else backend)\n if not backends:\n raise ImproperlyConfigured(\n \"No authentication backends have been defined. Does \"\n \"AUTHENTICATION_BACKENDS contain anyth", "meta": {"filepath": "django/contrib/auth/__init__.py", "language": "python", "file_size": 14635, "cut_index": 921, "middle_length": 229}} +{"prefix": "ray import ArrayField\nfrom django.contrib.postgres.utils import CheckPostgresInstalledMixin\nfrom django.core import exceptions\nfrom django.db.models import Field, TextField, Transform\nfrom django.db.models.fields.mixins import CheckFieldDefaultMixin\nfrom django.utils.translation import gettext_lazy as _\n\n__all__ = [\"HStoreField\"]\n\n\nclass HStoreField(CheckPostgresInstalledMixin, CheckFieldDefaultMixin, Field):\n empty_strings_allowed = False\n description = _(\"Map of strings to strings/nulls\")\n defaul", "suffix": "name):\n transform = super().get_transform(name)\n if transform:\n return transform\n return KeyTransformFactory(name)\n\n def validate(self, value, model_instance):\n super().validate(value, model_instance)\n for k", "middle": "t_error_messages = {\n \"not_a_string\": _(\"The value of “%(key)s” is not a string or null.\"),\n }\n _default_hint = (\"dict\", \"{}\")\n\n def db_type(self, connection):\n return \"hstore\"\n\n def get_transform(self, ", "meta": {"filepath": "django/contrib/postgres/fields/hstore.py", "language": "python", "file_size": 3387, "cut_index": 614, "middle_length": 229}} +{"prefix": "jango.core.exceptions import PermissionDenied\nfrom django.db import router, transaction\nfrom django.http import Http404, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import path, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.utils.html import escape\nfrom django.utils.translation import gettext\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug", "suffix": ", db_field, request=None, **kwargs):\n if db_field.name == \"permissions\":\n qs = kwargs.get(\"queryset\", db_field.remote_field.model.objects)\n # Avoid a major performance hit resolving permission names which\n # triggers", "middle": " import sensitive_post_parameters\n\n\n@admin.register(Group)\nclass GroupAdmin(admin.ModelAdmin):\n search_fields = (\"name\",)\n ordering = (\"name\",)\n filter_horizontal = (\"permissions\",)\n\n def formfield_for_manytomany(self", "meta": {"filepath": "django/contrib/auth/admin.py", "language": "python", "file_size": 10163, "cut_index": 921, "middle_length": 229}} +{"prefix": "apps import AppConfig\nfrom django.core import checks\nfrom django.db.models.query_utils import DeferredAttribute\nfrom django.db.models.signals import post_migrate\nfrom django.utils.translation import gettext_lazy as _\n\nfrom . import get_user_model\nfrom .checks import check_middleware, check_models_permissions, check_user_model\nfrom .management import create_permissions, rename_permissions_after_model_rename\nfrom .signals import user_logged_in\n\n\nclass AuthConfig(AppConfig):\n default_auto_field = \"django.db", "suffix": "tch_uid=\"django.contrib.auth.management.rename_permissions\",\n )\n post_migrate.connect(\n create_permissions,\n dispatch_uid=\"django.contrib.auth.management.create_permissions\",\n )\n last_login_field = getattr(", "middle": ".models.AutoField\"\n name = \"django.contrib.auth\"\n verbose_name = _(\"Authentication and Authorization\")\n\n def ready(self):\n post_migrate.connect(\n rename_permissions_after_model_rename,\n dispa", "meta": {"filepath": "django/contrib/auth/apps.py", "language": "python", "file_size": 1492, "cut_index": 524, "middle_length": 229}} +{"prefix": "ist, return -1.\n \"\"\"\n cls = import_string(class_path)\n for index, path in enumerate(candidate_paths):\n try:\n candidate_cls = import_string(path)\n if issubclass(candidate_cls, cls):\n return index\n except (ImportError, TypeError):\n continue\n return -1\n\n\ndef check_user_model(app_configs, **kwargs):\n if app_configs is None:\n cls = apps.get_model(settings.AUTH_USER_MODEL)\n else:\n app_label, model_name = settings.AUTH_US", "suffix": " against a set of app configs that don't\n # include the specified user model. In this case we simply don't\n # perform the checks defined below.\n return []\n\n errors = []\n\n # Check that REQUIRED_FIELDS is a list\n if ", "middle": "ER_MODEL.split(\".\")\n for app_config in app_configs:\n if app_config.label == app_label:\n cls = app_config.get_model(model_name)\n break\n else:\n # Checks might be run", "meta": {"filepath": "django/contrib/auth/checks.py", "language": "python", "file_size": 9780, "cut_index": 921, "middle_length": 229}} +{"prefix": "ort Aggregate, FloatField, IntegerField\n\n__all__ = [\n \"CovarPop\",\n \"Corr\",\n \"RegrAvgX\",\n \"RegrAvgY\",\n \"RegrCount\",\n \"RegrIntercept\",\n \"RegrR2\",\n \"RegrSlope\",\n \"RegrSXX\",\n \"RegrSXY\",\n \"RegrSYY\",\n \"StatAggregate\",\n]\n\n\nclass StatAggregate(Aggregate):\n output_field = FloatField()\n\n def __init__(self, y, x, output_field=None, filter=None, default=None):\n if not x or not y:\n raise ValueError(\"Both y and x must be provided.\")\n super().__init__(\n ", "suffix": "t=None):\n self.function = \"COVAR_SAMP\" if sample else \"COVAR_POP\"\n super().__init__(y, x, filter=filter, default=default)\n\n\nclass RegrAvgX(StatAggregate):\n function = \"REGR_AVGX\"\n\n\nclass RegrAvgY(StatAggregate):\n function = \"REGR_AVGY\"\n", "middle": " y, x, output_field=output_field, filter=filter, default=default\n )\n\n\nclass Corr(StatAggregate):\n function = \"CORR\"\n\n\nclass CovarPop(StatAggregate):\n def __init__(self, y, x, sample=False, filter=None, defaul", "meta": {"filepath": "django/contrib/postgres/aggregates/statistics.py", "language": "python", "file_size": 1511, "cut_index": 537, "middle_length": 229}} +{"prefix": "itive file systems.\nVALID_KEY_CHARS = string.ascii_lowercase + string.digits\n\n\nclass CreateError(Exception):\n \"\"\"\n Used internally as a consistent exception type to catch from save (see the\n docstring for SessionBase.save() for details).\n \"\"\"\n\n pass\n\n\nclass UpdateError(Exception):\n \"\"\"\n Occurs if Django tries to update a session that was deleted.\n \"\"\"\n\n pass\n\n\nclass SessionBase:\n \"\"\"\n Base class for all Session classes.\n \"\"\"\n\n TEST_COOKIE_NAME = \"testcookie\"\n TEST_C", "suffix": "ring(settings.SESSION_SERIALIZER)\n\n def __contains__(self, key):\n return key in self._session\n\n def __getitem__(self, key):\n return self._session[key]\n\n def __setitem__(self, key, value):\n self._session[key] = value\n se", "middle": "OOKIE_VALUE = \"worked\"\n\n __not_given = object()\n\n def __init__(self, session_key=None):\n self._session_key = session_key\n self.accessed = False\n self.modified = False\n self.serializer = import_st", "meta": {"filepath": "django/contrib/sessions/backends/base.py", "language": "python", "file_size": 17040, "cut_index": 921, "middle_length": 229}} +{"prefix": "onBase,\n UpdateError,\n)\nfrom django.contrib.sessions.exceptions import InvalidSessionKey\nfrom django.core.exceptions import ImproperlyConfigured, SuspiciousOperation\n\n\nclass SessionStore(SessionBase):\n \"\"\"\n Implement a file based session store.\n \"\"\"\n\n def __init__(self, session_key=None):\n self.storage_path = self._get_storage_path()\n self.file_prefix = settings.SESSION_COOKIE_NAME\n super().__init__(session_key)\n\n @classmethod\n def _get_storage_path(cls):\n tr", "suffix": "torage path is valid.\n if not os.path.isdir(storage_path):\n raise ImproperlyConfigured(\n \"The session storage path %r doesn't exist. Please set your\"\n \" SESSION_FILE_PATH setting to an existin", "middle": "y:\n return cls._storage_path\n except AttributeError:\n storage_path = (\n getattr(settings, \"SESSION_FILE_PATH\", None) or tempfile.gettempdir()\n )\n # Make sure the s", "meta": {"filepath": "django/contrib/sessions/backends/file.py", "language": "python", "file_size": 8188, "cut_index": 716, "middle_length": 229}} +{"prefix": " django.contrib.sessions.models\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = []\n\n operations = [\n migrations.CreateModel(\n name=\"Session\",\n fields=[\n (\n \"session_key\",\n models.CharField(\n max_length=40,\n serialize=False,\n verbose_name=\"session key\",\n primary_key=True,\n ", "suffix": "ate\", db_index=True),\n ),\n ],\n options={\n \"abstract\": False,\n \"db_table\": \"django_session\",\n \"verbose_name\": \"session\",\n \"verbose_name_plural\": \"sessions\",\n ", "middle": " ),\n ),\n (\"session_data\", models.TextField(verbose_name=\"session data\")),\n (\n \"expire_date\",\n models.DateTimeField(verbose_name=\"expire d", "meta": {"filepath": "django/contrib/sessions/migrations/0001_initial.py", "language": "python", "file_size": 1148, "cut_index": 518, "middle_length": 229}} +{"prefix": " def authenticate(self, request, **kwargs):\n return None\n\n async def aauthenticate(self, request, **kwargs):\n return await sync_to_async(self.authenticate)(request, **kwargs)\n\n def get_user(self, user_id):\n return None\n\n async def aget_user(self, user_id):\n return await sync_to_async(self.get_user)(user_id)\n\n def get_user_permissions(self, user_obj, obj=None):\n return set()\n\n async def aget_user_permissions(self, user_obj, obj=None):\n return await ", "suffix": "async(self.get_group_permissions)(user_obj, obj)\n\n def get_all_permissions(self, user_obj, obj=None):\n return {\n *self.get_user_permissions(user_obj, obj=obj),\n *self.get_group_permissions(user_obj, obj=obj),\n }\n\n ", "middle": "sync_to_async(self.get_user_permissions)(user_obj, obj)\n\n def get_group_permissions(self, user_obj, obj=None):\n return set()\n\n async def aget_group_permissions(self, user_obj, obj=None):\n return await sync_to_", "meta": {"filepath": "django/contrib/auth/backends.py", "language": "python", "file_size": 12899, "cut_index": 921, "middle_length": 229}} +{"prefix": "kupDict proxy the permissions system into objects that\n# the template system can understand.\n\n\nclass PermLookupDict:\n def __init__(self, user, app_label):\n self.user, self.app_label = user, app_label\n\n def __repr__(self):\n return str(self.user.get_all_permissions())\n\n def __getitem__(self, perm_name):\n return self.user.has_perm(\"%s.%s\" % (self.app_label, perm_name))\n\n def __iter__(self):\n # To fix 'item in perms.someapp' and __getitem__ interaction we need to\n ", "suffix": "user):\n self.user = user\n\n def __repr__(self):\n return f\"{self.__class__.__qualname__}({self.user!r})\"\n\n def __getitem__(self, app_label):\n return PermLookupDict(self.user, app_label)\n\n def __iter__(self):\n # I am large", "middle": "# define __iter__. See #18979 for details.\n raise TypeError(\"PermLookupDict is not iterable.\")\n\n def __bool__(self):\n return self.user.has_module_perms(self.app_label)\n\n\nclass PermWrapper:\n def __init__(self, ", "meta": {"filepath": "django/contrib/auth/context_processors.py", "language": "python", "file_size": 1911, "cut_index": 537, "middle_length": 229}} +{"prefix": "sessions.backends.base import UpdateError\nfrom django.contrib.sessions.exceptions import SessionInterrupted\nfrom django.utils.cache import patch_vary_headers\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.http import http_date\n\n\nclass SessionMiddleware(MiddlewareMixin):\n def __init__(self, get_response):\n super().__init__(get_response)\n engine = import_module(settings.SESSION_ENGINE)\n self.SessionStore = engine.SessionStore\n\n def process_request(self, reque", "suffix": "modified, or if the configuration is to save the\n session every time, save the changes and set a session cookie or delete\n the session cookie if the session has been emptied.\n \"\"\"\n try:\n accessed = request.session.acc", "middle": "st):\n session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)\n request.session = self.SessionStore(session_key)\n\n def process_response(self, request, response):\n \"\"\"\n If request.session was ", "meta": {"filepath": "django/contrib/sessions/middleware.py", "language": "python", "file_size": 3755, "cut_index": 614, "middle_length": 229}} +{"prefix": "o.contrib.sessions.backends.db import SessionStore as DBStore\nfrom django.core.cache import caches\n\nKEY_PREFIX = \"django.contrib.sessions.cached_db\"\n\nlogger = logging.getLogger(\"django.contrib.sessions\")\n\n\nclass SessionStore(DBStore):\n \"\"\"\n Implement cached, database backed sessions.\n \"\"\"\n\n cache_key_prefix = KEY_PREFIX\n\n def __init__(self, session_key=None):\n self._cache = caches[settings.SESSION_CACHE_ALIAS]\n super().__init__(session_key)\n\n @property\n def cache_key(self)", "suffix": " data = self._cache.get(self.cache_key)\n except Exception:\n # Some backends (e.g. memcache) raise an exception on invalid\n # cache keys. If this happens, reset the session. See #17810.\n data = None\n\n if da", "middle": ":\n return self.cache_key_prefix + self._get_or_create_session_key()\n\n async def acache_key(self):\n return self.cache_key_prefix + await self._aget_or_create_session_key()\n\n def load(self):\n try:\n ", "meta": {"filepath": "django/contrib/sessions/backends/cached_db.py", "language": "python", "file_size": 4148, "cut_index": 614, "middle_length": 229}} +{"prefix": "PS.\n\"\"\"\n\nimport unicodedata\n\nfrom django.conf import settings\nfrom django.contrib.auth import password_validation\nfrom django.contrib.auth.hashers import (\n acheck_password,\n check_password,\n is_password_usable,\n make_password,\n)\nfrom django.db import models\nfrom django.utils.crypto import salted_hmac\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass BaseUserManager(models.Manager):\n @classmethod\n def normalize_email(cls, email):\n \"\"\"\n Normalize the email address", "suffix": "email = email_name + \"@\" + domain_part.lower()\n return email\n\n def get_by_natural_key(self, username):\n return self.get(**{self.model.USERNAME_FIELD: username})\n\n async def aget_by_natural_key(self, username):\n return await self.", "middle": " by lowercasing the domain part of it.\n \"\"\"\n email = email or \"\"\n try:\n email_name, domain_part = email.strip().rsplit(\"@\", 1)\n except ValueError:\n pass\n else:\n ", "meta": {"filepath": "django/contrib/auth/base_user.py", "language": "python", "file_size": 4893, "cut_index": 614, "middle_length": 229}} +{"prefix": "db.models import CharField, EmailField, TextField\n\n__all__ = [\"CICharField\", \"CIEmailField\", \"CITextField\"]\n\n\nclass CICharField(CharField):\n system_check_removed_details = {\n \"msg\": (\n \"django.contrib.postgres.fields.CICharField is removed except for support \"\n \"in historical migrations.\"\n ),\n \"hint\": (\n 'Use CharField(db_collation=\"…\") with a case-insensitive non-deterministic '\n \"collation instead.\"\n ),\n \"id\": \"fields.E905\",", "suffix": " ),\n \"hint\": (\n 'Use EmailField(db_collation=\"…\") with a case-insensitive '\n \"non-deterministic collation instead.\"\n ),\n \"id\": \"fields.E906\",\n }\n\n\nclass CITextField(TextField):\n system_check_removed_detail", "middle": "\n }\n\n\nclass CIEmailField(EmailField):\n system_check_removed_details = {\n \"msg\": (\n \"django.contrib.postgres.fields.CIEmailField is removed except for support \"\n \"in historical migrations.\"\n ", "meta": {"filepath": "django/contrib/postgres/fields/citext.py", "language": "python", "file_size": 1363, "cut_index": 524, "middle_length": 229}} +{"prefix": "om .utils import AttributeSetter\n\n__all__ = [\n \"RangeField\",\n \"IntegerRangeField\",\n \"BigIntegerRangeField\",\n \"DecimalRangeField\",\n \"DateTimeRangeField\",\n \"DateRangeField\",\n \"RangeBoundary\",\n \"RangeOperators\",\n]\n\n\nclass RangeBoundary(models.Expression):\n \"\"\"A class that represents range boundaries.\"\"\"\n\n def __init__(self, inclusive_lower=True, inclusive_upper=False):\n self.lower = \"[\" if inclusive_lower else \"(\"\n self.upper = \"]\" if inclusive_upper else \")\"\n\n de", "suffix": "_EQUAL = \"<>\"\n CONTAINS = \"@>\"\n CONTAINED_BY = \"<@\"\n OVERLAPS = \"&&\"\n FULLY_LT = \"<<\"\n FULLY_GT = \">>\"\n NOT_LT = \"&>\"\n NOT_GT = \"&<\"\n ADJACENT_TO = \"-|-\"\n\n\nclass RangeField(CheckPostgresInstalledMixin, models.Field):\n empty_strin", "middle": "f as_sql(self, compiler, connection):\n return \"'%s%s'\" % (self.lower, self.upper), []\n\n\nclass RangeOperators:\n # https://www.postgresql.org/docs/current/functions-range.html#RANGE-OPERATORS-TABLE\n EQUAL = \"=\"\n NOT", "meta": {"filepath": "django/contrib/postgres/fields/ranges.py", "language": "python", "file_size": 11682, "cut_index": 921, "middle_length": 229}} +{"prefix": "(encoded):\n \"\"\"\n Return True if this password wasn't generated by\n User.set_unusable_password(), i.e. make_password(None).\n \"\"\"\n return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX)\n\n\ndef verify_password(password, encoded, preferred=\"default\"):\n \"\"\"\n Return two booleans. The first is whether the raw password matches the\n three part encoded digest, and the second whether to regenerate the\n password.\n \"\"\"\n fake_runtime = password is None or not is_passwor", "suffix": " True\n\n if fake_runtime:\n # Run the default password hasher once to reduce the timing difference\n # between an existing user with an unusable password and a nonexistent\n # user or missing hasher (similar to #20760).\n make_pas", "middle": "d_usable(encoded)\n\n preferred = get_hasher(preferred)\n try:\n hasher = identify_hasher(encoded)\n except ValueError:\n # encoded is gibberish or uses a hasher that's no longer installed.\n fake_runtime =", "meta": {"filepath": "django/contrib/auth/hashers.py", "language": "python", "file_size": 23765, "cut_index": 1331, "middle_length": 229}} +{"prefix": "DIRECT_FIELD_NAME\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.core.exceptions import ImproperlyConfigured, PermissionDenied\nfrom django.shortcuts import resolve_url\n\n\nclass AccessMixin:\n \"\"\"\n Abstract CBV mixin that gives access mixins the same customizable\n functionality.\n \"\"\"\n\n login_url = None\n permission_denied_message = \"\"\n raise_exception = False\n redirect_field_name = REDIRECT_FIELD_NAME\n\n def get_login_url(self):\n \"\"\"\n Override this me", "suffix": "ng the login_url attribute. Define \"\n f\"{self.__class__.__name__}.login_url, settings.LOGIN_URL, or override \"\n f\"{self.__class__.__name__}.get_login_url().\"\n )\n return str(login_url)\n\n def get_permission_", "middle": "thod to override the login_url attribute.\n \"\"\"\n login_url = self.login_url or settings.LOGIN_URL\n if not login_url:\n raise ImproperlyConfigured(\n f\"{self.__class__.__name__} is missi", "meta": {"filepath": "django/contrib/auth/mixins.py", "language": "python", "file_size": 4660, "cut_index": 614, "middle_length": 229}} +{"prefix": "tring\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import ngettext\n\n\n@functools.cache\ndef get_default_password_validators():\n return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)\n\n\ndef get_password_validators(validator_config):\n validators = []\n for validator in validator_config:\n try:\n klass = import_string(validator[\"NAME\"])\n except ImportError:\n msg = (\n \"The module in NAME could not be imported: %", "suffix": "tors\n\n\ndef validate_password(password, user=None, password_validators=None):\n \"\"\"\n Validate that the password meets all validator requirements.\n\n If the password is valid, return ``None``.\n If the password is invalid, raise ValidationError with", "middle": "s. Check your \"\n \"AUTH_PASSWORD_VALIDATORS setting.\"\n )\n raise ImproperlyConfigured(msg % validator[\"NAME\"])\n validators.append(klass(**validator.get(\"OPTIONS\", {})))\n\n return valida", "meta": {"filepath": "django/contrib/auth/password_validation.py", "language": "python", "file_size": 9635, "cut_index": 921, "middle_length": 229}} +{"prefix": "views used below are normally mapped in the AdminSite instance.\n# This URLs file is used to provide a reliable view deployment for test\n# purposes. It is also provided as a convenience to those who want to deploy\n# these URLs elsewhere.\n\nfrom django.contrib.auth import views\nfrom django.urls import path\n\nurlpatterns = [\n path(\"login/\", views.LoginView.as_view(), name=\"login\"),\n path(\"logout/\", views.LogoutView.as_view(), name=\"logout\"),\n path(\n \"password_change/\", views.PasswordChangeView.as", "suffix": "view(), name=\"password_reset\"),\n path(\n \"password_reset/done/\",\n views.PasswordResetDoneView.as_view(),\n name=\"password_reset_done\",\n ),\n path(\n \"reset/<uidb64>/<token>/\",\n views.PasswordResetConfirmView.as_view(", "middle": "_view(), name=\"password_change\"\n ),\n path(\n \"password_change/done/\",\n views.PasswordChangeDoneView.as_view(),\n name=\"password_change_done\",\n ),\n path(\"password_reset/\", views.PasswordResetView.as_", "meta": {"filepath": "django/contrib/auth/urls.py", "language": "python", "file_size": 1185, "cut_index": 518, "middle_length": 229}} +{"prefix": "m django.contrib import auth\n\nUserModel = auth.get_user_model()\n\n\ndef _get_user(username):\n \"\"\"\n Return the UserModel instance for `username`.\n\n If no matching user exists, or if the user is inactive, return None.\n \"\"\"\n try:\n user = UserModel._default_manager.get_by_natural_key(username)\n except UserModel.DoesNotExist:\n user = None\n else:\n if not user.is_active:\n user = None\n return user\n\n\ndef check_password(environ, username, password):\n \"\"\"\n Au", "suffix": "user exists but\n password is not correct, and return True otherwise.\n\n \"\"\"\n # db connection state is managed similarly to the wsgi handler\n # as mod_wsgi may call these functions outside of a request/response cycle\n db.reset_queries()\n tr", "middle": "thenticate against Django's auth database.\n\n mod_wsgi docs specify None, True, False as return value depending\n on whether the user exists and authenticates.\n\n Return None if the user does not exist, return False if the ", "meta": {"filepath": "django/contrib/auth/handlers/modwsgi.py", "language": "python", "file_size": 1634, "cut_index": 537, "middle_length": 229}} +{"prefix": "_user_model\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.core.exceptions import ValidationError\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import DEFAULT_DB_ALIAS, connections\n\nUserModel = get_user_model()\n\n\nclass Command(BaseCommand):\n help = \"Change a user's password for django.contrib.auth.\"\n requires_migrations_checks = True\n requires_system_checks = []\n\n def _get_pass(self, prompt=\"Password: \"):\n p = getpass.g", "suffix": "=(\n \"Username to change password for; by default, it's the current \"\n \"username.\"\n ),\n )\n parser.add_argument(\n \"--database\",\n default=DEFAULT_DB_ALIAS,\n choices=tuple(", "middle": "etpass(prompt=prompt)\n if not p:\n raise CommandError(\"aborted\")\n return p\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"username\",\n nargs=\"?\",\n help", "meta": {"filepath": "django/contrib/auth/management/commands/changepassword.py", "language": "python", "file_size": 2686, "cut_index": 563, "middle_length": 229}} +{"prefix": "ncies = [\n (\"contenttypes\", \"__first__\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"Permission\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n primary_key=True,\n ),\n ),\n (\"name\", models.CharField(max_length=50, ver", "suffix": " verbose_name=\"content type\",\n ),\n ),\n (\"codename\", models.CharField(max_length=100, verbose_name=\"codename\")),\n ],\n options={\n \"ordering\": [\n ", "middle": "bose_name=\"name\")),\n (\n \"content_type\",\n models.ForeignKey(\n to=\"contenttypes.ContentType\",\n on_delete=models.CASCADE,\n ", "meta": {"filepath": "django/contrib/auth/migrations/0001_initial.py", "language": "python", "file_size": 7281, "cut_index": 716, "middle_length": 229}} +{"prefix": "django.contrib.auth import validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"auth\", \"0006_require_contenttypes_0002\"),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=\"user\",\n name=\"username\",\n field=models.CharField(\n error_messages={\"unique\": \"A user with that username already exists.\"},\n help_text=(\n \"Required. 30 characters or fe", "suffix": "digits and @/./+/-/_ \"\n \"only.\"\n ),\n max_length=30,\n unique=True,\n validators=[validators.UnicodeUsernameValidator()],\n verbose_name=\"username\",\n ),\n ", "middle": "wer. Letters, ", "meta": {"filepath": "django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py", "language": "python", "file_size": 802, "cut_index": 517, "middle_length": 14}} +{"prefix": "t color_style\nfrom django.db import IntegrityError, migrations, transaction\nfrom django.db.models import Q\n\nWARNING = \"\"\"\n A problem arose migrating proxy model permissions for {old} to {new}.\n\n Permission(s) for {new} already existed.\n Codenames Q: {query}\n\n Ensure to audit ALL permissions for {old} and {new}.\n\"\"\"\n\n\ndef update_proxy_model_permissions(apps, schema_editor, reverse=False):\n \"\"\"\n Update the content_type of proxy model permissions to use the ContentType\n of the proxy mo", "suffix": "els():\n opts = Model._meta\n if not opts.proxy:\n continue\n proxy_default_permissions_codenames = [\n \"%s_%s\" % (action, opts.model_name) for action in opts.default_permissions\n ]\n permissions_query = Q", "middle": "del.\n \"\"\"\n style = color_style()\n Permission = apps.get_model(\"auth\", \"Permission\")\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n alias = schema_editor.connection.alias\n for Model in apps.get_mod", "meta": {"filepath": "django/contrib/auth/migrations/0011_update_proxy_permissions.py", "language": "python", "file_size": 2860, "cut_index": 563, "middle_length": 229}} +{"prefix": "age\n\n__all__ = (\n \"add_message\",\n \"get_messages\",\n \"get_level\",\n \"set_level\",\n \"debug\",\n \"info\",\n \"success\",\n \"warning\",\n \"error\",\n \"MessageFailure\",\n)\n\n\nclass MessageFailure(Exception):\n pass\n\n\ndef add_message(request, level, message, extra_tags=\"\", fail_silently=False):\n \"\"\"\n Attempt to add a message to the request using the 'messages' app.\n \"\"\"\n try:\n messages = request._messages\n except AttributeError:\n if not hasattr(request, \"META\"):\n ", "suffix": "(\n \"You cannot add messages without installing \"\n \"django.contrib.messages.middleware.MessageMiddleware\"\n )\n else:\n return messages.add(level, message, extra_tags)\n\n\ndef get_messages(request):\n \"\"\"\n ", "middle": " raise TypeError(\n \"add_message() argument must be an HttpRequest object, not \"\n \"'%s'.\" % request.__class__.__name__\n )\n if not fail_silently:\n raise MessageFailure", "meta": {"filepath": "django/contrib/messages/api.py", "language": "python", "file_size": 3250, "cut_index": 614, "middle_length": 229}} +{"prefix": "age:\n \"\"\"\n Represent an actual message that can be stored in any of the supported\n storage classes (typically session- or cookie-based) and rendered in a view\n or template.\n \"\"\"\n\n def __init__(self, level, message, extra_tags=None):\n self.level = int(level)\n self.message = message\n self.extra_tags = extra_tags\n\n def _prepare(self):\n \"\"\"\n Prepare the message for serialization by forcing the ``message``\n and ``extra_tags`` to str in case they are ", "suffix": "e):\n return NotImplemented\n return self.level == other.level and self.message == other.message\n\n def __str__(self):\n return str(self.message)\n\n def __repr__(self):\n extra_tags = f\", extra_tags={self.extra_tags!r}\" if s", "middle": "lazy translations.\n \"\"\"\n self.message = str(self.message)\n self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None\n\n def __eq__(self, other):\n if not isinstance(other, Messag", "meta": {"filepath": "django/contrib/messages/storage/base.py", "language": "python", "file_size": 6082, "cut_index": 716, "middle_length": 229}} +{"prefix": "ger(\"django.contrib.auth\")\n\n\ndef _unicode_ci_compare(s1, s2):\n \"\"\"\n Perform case-insensitive comparison of two identifiers, using the\n recommended algorithm from Unicode Technical Report 36, section\n 2.11.2(B)(2).\n \"\"\"\n return (\n unicodedata.normalize(\"NFKC\", s1).casefold()\n == unicodedata.normalize(\"NFKC\", s2).casefold()\n )\n\n\nclass ReadOnlyPasswordHashWidget(forms.Widget):\n template_name = \"auth/widgets/read_only_password_hash.html\"\n\n def get_context(self, name, val", "suffix": "e_password else _(\"Set password\")\n )\n return context\n\n def id_for_label(self, id_):\n return None\n\n\nclass ReadOnlyPasswordHashField(forms.Field):\n widget = ReadOnlyPasswordHashWidget\n\n def __init__(self, *args, **kwargs):\n ", "middle": "ue, attrs):\n context = super().get_context(name, value, attrs)\n usable_password = value and not value.startswith(UNUSABLE_PASSWORD_PREFIX)\n context[\"button_label\"] = (\n _(\"Reset password\") if usabl", "meta": {"filepath": "django/contrib/auth/forms.py", "language": "python", "file_size": 20800, "cut_index": 1331, "middle_length": 229}} +{"prefix": "login\"])\n\n\nclass PermissionManager(models.Manager):\n use_in_migrations = True\n\n def get_by_natural_key(self, codename, app_label, model):\n return self.get(\n codename=codename,\n content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(\n app_label, model\n ),\n )\n\n\nclass Permission(models.Model):\n \"\"\"\n The permissions system provides a way to assign permissions to specific\n users and groups of users.\n\n The permission ", "suffix": "nd add an object.\n - The \"change\" permission limits a user's ability to view the change\n list, view the \"change\" form and change an object.\n - The \"delete\" permission limits the ability to delete an object.\n - The \"view\" permi", "middle": "system is used by the Django admin site, but may also be\n useful in your own code. The Django admin site uses permissions as follows:\n\n - The \"add\" permission limits the user's ability to view the \"add\" form\n a", "meta": {"filepath": "django/contrib/auth/models.py", "language": "python", "file_size": 21479, "cut_index": 1331, "middle_length": 229}} +{"prefix": "t login_not_required, login_required\nfrom django.contrib.auth.forms import (\n AuthenticationForm,\n PasswordChangeForm,\n PasswordResetForm,\n SetPasswordForm,\n)\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.exceptions import ImproperlyConfigured, ValidationError\nfrom django.http import HttpResponseRedirect, QueryDict\nfrom django.shortcuts import resolve_url\nfrom django.urls import reverse_lazy\nfrom django", "suffix": "_cache\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic.edit import FormView\n\nUserModel = get_user_model()", "middle": ".utils.decorators import method_decorator\nfrom django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views.decorators.cache import never", "meta": {"filepath": "django/contrib/auth/views.py", "language": "python", "file_size": 13870, "cut_index": 921, "middle_length": 229}} +{"prefix": "connections\nfrom django.utils.functional import cached_property\nfrom django.utils.text import capfirst\n\n\nclass NotRunningInTTYException(Exception):\n pass\n\n\nPASSWORD_FIELD = \"password\"\n\n\nclass Command(BaseCommand):\n help = \"Used to create a superuser.\"\n requires_migrations_checks = True\n stealth_options = (\"stdin\",)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.UserModel = get_user_model()\n self.username_field = self.UserModel._meta.get_fi", "suffix": "er.\",\n )\n parser.add_argument(\n \"--noinput\",\n \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=(\n \"Tells Django to NOT prompt the user for input of any kind.", "middle": "eld(\n self.UserModel.USERNAME_FIELD\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--%s\" % self.UserModel.USERNAME_FIELD,\n help=\"Specifies the login for the superus", "meta": {"filepath": "django/contrib/auth/management/commands/createsuperuser.py", "language": "python", "file_size": 13740, "cut_index": 921, "middle_length": 229}} +{"prefix": "o.contrib.auth import validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"auth\", \"0007_alter_validators_add_error_messages\"),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=\"user\",\n name=\"username\",\n field=models.CharField(\n error_messages={\"unique\": \"A user with that username already exists.\"},\n help_text=(\n \"Required. 150 characters", "suffix": "ters, digits and @/./+/-/_ \"\n \"only.\"\n ),\n max_length=150,\n unique=True,\n validators=[validators.UnicodeUsernameValidator()],\n verbose_name=\"username\",\n ", "middle": " or fewer. Let", "meta": {"filepath": "django/contrib/auth/migrations/0008_alter_user_username_max_length.py", "language": "python", "file_size": 814, "cut_index": 522, "middle_length": 14}} +{"prefix": "import default_storage\nfrom django.utils.deprecation import MiddlewareMixin\n\n\nclass MessageMiddleware(MiddlewareMixin):\n \"\"\"\n Middleware that handles temporary messages.\n \"\"\"\n\n def process_request(self, request):\n request._messages = default_storage(request)\n\n def process_response(self, request, response):\n \"\"\"\n Update the storage backend (i.e., save the messages).\n\n Raise ValueError if not all messages could be stored and DEBUG is True.\n \"\"\"\n # A hig", "suffix": " not contain\n # messages storage, so make no assumption that it will be there.\n if hasattr(request, \"_messages\"):\n unstored_messages = request._messages.update(response)\n if unstored_messages and settings.DEBUG:\n ", "middle": "her middleware layer may return a request which does", "meta": {"filepath": "django/contrib/messages/middleware.py", "language": "python", "file_size": 986, "cut_index": 582, "middle_length": 52}} +{"prefix": "ImproperlyConfigured\nfrom django.core.handlers.asgi import ASGIRequest\nfrom django.shortcuts import resolve_url\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.utils.functional import SimpleLazyObject\n\n\ndef get_user(request):\n if not hasattr(request, \"_cached_user\"):\n request._cached_user = auth.get_user(request)\n return request._cached_user\n\n\nasync def auser(request):\n if not hasattr(request, \"_acached_user\"):\n request._acached_user = await auth.aget_user(request)\n ", "suffix": "ango authentication middleware requires session \"\n \"middleware to be installed. Edit your MIDDLEWARE setting to \"\n \"insert \"\n \"'django.contrib.sessions.middleware.SessionMiddleware' before \"\n \"'dj", "middle": " return request._acached_user\n\n\nclass AuthenticationMiddleware(MiddlewareMixin):\n def process_request(self, request):\n if not hasattr(request, \"session\"):\n raise ImproperlyConfigured(\n \"The Dj", "meta": {"filepath": "django/contrib/auth/middleware.py", "language": "python", "file_size": 11826, "cut_index": 921, "middle_length": 229}} +{"prefix": "style\nfrom django.db import DEFAULT_DB_ALIAS, migrations, router, transaction\n\n\ndef _get_all_permissions(opts):\n \"\"\"\n Return (codename, name) for all permissions in the given opts.\n \"\"\"\n return [*_get_builtin_permissions(opts), *opts.permissions]\n\n\ndef _get_builtin_permissions(opts):\n \"\"\"\n Return (codename, name) for all autogenerated permissions.\n By default, this is ('add', 'change', 'delete', 'view')\n \"\"\"\n perms = []\n for action in opts.default_permissions:\n perms.app", "suffix": "sity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n if not app_config.models_module:\n return\n\n try:\n Permission = apps.get_model(\"auth\", \"Permission\")\n except LookupError:\n return\n", "middle": "end(\n (\n get_permission_codename(action, opts),\n \"Can %s %s\" % (action, opts.verbose_name_raw),\n )\n )\n return perms\n\n\ndef create_permissions(\n app_config,\n verbo", "meta": {"filepath": "django/contrib/auth/management/__init__.py", "language": "python", "file_size": 9225, "cut_index": 921, "middle_length": 229}} +{"prefix": "template import Library\nfrom django.utils.html import format_html, format_html_join\nfrom django.utils.translation import gettext\n\nregister = Library()\n\n\n@register.simple_tag\ndef render_password_as_hash(value):\n if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX):\n return format_html(\"<p><strong>{}</strong></p>\", gettext(\"No password set.\"))\n try:\n hasher = identify_hasher(value)\n hashed_summary = hasher.safe_summary(value)\n except ValueError:\n return format_html(\n", "suffix": " gettext(\"Invalid password format or unknown hashing algorithm.\"),\n )\n items = [(gettext(key), val) for key, val in hashed_summary.items()]\n return format_html(\n \"<p>{}</p>\",\n format_html_join(\" \", \"<strong>{}</strong>: <bdi>{}<", "middle": " \"<p><strong>{}</strong></p>\",\n ", "meta": {"filepath": "django/contrib/auth/templatetags/auth.py", "language": "python", "file_size": 936, "cut_index": 606, "middle_length": 52}} +{"prefix": "nt_time_compare, salted_hmac\nfrom django.utils.http import base36_to_int, int_to_base36\n\n\nclass PasswordResetTokenGenerator:\n \"\"\"\n Strategy object used to generate and check tokens for the password\n reset mechanism.\n \"\"\"\n\n key_salt = \"django.contrib.auth.tokens.PasswordResetTokenGenerator\"\n algorithm = None\n _secret = None\n _secret_fallbacks = None\n\n def __init__(self):\n self.algorithm = self.algorithm or \"sha256\"\n\n def _get_secret(self):\n return self._secret or s", "suffix": "ttings.SECRET_KEY_FALLBACKS\n return self._secret_fallbacks\n\n def _set_fallbacks(self, fallbacks):\n self._secret_fallbacks = fallbacks\n\n secret_fallbacks = property(_get_fallbacks, _set_fallbacks)\n\n def make_token(self, user):\n ", "middle": "ettings.SECRET_KEY\n\n def _set_secret(self, secret):\n self._secret = secret\n\n secret = property(_get_secret, _set_secret)\n\n def _get_fallbacks(self):\n if self._secret_fallbacks is None:\n return se", "meta": {"filepath": "django/contrib/auth/tokens.py", "language": "python", "file_size": 4328, "cut_index": 614, "middle_length": 229}} +{"prefix": " django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"auth\", \"0003_alter_user_email_max_length\"),\n ]\n\n # No database changes; modifies validators and error_messages (#13147).\n operations = [\n migrations.AlterField(\n model_name=\"user\",\n name=\"username\",\n field=models.CharField(\n error_messages={\"unique\": \"A user with that username already exists.\"},\n max_length=30,\n ", "suffix": "()],\n help_text=(\n \"Required. 30 characters or fewer. Letters, digits and @/./+/-/_ \"\n \"only.\"\n ),\n unique=True,\n verbose_name=\"username\",\n ),\n ", "middle": " validators=[validators.UnicodeUsernameValidator", "meta": {"filepath": "django/contrib/auth/migrations/0004_alter_user_username_opts.py", "language": "python", "file_size": 880, "cut_index": 559, "middle_length": 52}} +{"prefix": "seStorage\nfrom django.contrib.messages.storage.cookie import CookieStorage\nfrom django.contrib.messages.storage.session import SessionStorage\n\n\nclass FallbackStorage(BaseStorage):\n \"\"\"\n Try to store all messages in the first backend. Store any unstored\n messages in each subsequent backend.\n \"\"\"\n\n storage_classes = (CookieStorage, SessionStorage)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.storages = [\n storage_class(*args, **kwar", "suffix": "l_messages = []\n for storage in self.storages:\n messages, all_retrieved = storage._get()\n # If the backend hasn't been used, no more retrieval is necessary.\n if messages is None:\n break\n if ", "middle": "gs) for storage_class in self.storage_classes\n ]\n self._used_storages = set()\n\n def _get(self, *args, **kwargs):\n \"\"\"\n Get a single list of messages from all storage backends.\n \"\"\"\n al", "meta": {"filepath": "django/contrib/messages/storage/fallback.py", "language": "python", "file_size": 2093, "cut_index": 563, "middle_length": 229}} +{"prefix": "ngo.conf import STATICFILES_STORAGE_ALIAS, settings\nfrom django.contrib.staticfiles.finders import get_finders\nfrom django.core.checks import Error\n\nE005 = Error(\n f\"The STORAGES setting must define a '{STATICFILES_STORAGE_ALIAS}' storage.\",\n id=\"staticfiles.E005\",\n)\n\n\ndef check_finders(app_configs, **kwargs):\n \"\"\"Check all registered staticfiles finders.\"\"\"\n errors = []\n for finder in get_finders():\n try:\n finder_errors = finder.check()\n except NotImplementedError:\n ", "suffix": "end(finder_errors)\n return errors\n\n\ndef check_storages(app_configs, **kwargs):\n \"\"\"Ensure staticfiles is defined in STORAGES setting.\"\"\"\n errors = []\n if STATICFILES_STORAGE_ALIAS not in settings.STORAGES:\n errors.append(E005)\n return", "middle": " pass\n else:\n errors.ext", "meta": {"filepath": "django/contrib/staticfiles/checks.py", "language": "python", "file_size": 836, "cut_index": 520, "middle_length": 52}} +{"prefix": "nc_to_async\n\nfrom django.conf import settings\nfrom django.contrib.staticfiles import utils\nfrom django.contrib.staticfiles.views import serve\nfrom django.core.handlers.asgi import ASGIHandler\nfrom django.core.handlers.exception import response_for_exception\nfrom django.core.handlers.wsgi import WSGIHandler, get_path_info\nfrom django.http import Http404\n\n\nclass StaticFilesHandlerMixin:\n \"\"\"\n Common methods used by WSGI and ASGI handlers.\n \"\"\"\n\n # May be used to differentiate between handler types", "suffix": "t_base_url(self):\n utils.check_settings()\n return settings.STATIC_URL\n\n def _should_handle(self, path):\n \"\"\"\n Check if the path should be handled. Ignore the path if:\n * the host is provided as part of the base_url\n ", "middle": " (e.g. in a\n # request_finished signal)\n handles_files = True\n\n def load_middleware(self):\n # Middleware are already loaded for self.application; no need to reload\n # them for self.\n pass\n\n def ge", "meta": {"filepath": "django/contrib/staticfiles/handlers.py", "language": "python", "file_size": 4043, "cut_index": 614, "middle_length": 229}} +{"prefix": "ettings\nfrom django.core.exceptions import ImproperlyConfigured\n\n\ndef matches_patterns(path, patterns):\n \"\"\"\n Return True or False depending on whether the ``path`` should be\n ignored (if it matches any pattern in ``ignore_patterns``).\n \"\"\"\n return any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns)\n\n\ndef get_files(storage, ignore_patterns=None, location=\"\"):\n \"\"\"\n Recursively walk the storage directories yielding the paths\n of all files that should be copied.\n \"\"\"\n ", "suffix": "ntinue\n if location:\n fn = os.path.join(location, fn)\n # Match the full file path.\n if matches_patterns(fn, ignore_patterns):\n continue\n yield fn\n for dir in directories:\n if matches_p", "middle": " if ignore_patterns is None:\n ignore_patterns = []\n directories, files = storage.listdir(location)\n for fn in files:\n # Match only the basename.\n if matches_patterns(fn, ignore_patterns):\n co", "meta": {"filepath": "django/contrib/staticfiles/utils.py", "language": "python", "file_size": 2279, "cut_index": 563, "middle_length": 229}} +{"prefix": " cached_property\n\n\nclass Command(BaseCommand):\n \"\"\"\n Copies or symlinks static files from different locations to the\n settings.STATIC_ROOT.\n \"\"\"\n\n help = \"Collect static files in a single location.\"\n requires_system_checks = [Tags.staticfiles]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.copied_files = []\n self.symlinked_files = []\n self.unmodified_files = []\n self.post_processed_files = []\n self.skipped_files ", "suffix": "edError:\n return False\n return True\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--noinput\",\n \"--no-input\",\n action=\"store_false\",\n dest=\"interactive\",\n help=\"", "middle": "= []\n self.deleted_files = []\n self.storage = staticfiles_storage\n self.style = no_style()\n\n @cached_property\n def local(self):\n try:\n self.storage.path(\"\")\n except NotImplement", "meta": {"filepath": "django/contrib/staticfiles/management/commands/collectstatic.py", "language": "python", "file_size": 16248, "cut_index": 921, "middle_length": 229}} +{"prefix": "conf import settings\nfrom django.contrib.staticfiles.handlers import StaticFilesHandler\nfrom django.core.management.commands.runserver import Command as RunserverCommand\n\n\nclass Command(RunserverCommand):\n help = (\n \"Starts a lightweight web server for development and also serves static files.\"\n )\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument(\n \"--nostatic\",\n action=\"store_false\",\n dest=\"use_static_handle", "suffix": " help=\"Allows serving static files even if DEBUG is False.\",\n )\n\n def get_handler(self, *args, **options):\n \"\"\"\n Return the static files serving handler wrapping the default handler,\n if static files should be served", "middle": "r\",\n help=\"Tells Django to NOT automatically serve static files at STATIC_URL.\",\n )\n parser.add_argument(\n \"--insecure\",\n action=\"store_true\",\n dest=\"insecure_serving\",\n ", "meta": {"filepath": "django/contrib/staticfiles/management/commands/runserver.py", "language": "python", "file_size": 1373, "cut_index": 524, "middle_length": 229}} +{"prefix": "rom django.conf import settings\nfrom django.core.checks import Error\nfrom django.core.exceptions import ValidationError\n\n\ndef check_site_id(app_configs, **kwargs):\n # Inner import avoids AppRegistryNotReady\n from django.contrib.sites.models import Site\n\n if hasattr(settings, \"SITE_ID\"):\n try:\n site_id = Site._meta.pk.to_python(settings.SITE_ID)\n except ValidationError as exc:\n return [\n Error(\n f\"The SITE_ID setting failed to val", "suffix": "d != settings.SITE_ID:\n expected_type = type(site_id).__name__\n return [\n Error(\n f\"The SITE_ID setting must be of type {expected_type}.\",\n id=\"sites.E101\",\n ", "middle": "idate: {exc}.\", id=\"sites.E101\"\n ),\n ]\n else:\n # to_python() might coerce a SITE_ID of the wrong type to the valid\n # type, e.g. \"1\" to 1 for AutoField.\n if site_i", "meta": {"filepath": "django/contrib/sites/checks.py", "language": "python", "file_size": 1049, "cut_index": 513, "middle_length": 229}} +{"prefix": "ite object.\n\"\"\"\n\nfrom django.apps import apps as global_apps\nfrom django.conf import settings\nfrom django.core.management.color import no_style\nfrom django.db import DEFAULT_DB_ALIAS, connections, router\n\n\ndef create_default_site(\n app_config,\n verbosity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n try:\n Site = apps.get_model(\"sites\", \"Site\")\n except LookupError:\n return\n\n if not router.allow_migrate_model(using, Site):\n ret", "suffix": "the test suite after flush/syncdb), it isn't guaranteed that\n # the next id will be 1, so we coerce it. See #15573 and #16353. This\n # can also crop up outside of tests - see #15346.\n if verbosity >= 2:\n print(\"Creating exam", "middle": "urn\n\n if not Site.objects.using(using).exists():\n # The default settings set SITE_ID = 1, and some tests in Django's test\n # suite rely on this value. However, if database sequences are reused\n # (e.g. in ", "meta": {"filepath": "django/contrib/sites/management.py", "language": "python", "file_size": 1646, "cut_index": 537, "middle_length": 229}} +{"prefix": " import models\nfrom django.db.models.signals import pre_delete, pre_save\nfrom django.http.request import split_domain_port\nfrom django.utils.translation import gettext_lazy as _\n\nSITE_CACHE = {}\n\n\ndef _simple_domain_name_validator(value):\n \"\"\"\n Validate that the given value contains no whitespaces to prevent common\n typos.\n \"\"\"\n checks = ((s in value) for s in string.whitespace)\n if any(checks):\n raise ValidationError(\n _(\"The domain name cannot contain any spaces or tabs", "suffix": " SITE_CACHE[site_id] = site\n return SITE_CACHE[site_id]\n\n def _get_site_by_request(self, request):\n host = request.get_host()\n try:\n # First attempt to look up the site by host with or without port.\n ", "middle": ".\"),\n code=\"invalid\",\n )\n\n\nclass SiteManager(models.Manager):\n use_in_migrations = True\n\n def _get_site_by_id(self, site_id):\n if site_id not in SITE_CACHE:\n site = self.get(pk=site_id)\n ", "meta": {"filepath": "django/contrib/sites/models.py", "language": "python", "file_size": 3695, "cut_index": 614, "middle_length": 229}} +{"prefix": "jango.utils.connection import BaseConnectionHandler, ConnectionProxy\nfrom django.utils.module_loading import import_string\n\nfrom . import checks, signals # NOQA\nfrom .base import (\n DEFAULT_TASK_BACKEND_ALIAS,\n DEFAULT_TASK_QUEUE_NAME,\n Task,\n TaskContext,\n TaskResult,\n TaskResultStatus,\n task,\n)\nfrom .exceptions import InvalidTaskBackend\n\n__all__ = [\n \"DEFAULT_TASK_BACKEND_ALIAS\",\n \"DEFAULT_TASK_QUEUE_NAME\",\n \"default_task_backend\",\n \"task\",\n \"task_backends\",\n \"Task\"", "suffix": " params = self.settings[alias]\n backend = params[\"BACKEND\"]\n try:\n backend_cls = import_string(backend)\n except ImportError as e:\n raise InvalidTaskBackend(f\"Could not find backend '{backend}': {e}\") from e\n ", "middle": ",\n \"TaskContext\",\n \"TaskResult\",\n \"TaskResultStatus\",\n]\n\n\nclass TaskBackendHandler(BaseConnectionHandler):\n settings_name = \"TASKS\"\n exception_class = InvalidTaskBackend\n\n def create_connection(self, alias):\n ", "meta": {"filepath": "django/tasks/__init__.py", "language": "python", "file_size": 1178, "cut_index": 518, "middle_length": 229}} +{"prefix": "sgiref.sync import async_to_sync, sync_to_async\n\nfrom django.db.models.enums import TextChoices\nfrom django.utils.json import normalize_json\nfrom django.utils.module_loading import import_string\nfrom django.utils.translation import pgettext_lazy\n\nfrom .exceptions import TaskResultMismatch\n\nDEFAULT_TASK_BACKEND_ALIAS = \"default\"\nDEFAULT_TASK_PRIORITY = 0\nDEFAULT_TASK_QUEUE_NAME = \"default\"\nTASK_MAX_PRIORITY = 100\nTASK_MIN_PRIORITY = -100\nTASK_REFRESH_ATTRS = {\n \"errors\",\n \"_return_value\",\n \"finished", "suffix": "EADY\", pgettext_lazy(\"Task\", \"Ready\"))\n # The Task is currently running.\n RUNNING = (\"RUNNING\", pgettext_lazy(\"Task\", \"Running\"))\n # The Task raised an exception during execution, or was unable to start.\n FAILED = (\"FAILED\", pgettext_lazy(\"Task", "middle": "_at\",\n \"started_at\",\n \"last_attempted_at\",\n \"status\",\n \"enqueued_at\",\n \"worker_ids\",\n}\n\n\nclass TaskResultStatus(TextChoices):\n # The Task has just been enqueued, or is ready to be executed again.\n READY = (\"R", "meta": {"filepath": "django/tasks/base.py", "language": "python", "file_size": 8547, "cut_index": 716, "middle_length": 229}} +{"prefix": "contrib.messages.storage.base import BaseStorage\nfrom django.contrib.messages.storage.cookie import MessageDecoder, MessageEncoder\nfrom django.core.exceptions import ImproperlyConfigured\n\n\nclass SessionStorage(BaseStorage):\n \"\"\"\n Store messages in the session (that is, django.contrib.sessions).\n \"\"\"\n\n session_key = \"_messages\"\n\n def __init__(self, request, *args, **kwargs):\n if not hasattr(request, \"session\"):\n raise ImproperlyConfigured(\n \"The session-based t", "suffix": "kwargs)\n\n def _get(self, *args, **kwargs):\n \"\"\"\n Retrieve a list of messages from the request's session. This storage\n always stores everything it is given, so return True for the\n all_retrieved flag.\n \"\"\"\n retu", "middle": "emporary message storage requires session \"\n \"middleware to be installed, and come before the message \"\n \"middleware in the MIDDLEWARE list.\"\n )\n super().__init__(request, *args, **", "meta": {"filepath": "django/contrib/messages/storage/session.py", "language": "python", "file_size": 1764, "cut_index": 537, "middle_length": 229}} +{"prefix": "tic files.\n\n The defaults for ``location`` and ``base_url`` are\n ``STATIC_ROOT`` and ``STATIC_URL``.\n \"\"\"\n\n def __init__(self, location=None, base_url=None, *args, **kwargs):\n if location is None:\n location = settings.STATIC_ROOT\n if base_url is None:\n base_url = settings.STATIC_URL\n check_settings(base_url)\n super().__init__(location, base_url, *args, **kwargs)\n # FileSystemStorage fallbacks to MEDIA_ROOT when location\n # is empty,", "suffix": " \"You're using the staticfiles app \"\n \"without having set the STATIC_ROOT \"\n \"setting to a filesystem path.\"\n )\n return super().path(name)\n\n\nclass HashedFilesMixin:\n default_template = \"\"\"url(\"%", "middle": " so we restore the empty value.\n if not location:\n self.base_location = None\n self.location = None\n\n def path(self, name):\n if not self.location:\n raise ImproperlyConfigured(\n ", "meta": {"filepath": "django/contrib/staticfiles/storage.py", "language": "python", "file_size": 23320, "cut_index": 1331, "middle_length": 229}} +{"prefix": "ntrib.staticfiles import finders\nfrom django.core.management.base import LabelCommand\n\n\nclass Command(LabelCommand):\n help = \"Finds the absolute paths for the given static file(s).\"\n label = \"staticfile\"\n\n def add_arguments(self, parser):\n super().add_arguments(parser)\n parser.add_argument(\n \"--first\",\n action=\"store_false\",\n dest=\"all\",\n help=\"Only return the first match for each static file.\",\n )\n\n def handle_label(self, path, **", "suffix": "n %s\"\n % \"\\n \".join([str(loc) for loc in finders.searched_locations])\n )\n else:\n searched_locations = \"\"\n if result:\n if not isinstance(result, (list, tuple)):\n result = [result", "middle": "options):\n verbosity = options[\"verbosity\"]\n result = finders.find(path, find_all=options[\"all\"])\n if verbosity >= 2:\n searched_locations = (\n \"\\nLooking in the following locations:\\", "meta": {"filepath": "django/contrib/staticfiles/management/commands/findstatic.py", "language": "python", "file_size": 1643, "cut_index": 537, "middle_length": 229}} +{"prefix": "y,\n ngettext,\n ngettext_lazy,\n npgettext_lazy,\n pgettext,\n round_away_from_one,\n)\n\nregister = template.Library()\n\n\n@register.filter(is_safe=True)\ndef ordinal(value):\n \"\"\"\n Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',\n 3 is '3rd', etc. Works for any non-negative integer.\n \"\"\"\n try:\n value = int(value)\n except (TypeError, ValueError):\n return value\n if value < 0:\n return str(value)\n if value == 1:\n # Translators: Ordi", "suffix": " pgettext(\"ordinal 11, 12, 13\", \"{}th\").format(value)\n else:\n templates = (\n # Translators: Ordinal format when value ends with 0, e.g. 80th.\n pgettext(\"ordinal 0\", \"{}th\"),\n # Translators: Ordinal format when val", "middle": "nal format when value is 1 (1st).\n value = pgettext(\"ordinal is 1\", \"{}st\").format(value)\n elif value % 100 in (11, 12, 13):\n # Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th).\n value =", "meta": {"filepath": "django/contrib/humanize/templatetags/humanize.py", "language": "python", "file_size": 13010, "cut_index": 921, "middle_length": 229}} +{"prefix": "ty\nfrom django.utils.module_loading import import_string\n\n# To keep track on which directories the finder has searched the static files.\nsearched_locations = []\n\n\nclass BaseFinder:\n \"\"\"\n A base file finder to be used for custom staticfiles finder classes.\n \"\"\"\n\n def check(self, **kwargs):\n raise NotImplementedError(\n \"subclasses may provide a check() method to verify the finder is \"\n \"configured correctly.\"\n )\n\n def list(self, ignore_patterns):\n \"\"\"\n", "suffix": " provide a list() method\"\n )\n\n\nclass FileSystemFinder(BaseFinder):\n \"\"\"\n A static files finder that uses the ``STATICFILES_DIRS`` setting\n to locate files.\n \"\"\"\n\n def __init__(self, app_names=None, *args, **kwargs):\n # List of ", "middle": " Given an optional list of paths to ignore, return a two item iterable\n consisting of the relative path and storage instance.\n \"\"\"\n raise NotImplementedError(\n \"subclasses of BaseFinder must", "meta": {"filepath": "django/contrib/staticfiles/finders.py", "language": "python", "file_size": 10668, "cut_index": 921, "middle_length": 229}} +{"prefix": "ettings\nfrom django.core import checks\nfrom django.core.exceptions import FieldDoesNotExist\nfrom django.db import models\n\n\nclass CurrentSiteManager(models.Manager):\n \"Use this to limit objects to those associated with the current site.\"\n\n use_in_migrations = True\n\n def __init__(self, field_name=None):\n super().__init__()\n self.__field_name = field_name\n\n def check(self, **kwargs):\n errors = super().check(**kwargs)\n errors.extend(self._check_field_name())\n retur", "suffix": " checks.Error(\n \"CurrentSiteManager could not find a field named '%s'.\"\n % field_name,\n obj=self,\n id=\"sites.E001\",\n )\n ]\n\n if not field.many_to_ma", "middle": "n errors\n\n def _check_field_name(self):\n field_name = self._get_field_name()\n try:\n field = self.model._meta.get_field(field_name)\n except FieldDoesNotExist:\n return [\n ", "meta": {"filepath": "django/contrib/sites/managers.py", "language": "python", "file_size": 1994, "cut_index": 537, "middle_length": 229}} +{"prefix": "ignals\nfrom django.db.utils import (\n DEFAULT_DB_ALIAS,\n DJANGO_VERSION_PICKLE_KEY,\n ConnectionHandler,\n ConnectionRouter,\n DatabaseError,\n DataError,\n Error,\n IntegrityError,\n InterfaceError,\n InternalError,\n NotSupportedError,\n OperationalError,\n ProgrammingError,\n)\nfrom django.utils.connection import ConnectionProxy\n\n__all__ = [\n \"close_old_connections\",\n \"connection\",\n \"connections\",\n \"reset_queries\",\n \"router\",\n \"DatabaseError\",\n \"IntegrityErr", "suffix": "ectionHandler()\n\nrouter = ConnectionRouter()\n\n# For backwards compatibility. Prefer connections['default'] instead.\nconnection = ConnectionProxy(connections, DEFAULT_DB_ALIAS)\n\n\n# Register an event to reset saved queries when a Django request is started.\nd", "middle": "or\",\n \"InternalError\",\n \"ProgrammingError\",\n \"DataError\",\n \"NotSupportedError\",\n \"Error\",\n \"InterfaceError\",\n \"OperationalError\",\n \"DEFAULT_DB_ALIAS\",\n \"DJANGO_VERSION_PICKLE_KEY\",\n]\n\nconnections = Conn", "meta": {"filepath": "django/db/__init__.py", "language": "python", "file_size": 1533, "cut_index": 537, "middle_length": 229}} +{"prefix": "Error:\n import psycopg2 as Database\nexcept ImportError:\n raise ImproperlyConfigured(\"Error loading psycopg2 or psycopg module\")\n\n\n@lru_cache\ndef psycopg_version():\n version = Database.__version__.split(\" \", 1)[0]\n return get_version_tuple(version)\n\n\nif psycopg_version() < (2, 9, 9):\n raise ImproperlyConfigured(\n f\"psycopg2 version 2.9.9 or newer is required; you have {Database.__version__}\"\n )\nif (3,) <= psycopg_version() < (3, 1, 12):\n raise ImproperlyConfigured(\n f\"p", "suffix": "pq import Format\n\n from .psycopg_any import get_adapters_template, register_tzloader\n\n TIMESTAMPTZ_OID = adapters.types[\"timestamptz\"].oid\n\nelse:\n import psycopg2.extensions\n import psycopg2.extras\n\n psycopg2.extensions.register_adapter(Safe", "middle": "sycopg version 3.1.12 or newer is required; you have {Database.__version__}\"\n )\n\n\nfrom .psycopg_any import IsolationLevel, is_psycopg3 # NOQA isort:skip\n\nif is_psycopg3:\n from psycopg import adapters, sql\n from psycopg.", "meta": {"filepath": "django/db/backends/postgresql/base.py", "language": "python", "file_size": 23830, "cut_index": 1331, "middle_length": 229}} +{"prefix": "oroutinefunction\n\n\ndef xframe_options_deny(view_func):\n \"\"\"\n Modify a view function so its response has the X-Frame-Options HTTP\n header set to 'DENY' as long as the response doesn't already have that\n header set. Usage:\n\n @xframe_options_deny\n def some_view(request):\n ...\n \"\"\"\n\n if iscoroutinefunction(view_func):\n\n async def _view_wrapper(*args, **kwargs):\n response = await view_func(*args, **kwargs)\n if response.get(\"X-Frame-Options\") is None:\n ", "suffix": "\") is None:\n response[\"X-Frame-Options\"] = \"DENY\"\n return response\n\n return wraps(view_func)(_view_wrapper)\n\n\ndef xframe_options_sameorigin(view_func):\n \"\"\"\n Modify a view function so its response has the X-Frame-Options ", "middle": " response[\"X-Frame-Options\"] = \"DENY\"\n return response\n\n else:\n\n def _view_wrapper(*args, **kwargs):\n response = view_func(*args, **kwargs)\n if response.get(\"X-Frame-Options", "meta": {"filepath": "django/views/decorators/clickjacking.py", "language": "python", "file_size": 2549, "cut_index": 563, "middle_length": 229}} +{"prefix": "se\nfrom django.utils.decorators import classonlymethod\nfrom django.utils.functional import classproperty\nfrom django.utils.log import log_response\n\nlogger = logging.getLogger(\"django.request\")\n\n\nclass ContextMixin:\n \"\"\"\n A default context mixin that passes the keyword arguments received by\n get_context_data() as the template context.\n \"\"\"\n\n extra_context = None\n\n def get_context_data(self, **kwargs):\n kwargs.setdefault(\"view\", self)\n if self.extra_context is not None:\n ", "suffix": "ames = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"head\",\n \"options\",\n \"trace\",\n ]\n\n def __init__(self, **kwargs):\n \"\"\"\n Constructor. Called in the URLconf; can contain helpf", "middle": " kwargs.update(self.extra_context)\n return kwargs\n\n\nclass View:\n \"\"\"\n Intentionally simple parent class for all views. Only implements\n dispatch-by-method and simple sanity checking.\n \"\"\"\n\n http_method_n", "meta": {"filepath": "django/views/generic/base.py", "language": "python", "file_size": 9546, "cut_index": 921, "middle_length": 229}} +{"prefix": " ContextMixin, TemplateResponseMixin, View\n\n\nclass SingleObjectMixin(ContextMixin):\n \"\"\"\n Provide the ability to retrieve a single object for further manipulation.\n \"\"\"\n\n model = None\n queryset = None\n slug_field = \"slug\"\n context_object_name = None\n slug_url_kwarg = \"slug\"\n pk_url_kwarg = \"pk\"\n query_pk_and_slug = False\n\n def get_object(self, queryset=None):\n \"\"\"\n Return the object the view is displaying.\n\n Require `self.queryset` and a `pk` or `slug` a", "suffix": ":\n queryset = self.get_queryset()\n\n # Next, try looking up by primary key.\n pk = self.kwargs.get(self.pk_url_kwarg)\n slug = self.kwargs.get(self.slug_url_kwarg)\n if pk is not None:\n queryset = queryset.filt", "middle": "rgument in the URLconf.\n Subclasses can override this to return any object.\n \"\"\"\n # Use a custom queryset if provided; this is required for subclasses\n # like DateDetailView\n if queryset is None", "meta": {"filepath": "django/views/generic/detail.py", "language": "python", "file_size": 7040, "cut_index": 716, "middle_length": 229}} +{"prefix": "nslation import gettext as _\nfrom django.views.generic.base import ContextMixin, TemplateResponseMixin, View\n\n\nclass MultipleObjectMixin(ContextMixin):\n \"\"\"A mixin for views manipulating multiple objects.\"\"\"\n\n allow_empty = True\n queryset = None\n model = None\n paginate_by = None\n paginate_orphans = 0\n context_object_name = None\n paginator_class = Paginator\n page_kwarg = \"page\"\n ordering = None\n\n def get_queryset(self):\n \"\"\"\n Return the list of items for this vi", "suffix": "elf.queryset\n if isinstance(queryset, QuerySet):\n queryset = queryset.all()\n elif self.model is not None:\n queryset = self.model._default_manager.all()\n else:\n raise ImproperlyConfigured(\n ", "middle": "ew.\n\n The return value must be an iterable and may be an instance of\n `QuerySet` in which case `QuerySet` specific behavior will be enabled.\n \"\"\"\n if self.queryset is not None:\n queryset = s", "meta": {"filepath": "django/views/generic/list.py", "language": "python", "file_size": 8009, "cut_index": 716, "middle_length": 229}} +{"prefix": "\n\nfrom asgiref.local import Local\n\nfrom django.core.signals import setting_changed\nfrom django.dispatch import Signal, receiver\n\nfrom .base import TaskResultStatus\n\nlogger = logging.getLogger(\"django.tasks\")\n\ntask_enqueued = Signal()\ntask_finished = Signal()\ntask_started = Signal()\n\n\n@receiver(setting_changed)\ndef clear_tasks_handlers(*, setting, **kwargs):\n \"\"\"Reset the connection handler whenever the settings change.\"\"\"\n if setting == \"TASKS\":\n from . import task_backends\n\n task_backen", "suffix": " logger.debug(\n \"Task id=%s path=%s enqueued backend=%s\",\n task_result.id,\n task_result.task.module_path,\n task_result.backend,\n )\n\n\n@receiver(task_started)\ndef log_task_started(sender, task_result, **kwargs):\n logger.i", "middle": "ds._settings = task_backends.settings = (\n task_backends.configure_settings(None)\n )\n task_backends._connections = Local()\n\n\n@receiver(task_enqueued)\ndef log_task_enqueued(sender, task_result, **kwargs):\n", "meta": {"filepath": "django/tasks/signals.py", "language": "python", "file_size": 1690, "cut_index": 537, "middle_length": 229}} +{"prefix": "ort sync_to_async\n\nfrom django.conf import settings\nfrom django.tasks import DEFAULT_TASK_QUEUE_NAME\nfrom django.tasks.base import (\n DEFAULT_TASK_PRIORITY,\n TASK_MAX_PRIORITY,\n TASK_MIN_PRIORITY,\n Task,\n)\nfrom django.tasks.exceptions import InvalidTask\nfrom django.utils import timezone\nfrom django.utils.inspect import get_func_args, is_module_level_function\n\n\nclass BaseTaskBackend(metaclass=ABCMeta):\n task_class = Task\n\n # Does the backend support Tasks to be enqueued with the run_after\n ", "suffix": "pports_get_result = False\n\n # Does the backend support executing Tasks in a given\n # priority order?\n supports_priority = False\n\n def __init__(self, alias, params):\n self.alias = alias\n self.queues = set(params.get(\"QUEUES\", [DEFA", "middle": " # attribute?\n supports_defer = False\n\n # Does the backend support coroutines to be enqueued?\n supports_async_task = False\n\n # Does the backend support results being retrieved (from any\n # thread/process)?\n su", "meta": {"filepath": "django/tasks/backends/base.py", "language": "python", "file_size": 3796, "cut_index": 614, "middle_length": 229}} +{"prefix": "\n\nfrom django.tasks.base import TaskResult, TaskResultStatus\nfrom django.tasks.exceptions import TaskResultDoesNotExist\nfrom django.tasks.signals import task_enqueued\nfrom django.utils import timezone\nfrom django.utils.crypto import get_random_string\n\nfrom .base import BaseTaskBackend\n\n\nclass DummyBackend(BaseTaskBackend):\n supports_defer = True\n supports_async_task = True\n supports_priority = True\n\n def __init__(self, alias, params):\n super().__init__(alias, params)\n self.results ", "suffix": "sk, args, kwargs):\n self.validate_task(task)\n\n result = TaskResult(\n task=task,\n id=get_random_string(32),\n status=TaskResultStatus.READY,\n enqueued_at=None,\n started_at=None,\n ", "middle": "= []\n\n def _store_result(self, result):\n object.__setattr__(result, \"enqueued_at\", timezone.now())\n self.results.append(result)\n task_enqueued.send(type(self), task_result=result)\n\n def enqueue(self, ta", "meta": {"filepath": "django/tasks/backends/dummy.py", "language": "python", "file_size": 1957, "cut_index": 537, "middle_length": 229}} +{"prefix": "_to_sensitive_variables\n\n# Minimal Django templates engine to render the error templates\n# regardless of the project's TEMPLATES setting. Templates are\n# read directly from the filesystem so that the error handler\n# works even if the template loader is broken.\nDEBUG_ENGINE = Engine(\n debug=True,\n libraries={\"i18n\": \"django.templatetags.i18n\"},\n)\n\n\ndef builtin_template_path(name):\n \"\"\"\n Return a path to a builtin template.\n\n Avoid calling this function at the module level or in a class-definit", "suffix": "bject to wrap callable appearing in settings.\n * Not to call in the debug page (#21345).\n * Not to break the debug page if the callable forbidding to set attributes\n (#23070).\n \"\"\"\n\n def __init__(self, callable_setting):\n self._wrap", "middle": "ion\n because __file__ may not exist, e.g. in frozen environments.\n \"\"\"\n return Path(__file__).parent / \"templates\" / name\n\n\nclass ExceptionCycleWarning(UserWarning):\n pass\n\n\nclass CallableSettingWrapper:\n \"\"\"\n O", "meta": {"filepath": "django/views/debug.py", "language": "python", "file_size": 26618, "cut_index": 1331, "middle_length": 229}} +{"prefix": ".template import Context, Engine\nfrom django.urls import translate_url\nfrom django.utils.formats import get_format\nfrom django.utils.http import url_has_allowed_host_and_scheme\nfrom django.utils.translation import check_for_language, get_language\nfrom django.utils.translation.trans_real import DjangoTranslation\nfrom django.views.generic import View\n\nLANGUAGE_QUERY_PARAMETER = \"language\"\n\n\ndef builtin_template_path(name):\n \"\"\"\n Return a path to a builtin template.\n\n Avoid calling this function at th", "suffix": "RL while setting the chosen language in the language\n cookie. The URL and the language code need to be specified in the request\n parameters.\n\n Since this view changes how the user will see the rest of the site, it must\n only be accessed as a PO", "middle": "e module level or in a class-definition\n because __file__ may not exist, e.g. in frozen environments.\n \"\"\"\n return Path(__file__).parent / \"templates\" / name\n\n\ndef set_language(request):\n \"\"\"\n Redirect to a given U", "meta": {"filepath": "django/views/i18n.py", "language": "python", "file_size": 9031, "cut_index": 716, "middle_length": 229}} +{"prefix": "oroutinefunction\n\nfrom django.middleware.cache import CacheMiddleware\nfrom django.utils.cache import add_never_cache_headers, patch_cache_control\nfrom django.utils.decorators import decorator_from_middleware_with_args\n\n\ndef cache_page(timeout, *, cache=None, key_prefix=None):\n \"\"\"\n Decorator for views that tries getting the page from the cache and\n populates the cache if the page isn't in the cache yet.\n\n The cache is keyed by the URL and some data from the headers.\n Additionally there is the", "suffix": "from the response's Vary header will be taken\n into account on caching -- just like the middleware does.\n \"\"\"\n return decorator_from_middleware_with_args(CacheMiddleware)(\n page_timeout=timeout,\n cache_alias=cache,\n key_prefix", "middle": " key prefix that is used to distinguish different\n cache areas in a multi-site setup. You could use the\n get_current_site().domain, for example, as that is unique across a Django\n project.\n\n Additionally, all headers ", "meta": {"filepath": "django/views/decorators/cache.py", "language": "python", "file_size": 2815, "cut_index": 563, "middle_length": 229}} +{"prefix": "oroutinefunction\n\nfrom django.middleware.csrf import CsrfViewMiddleware, get_token\nfrom django.utils.decorators import decorator_from_middleware\n\ncsrf_protect = decorator_from_middleware(CsrfViewMiddleware)\ncsrf_protect.__name__ = \"csrf_protect\"\ncsrf_protect.__doc__ = \"\"\"\nThis decorator adds CSRF protection in exactly the same way as\nCsrfViewMiddleware, but it can be used on a per view basis. Using both, or\nusing the decorator multiple times, is harmless and efficient.\n\"\"\"\n\n\nclass _EnsureCsrfToken(CsrfViewM", "suffix": "csrf_token.__name__ = \"requires_csrf_token\"\nrequires_csrf_token.__doc__ = \"\"\"\nUse this decorator on views that need a correct csrf_token available to\nRequestContext, but without the CSRF protection that csrf_protect\nenforces.\n\"\"\"\n\n\nclass _EnsureCsrfCookie(", "middle": "iddleware):\n # Behave like CsrfViewMiddleware but don't reject requests or log warnings.\n def _reject(self, request, reason):\n return None\n\n\nrequires_csrf_token = decorator_from_middleware(_EnsureCsrfToken)\nrequires_", "meta": {"filepath": "django/views/decorators/csrf.py", "language": "python", "file_size": 2317, "cut_index": 563, "middle_length": 229}} +{"prefix": "are.http import ConditionalGetMiddleware\nfrom django.utils import timezone\nfrom django.utils.cache import get_conditional_response\nfrom django.utils.decorators import decorator_from_middleware\nfrom django.utils.http import http_date, quote_etag\nfrom django.utils.log import log_response\n\nconditional_page = decorator_from_middleware(ConditionalGetMiddleware)\n\n\ndef require_http_methods(request_method_list):\n \"\"\"\n Decorator to make a view only accept particular request methods. Usage::\n\n @require_h", "suffix": "ecorator(func):\n if iscoroutinefunction(func):\n\n @wraps(func)\n async def inner(request, *args, **kwargs):\n if request.method not in request_method_list:\n response = HttpResponseNotAllowed(reque", "middle": "ttp_methods([\"GET\", \"POST\"])\n def my_view(request):\n # I can assume now that only GET or POST requests make it this far\n # ...\n\n Note that request methods should be in uppercase.\n \"\"\"\n\n def d", "meta": {"filepath": "django/views/decorators/http.py", "language": "python", "file_size": 6517, "cut_index": 716, "middle_length": 229}} +{"prefix": "rt RedirectView, TemplateView, View\nfrom django.views.generic.dates import (\n ArchiveIndexView,\n DateDetailView,\n DayArchiveView,\n MonthArchiveView,\n TodayArchiveView,\n WeekArchiveView,\n YearArchiveView,\n)\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView\nfrom django.views.generic.list import ListView\n\n__all__ = [\n \"View\",\n \"TemplateView\",\n \"RedirectView\",\n \"ArchiveIndexView\",\n \"YearArchiv", "suffix": "\",\n \"DayArchiveView\",\n \"TodayArchiveView\",\n \"DateDetailView\",\n \"DetailView\",\n \"FormView\",\n \"CreateView\",\n \"UpdateView\",\n \"DeleteView\",\n \"ListView\",\n \"GenericViewError\",\n]\n\n\nclass GenericViewError(Exception):\n \"\"\"A problem i", "middle": "eView\",\n \"MonthArchiveView\",\n \"WeekArchiveView", "meta": {"filepath": "django/views/generic/__init__.py", "language": "python", "file_size": 886, "cut_index": 547, "middle_length": 52}} +{"prefix": "bles.\n \"\"\"\n return self.year_format\n\n def get_year(self):\n \"\"\"Return the year for which this view should display data.\"\"\"\n year = self.year\n if year is None:\n try:\n year = self.kwargs[\"year\"]\n except KeyError:\n try:\n year = self.request.GET[\"year\"]\n except KeyError:\n raise Http404(_(\"No year specified\"))\n return year\n\n def get_next_year(self, date):\n ", "suffix": "te, is_previous=True, period=\"year\")\n\n def _get_next_year(self, date):\n \"\"\"\n Return the start date of the next interval.\n\n The interval is defined by start date <= item date < next start date.\n \"\"\"\n try:\n re", "middle": " \"\"\"Get the next valid year.\"\"\"\n return _get_next_prev(self, date, is_previous=False, period=\"year\")\n\n def get_previous_year(self, date):\n \"\"\"Get the previous valid year.\"\"\"\n return _get_next_prev(self, da", "meta": {"filepath": "django/views/generic/dates.py", "language": "python", "file_size": 26921, "cut_index": 1331, "middle_length": 229}} +{"prefix": "base import ContextMixin, TemplateResponseMixin, View\nfrom django.views.generic.detail import (\n BaseDetailView,\n SingleObjectMixin,\n SingleObjectTemplateResponseMixin,\n)\n\n\nclass FormMixin(ContextMixin):\n \"\"\"Provide a way to show and handle a form in a request.\"\"\"\n\n initial = {}\n form_class = None\n success_url = None\n prefix = None\n\n def get_initial(self):\n \"\"\"Return the initial data to use for forms on this view.\"\"\"\n return self.initial.copy()\n\n def get_prefix(se", "suffix": "\n \"\"\"Return an instance of the form to be used in this view.\"\"\"\n if form_class is None:\n form_class = self.get_form_class()\n return form_class(**self.get_form_kwargs())\n\n def get_form_kwargs(self):\n \"\"\"Return the k", "middle": "lf):\n \"\"\"Return the prefix to use for forms.\"\"\"\n return self.prefix\n\n def get_form_class(self):\n \"\"\"Return the form class to use.\"\"\"\n return self.form_class\n\n def get_form(self, form_class=None):", "meta": {"filepath": "django/views/generic/edit.py", "language": "python", "file_size": 9039, "cut_index": 716, "middle_length": 229}} +{"prefix": "o.contrib.sites.models\nfrom django.contrib.sites.models import _simple_domain_name_validator\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = []\n\n operations = [\n migrations.CreateModel(\n name=\"Site\",\n fields=[\n (\n \"id\",\n models.AutoField(\n verbose_name=\"ID\",\n serialize=False,\n auto_created=True,\n ", "suffix": "bose_name=\"domain name\",\n validators=[_simple_domain_name_validator],\n ),\n ),\n (\"name\", models.CharField(max_length=50, verbose_name=\"display name\")),\n ],\n option", "middle": " primary_key=True,\n ),\n ),\n (\n \"domain\",\n models.CharField(\n max_length=100,\n ver", "meta": {"filepath": "django/contrib/sites/migrations/0001_initial.py", "language": "python", "file_size": 1361, "cut_index": 524, "middle_length": 229}} +{"prefix": "en\nfrom django.template import Context, Engine, TemplateDoesNotExist, loader\nfrom django.utils.translation import gettext as _\nfrom django.utils.version import get_docs_version\n\nCSRF_FAILURE_TEMPLATE_NAME = \"403_csrf.html\"\n\n\ndef builtin_template_path(name):\n \"\"\"\n Return a path to a builtin template.\n\n Avoid calling this function at the module level or in a class-definition\n because __file__ may not exist, e.g. in frozen environments.\n \"\"\"\n return Path(__file__).parent / \"templates\" / name\n", "suffix": "FERER\n from django.template.context_processors import csp\n\n c = {\n \"title\": _(\"Forbidden\"),\n \"main\": _(\"CSRF verification failed. Request aborted.\"),\n \"reason\": reason,\n \"no_referer\": reason == REASON_NO_REFERER,\n \"", "middle": "\n\ndef csrf_failure(request, reason=\"\", template_name=CSRF_FAILURE_TEMPLATE_NAME):\n \"\"\"\n Default view used when request fails CSRF protection\n \"\"\"\n from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_RE", "meta": {"filepath": "django/views/csrf.py", "language": "python", "file_size": 3495, "cut_index": 614, "middle_length": 229}} +{"prefix": "OULD NOT be used in a production setting.\n\"\"\"\n\nimport mimetypes\nimport posixpath\nfrom pathlib import Path\n\nfrom django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified\nfrom django.template import Context, Engine, TemplateDoesNotExist, loader\nfrom django.utils._os import safe_join\nfrom django.utils.http import http_date, parse_http_date\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy\n\n\ndef builtin_template_path(name):\n \"\"\"\n Ret", "suffix": "s\" / name\n\n\ndef serve(request, path, document_root=None, show_indexes=False):\n \"\"\"\n Serve static files below a given point in the directory structure.\n\n To use, put a URL pattern such as::\n\n from django.views.static import serve\n\n pa", "middle": "urn a path to a builtin template.\n\n Avoid calling this function at the module level or in a class-definition\n because __file__ may not exist, e.g. in frozen environments.\n \"\"\"\n return Path(__file__).parent / \"template", "meta": {"filepath": "django/views/static.py", "language": "python", "file_size": 4053, "cut_index": 614, "middle_length": 229}} +{"prefix": "ls import wraps\nfrom inspect import iscoroutinefunction\n\n\ndef _make_csp_decorator(config_attr_name, config_attr_value):\n \"\"\"General CSP override decorator factory.\"\"\"\n\n if not isinstance(config_attr_value, dict):\n raise TypeError(\"CSP config should be a mapping.\")\n\n def decorator(view_func):\n @wraps(view_func)\n async def _wrapped_async_view(request, *args, **kwargs):\n response = await view_func(request, *args, **kwargs)\n setattr(response, config_attr_name,", "suffix": "attr_name, config_attr_value)\n return response\n\n if iscoroutinefunction(view_func):\n return _wrapped_async_view\n return _wrapped_sync_view\n\n return decorator\n\n\ndef csp_override(config):\n \"\"\"Override the Content-Sec", "middle": " config_attr_value)\n return response\n\n @wraps(view_func)\n def _wrapped_sync_view(request, *args, **kwargs):\n response = view_func(request, *args, **kwargs)\n setattr(response, config_", "meta": {"filepath": "django/views/decorators/csp.py", "language": "python", "file_size": 1273, "cut_index": 524, "middle_length": 229}} +{"prefix": "Error, TaskResult, TaskResultStatus\nfrom django.tasks.signals import task_enqueued, task_finished, task_started\nfrom django.utils import timezone\nfrom django.utils.crypto import get_random_string\nfrom django.utils.json import normalize_json\n\nfrom .base import BaseTaskBackend\n\nlogger = logging.getLogger(__name__)\n\n\nclass ImmediateBackend(BaseTaskBackend):\n supports_async_task = True\n supports_priority = True\n\n def __init__(self, alias, params):\n super().__init__(alias, params)\n self.wo", "suffix": "enqueued_at\", timezone.now())\n task_enqueued.send(type(self), task_result=task_result)\n\n task = task_result.task\n task_start_time = timezone.now()\n object.__setattr__(task_result, \"status\", TaskResultStatus.RUNNING)\n obje", "middle": "rker_id = get_random_string(32)\n\n def _execute_task(self, task_result):\n \"\"\"\n Execute the Task for the given TaskResult, mutating it with the\n outcome.\n \"\"\"\n object.__setattr__(task_result, \"", "meta": {"filepath": "django/tasks/backends/immediate.py", "language": "python", "file_size": 3377, "cut_index": 614, "middle_length": 229}} +{"prefix": "s):\n \"\"\"\n Indicate which variables used in the decorated function are sensitive so\n that those variables can later be treated in a special way, for example\n by hiding them when logging unhandled exceptions.\n\n Accept two forms:\n\n * with specified variable names:\n\n @sensitive_variables('user', 'password', 'credit_card')\n def my_function(user):\n password = user.pass_word\n credit_card = user.credit_card_number\n ...\n\n * without any specified var", "suffix": "or(\n \"sensitive_variables() must be called to use it as a decorator, \"\n \"e.g., use @sensitive_variables(), not @sensitive_variables.\"\n )\n\n def decorator(func):\n if iscoroutinefunction(func):\n sensitive_vari", "middle": "iable names, in which case consider all\n variables are sensitive:\n\n @sensitive_variables()\n def my_function()\n ...\n \"\"\"\n if len(variables) == 1 and callable(variables[0]):\n raise TypeErr", "meta": {"filepath": "django/views/decorators/debug.py", "language": "python", "file_size": 5250, "cut_index": 716, "middle_length": 229}} +{"prefix": "unctools import wraps\nfrom inspect import iscoroutinefunction\n\nfrom django.utils.cache import patch_vary_headers\n\n\ndef vary_on_headers(*headers):\n \"\"\"\n A view decorator that adds the specified headers to the Vary header of the\n response. Usage:\n\n @vary_on_headers('Cookie', 'Accept-language')\n def index(request):\n ...\n\n Note that the header names are not case-sensitive.\n \"\"\"\n\n def decorator(func):\n if iscoroutinefunction(func):\n\n async def _view_wrapp", "suffix": "uest, *args, **kwargs):\n response = func(request, *args, **kwargs)\n patch_vary_headers(response, headers)\n return response\n\n return wraps(func)(_view_wrapper)\n\n return decorator\n\n\nvary_on_cookie = vary", "middle": "er(request, *args, **kwargs):\n response = await func(request, *args, **kwargs)\n patch_vary_headers(response, headers)\n return response\n\n else:\n\n def _view_wrapper(req", "meta": {"filepath": "django/views/decorators/vary.py", "language": "python", "file_size": 1195, "cut_index": 518, "middle_length": 229}} +{"prefix": "ort import_string\n\nDEFAULT_DB_ALIAS = \"default\"\nDJANGO_VERSION_PICKLE_KEY = \"_django_version\"\n\n\nclass Error(Exception):\n pass\n\n\nclass InterfaceError(Error):\n pass\n\n\nclass DatabaseError(Error):\n pass\n\n\nclass DataError(DatabaseError):\n pass\n\n\nclass OperationalError(DatabaseError):\n pass\n\n\nclass IntegrityError(DatabaseError):\n pass\n\n\nclass InternalError(DatabaseError):\n pass\n\n\nclass ProgrammingError(DatabaseError):\n pass\n\n\nclass NotSupportedError(DatabaseError):\n pass\n\n\nclass Databas", "suffix": "rapper.\n\n It must have a Database attribute defining PEP-249 exceptions.\n \"\"\"\n self.wrapper = wrapper\n\n def __del__(self):\n del self.wrapper\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_value, ", "middle": "eErrorWrapper:\n \"\"\"\n Context manager and decorator that reraises backend-specific database\n exceptions using Django's common wrappers.\n \"\"\"\n\n def __init__(self, wrapper):\n \"\"\"\n wrapper is a database w", "meta": {"filepath": "django/db/utils.py", "language": "python", "file_size": 9350, "cut_index": 921, "middle_length": 229}} +{"prefix": " self.db = db\n\n WRAP_ERROR_ATTRS = frozenset([\"fetchone\", \"fetchmany\", \"fetchall\", \"nextset\"])\n\n APPS_NOT_READY_WARNING_MSG = (\n \"Accessing the database during app initialization is discouraged. To fix this \"\n \"warning, avoid executing queries in AppConfig.ready() or when your app \"\n \"modules are imported.\"\n )\n\n def __getattr__(self, attr):\n cursor_attr = getattr(self.cursor, attr)\n if attr in CursorWrapper.WRAP_ERROR_ATTRS:\n return self.db.wrap", "suffix": "def __exit__(self, type, value, traceback):\n # Close instead of passing through to avoid backend-specific behavior\n # (#17671). Catch errors liberally because errors in cleanup code\n # aren't useful.\n try:\n self.close", "middle": "_database_errors(cursor_attr)\n else:\n return cursor_attr\n\n def __iter__(self):\n with self.db.wrap_database_errors:\n yield from self.cursor\n\n def __enter__(self):\n return self\n\n ", "meta": {"filepath": "django/db/backends/utils.py", "language": "python", "file_size": 11137, "cut_index": 921, "middle_length": 229}} +{"prefix": "import BaseDatabaseClient\n\n\nclass DatabaseClient(BaseDatabaseClient):\n executable_name = \"mysql\"\n\n @classmethod\n def settings_to_cmd_args_env(cls, settings_dict, parameters):\n args = [cls.executable_name]\n env = None\n database = settings_dict[\"OPTIONS\"].get(\n \"database\",\n settings_dict[\"OPTIONS\"].get(\"db\", settings_dict[\"NAME\"]),\n )\n user = settings_dict[\"OPTIONS\"].get(\"user\", settings_dict[\"USER\"])\n password = settings_dict[\"OPTIONS\"]", "suffix": "NS\"].get(\"port\", settings_dict[\"PORT\"])\n server_ca = settings_dict[\"OPTIONS\"].get(\"ssl\", {}).get(\"ca\")\n client_cert = settings_dict[\"OPTIONS\"].get(\"ssl\", {}).get(\"cert\")\n client_key = settings_dict[\"OPTIONS\"].get(\"ssl\", {}).get(\"key\")\n", "middle": ".get(\n \"password\",\n settings_dict[\"OPTIONS\"].get(\"passwd\", settings_dict[\"PASSWORD\"]),\n )\n host = settings_dict[\"OPTIONS\"].get(\"host\", settings_dict[\"HOST\"])\n port = settings_dict[\"OPTIO", "meta": {"filepath": "django/db/backends/mysql/client.py", "language": "python", "file_size": 2988, "cut_index": 563, "middle_length": 229}} +{"prefix": "ion\n\nfrom .client import DatabaseClient\n\n\nclass DatabaseCreation(BaseDatabaseCreation):\n def sql_table_creation_suffix(self):\n suffix = []\n test_settings = self.connection.settings_dict[\"TEST\"]\n if test_settings[\"CHARSET\"]:\n suffix.append(\"CHARACTER SET %s\" % test_settings[\"CHARSET\"])\n if test_settings[\"COLLATION\"]:\n suffix.append(\"COLLATE %s\" % test_settings[\"COLLATION\"])\n return \" \".join(suffix)\n\n def _execute_create_test_db(self, cursor, para", "suffix": "database exists\" (1007) cancel tests.\n self.log(\"Got an error creating the test database: %s\" % e)\n sys.exit(2)\n else:\n raise\n\n def _clone_test_db(self, suffix, verbosity, keepdb=False):\n so", "middle": "meters, keepdb=False):\n try:\n super()._execute_create_test_db(cursor, parameters, keepdb)\n except Exception as e:\n if len(e.args) < 1 or e.args[0] != 1007:\n # All errors except \"", "meta": {"filepath": "django/db/backends/mysql/creation.py", "language": "python", "file_size": 4052, "cut_index": 614, "middle_length": 229}} +{"prefix": "\n\nFieldInfo = namedtuple(\n \"FieldInfo\",\n [\n *BaseFieldInfo._fields,\n \"extra\",\n \"is_unsigned\",\n \"has_json_constraint\",\n \"comment\",\n \"data_type\",\n ],\n)\nInfoLine = namedtuple(\n \"InfoLine\",\n \"col_name data_type max_len num_prec num_scale extra column_default \"\n \"collation is_unsigned comment\",\n)\nTableInfo = namedtuple(\"TableInfo\", [*BaseTableInfo._fields, \"comment\"])\n\n\nclass DatabaseIntrospection(BaseDatabaseIntrospection):\n data_types_reverse = {\n ", "suffix": "ME: \"DateTimeField\",\n FIELD_TYPE.DOUBLE: \"FloatField\",\n FIELD_TYPE.FLOAT: \"FloatField\",\n FIELD_TYPE.INT24: \"IntegerField\",\n FIELD_TYPE.JSON: \"JSONField\",\n FIELD_TYPE.LONG: \"IntegerField\",\n FIELD_TYPE.LONGLONG: \"Big", "middle": " FIELD_TYPE.BLOB: \"TextField\",\n FIELD_TYPE.CHAR: \"CharField\",\n FIELD_TYPE.DECIMAL: \"DecimalField\",\n FIELD_TYPE.NEWDECIMAL: \"DecimalField\",\n FIELD_TYPE.DATE: \"DateField\",\n FIELD_TYPE.DATETI", "meta": {"filepath": "django/db/backends/mysql/introspection.py", "language": "python", "file_size": 14976, "cut_index": 921, "middle_length": 229}} +{"prefix": "%(column)s %(type)s NOT NULL\"\n sql_alter_column_type = \"MODIFY %(column)s %(type)s%(collation)s%(comment)s\"\n sql_alter_column_no_default_null = \"ALTER COLUMN %(column)s SET DEFAULT NULL\"\n\n sql_delete_unique = \"ALTER TABLE %(table)s DROP INDEX %(name)s\"\n sql_create_column_inline_fk = (\n \", ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) \"\n \"REFERENCES %(to_table)s(%(to_column)s)%(on_delete_db)s\"\n )\n sql_delete_fk = \"ALTER TABLE %(table)s DROP FOREIGN KEY %(name)s\"\n\n sql_de", "suffix": "(columns)s)\"\n )\n sql_delete_pk = \"ALTER TABLE %(table)s DROP PRIMARY KEY\"\n\n sql_create_index = \"CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s\"\n\n sql_alter_table_comment = \"ALTER TABLE %(table)s COMMENT = %(comment)s\"\n sql_alter_c", "middle": "lete_index = \"DROP INDEX %(name)s ON %(table)s\"\n sql_rename_index = \"ALTER TABLE %(table)s RENAME INDEX %(old_name)s TO %(new_name)s\"\n\n sql_create_pk = (\n \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%", "meta": {"filepath": "django/db/backends/mysql/schema.py", "language": "python", "file_size": 9938, "cut_index": 921, "middle_length": 229}} +{"prefix": "\nfrom re import search as re_search\nfrom uuid import uuid4\n\nfrom django.db.backends.utils import (\n split_tzname_delta,\n typecast_time,\n typecast_timestamp,\n)\nfrom django.utils import timezone\nfrom django.utils.duration import duration_microseconds\nfrom django.utils.version import PY314\n\nif PY314:\n from uuid import uuid7\n\n\ndef register(connection):\n create_deterministic_function = functools.partial(\n connection.create_function,\n deterministic=True,\n )\n create_deterministic", "suffix": "me_cast_date\n )\n create_deterministic_function(\n \"django_datetime_cast_time\", 3, _sqlite_datetime_cast_time\n )\n create_deterministic_function(\n \"django_datetime_extract\", 4, _sqlite_datetime_extract\n )\n create_deterministic_", "middle": "_function(\"django_date_extract\", 2, _sqlite_datetime_extract)\n create_deterministic_function(\"django_date_trunc\", 4, _sqlite_date_trunc)\n create_deterministic_function(\n \"django_datetime_cast_date\", 3, _sqlite_dateti", "meta": {"filepath": "django/db/backends/sqlite3/_functions.py", "language": "python", "file_size": 15731, "cut_index": 921, "middle_length": 229}} +{"prefix": "\n\n\nclass DatabaseCreation(BaseDatabaseCreation):\n @staticmethod\n def is_in_memory_db(database_name):\n return not isinstance(database_name, Path) and (\n database_name == \":memory:\" or \"mode=memory\" in database_name\n )\n\n def _get_test_db_name(self):\n test_database_name = self.connection.settings_dict[\"TEST\"][\"NAME\"] or \":memory:\"\n if test_database_name == \":memory:\":\n return \"file:memorydb_%s?mode=memory&cache=shared\" % self.connection.alias\n r", "suffix": "_in_memory_db(test_database_name):\n # Erase the old test database\n if verbosity >= 1:\n self.log(\n \"Destroying old test database for alias %s...\"\n % (self._get_database_display_str(v", "middle": "eturn test_database_name\n\n def _create_test_db(self, verbosity, autoclobber, keepdb=False):\n test_database_name = self._get_test_db_name()\n\n if keepdb:\n return test_database_name\n if not self.is", "meta": {"filepath": "django/db/backends/sqlite3/creation.py", "language": "python", "file_size": 6823, "cut_index": 716, "middle_length": 229}} +{"prefix": "include variables in them -- e.g. \"varchar(30)\" -- and can't be matched\n# as a simple dictionary lookup.\nclass FlexibleFieldLookupDict:\n # Maps SQL types to Django Field types. Some of the SQL types have multiple\n # entries here because SQLite allows for anything and doesn't normalize the\n # field type; it uses whatever was given.\n base_data_types_reverse = {\n \"bool\": \"BooleanField\",\n \"boolean\": \"BooleanField\",\n \"smallint\": \"SmallIntegerField\",\n \"smallint unsigned\": \"", "suffix": " \"bigint unsigned\": \"PositiveBigIntegerField\",\n \"decimal\": \"DecimalField\",\n \"real\": \"FloatField\",\n \"text\": \"TextField\",\n \"char\": \"CharField\",\n \"varchar\": \"CharField\",\n \"blob\": \"BinaryField\",\n \"date\": \"", "middle": "PositiveSmallIntegerField\",\n \"smallinteger\": \"SmallIntegerField\",\n \"int\": \"IntegerField\",\n \"integer\": \"IntegerField\",\n \"bigint\": \"BigIntegerField\",\n \"integer unsigned\": \"PositiveIntegerField\",\n ", "meta": {"filepath": "django/db/backends/sqlite3/introspection.py", "language": "python", "file_size": 18046, "cut_index": 1331, "middle_length": 229}} +{"prefix": "_unique = \"DROP INDEX %(name)s\"\n sql_alter_table_comment = None\n sql_alter_column_comment = None\n\n def __enter__(self):\n # Some SQLite schema alterations need foreign key constraints to be\n # disabled. Enforce it here for the duration of the schema edition.\n if not self.connection.disable_constraint_checking():\n raise NotSupportedError(\n \"SQLite schema editor cannot be used while foreign key \"\n \"constraint checks are enabled. Make sure t", "suffix": " return super().__enter__()\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.connection.check_constraints()\n super().__exit__(exc_type, exc_value, traceback)\n self.connection.enable_constraint_checking()\n\n def q", "middle": "o disable them \"\n \"before entering a transaction.atomic() context because \"\n \"SQLite does not support disabling them in the middle of \"\n \"a multi-statement transaction.\"\n )\n", "meta": {"filepath": "django/db/backends/sqlite3/schema.py", "language": "python", "file_size": 20358, "cut_index": 1331, "middle_length": 229}} +{"prefix": "Forbidden,\n HttpResponseNotFound,\n HttpResponseServerError,\n)\nfrom django.template import Context, Engine, TemplateDoesNotExist, loader\nfrom django.views.decorators.csrf import requires_csrf_token\n\nERROR_404_TEMPLATE_NAME = \"404.html\"\nERROR_403_TEMPLATE_NAME = \"403.html\"\nERROR_400_TEMPLATE_NAME = \"400.html\"\nERROR_500_TEMPLATE_NAME = \"500.html\"\nERROR_PAGE_TEMPLATE = \"\"\"\n<!doctype html>\n<html lang=\"en\">\n<head>\n <title>%(title)s\n\n\n

%(title)s

%(details)s

\n\n\n\"\"\"\n\n\n# These views can be called when CsrfViewMiddleware.process_view() not run,\n# therefore need @requires_csrf_token in case the template needs\n# {% csrf_token %}.\n\n\n@requires_csrf_token\ndef page_not_found(request, exceptio", "meta": {"filepath": "django/views/defaults.py", "language": "python", "file_size": 4718, "cut_index": 614, "middle_length": 229}} +{"prefix": "on(using=None):\n \"\"\"\n Get a database connection by name, or the default database connection\n if no name is provided. This is a private API.\n \"\"\"\n if using is None:\n using = DEFAULT_DB_ALIAS\n return connections[using]\n\n\ndef get_autocommit(using=None):\n \"\"\"Get the autocommit status of the connection.\"\"\"\n return get_connection(using).get_autocommit()\n\n\ndef set_autocommit(autocommit, using=None):\n \"\"\"Set the autocommit status of the connection.\"\"\"\n return get_connection(usin", "suffix": "savepoint(using=None):\n warnings.warn(\n \"savepoint() is deprecated. Use savepoint_create() instead.\",\n category=RemovedInDjango70Warning,\n skip_file_prefixes=django_file_prefixes(),\n )\n return savepoint_create(using=using)\n\n\nd", "middle": "g).set_autocommit(autocommit)\n\n\ndef commit(using=None):\n \"\"\"Commit a transaction.\"\"\"\n get_connection(using).commit()\n\n\ndef rollback(using=None):\n \"\"\"Roll back a transaction.\"\"\"\n get_connection(using).rollback()\n\n\ndef ", "meta": {"filepath": "django/db/transaction.py", "language": "python", "file_size": 12872, "cut_index": 921, "middle_length": 229}} +{"prefix": "y\nfrom django.utils.regex_helper import _lazy_re_compile\n\ntry:\n import MySQLdb as Database\nexcept ImportError as err:\n raise ImproperlyConfigured(\n \"Error loading MySQLdb module.\\nDid you install mysqlclient?\"\n ) from err\n\nfrom MySQLdb.constants import CLIENT, FIELD_TYPE\nfrom MySQLdb.converters import conversions\n\n# Some of these import MySQLdb, so import them after checking if it's\n# installed.\nfrom .client import DatabaseClient\nfrom .creation import DatabaseCreation\nfrom .features import D", "suffix": "ersion < (2, 2, 1):\n raise ImproperlyConfigured(\n \"mysqlclient 2.2.1 or newer is required; you have %s.\" % Database.__version__\n )\n\n\n# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in\n# terms of actual behavior as t", "middle": "atabaseFeatures\nfrom .introspection import DatabaseIntrospection\nfrom .operations import DatabaseOperations\nfrom .schema import DatabaseSchemaEditor\nfrom .validation import DatabaseValidation\n\nversion = Database.version_info\nif v", "meta": {"filepath": "django/db/backends/mysql/base.py", "language": "python", "file_size": 16315, "cut_index": 921, "middle_length": 229}} +{"prefix": "alue = ()\n related_fields_match_type = True\n # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME.\n allow_sliced_subqueries_with_in = False\n has_select_for_update = True\n has_select_for_update_nowait = True\n has_select_for_update_skip_locked = True\n supports_forward_references = False\n supports_regex_backreferencing = False\n supports_date_lookup_using_string = False\n supports_timezones = False\n requires_explicit_null_ordering_when_grouping = True\n atomic_transac", "suffix": "_compound = True\n supports_index_on_text_field = False\n supports_over_clause = True\n supports_frame_range_fixed_distance = True\n supports_update_conflicts = True\n supports_default_in_bit_aggregations = False\n can_rename_index = True\n d", "middle": "tions = False\n can_clone_databases = True\n supports_aggregate_order_by_clause = True\n supports_comments = True\n supports_comments_inline = True\n supports_temporal_subtraction = True\n supports_slicing_ordering_in", "meta": {"filepath": "django/db/backends/mysql/features.py", "language": "python", "file_size": 8405, "cut_index": 716, "middle_length": 229}} +{"prefix": "rom django.utils.version import get_docs_version\n\n\nclass DatabaseValidation(BaseDatabaseValidation):\n def check(self, **kwargs):\n issues = super().check(**kwargs)\n issues.extend(self._check_sql_mode(**kwargs))\n return issues\n\n def _check_sql_mode(self, **kwargs):\n if not (\n self.connection.sql_mode & {\"STRICT_TRANS_TABLES\", \"STRICT_ALL_TABLES\"}\n ):\n return [\n checks.Warning(\n \"%s Strict Mode is not set for datab", "suffix": " \"%s, such as data truncation upon insertion, by \"\n \"escalating warnings into errors. It is strongly \"\n \"recommended you activate it. See: \"\n \"https://docs.djangoproject.com/en/%s/ref/da", "middle": "ase connection '%s'\"\n % (self.connection.display_name, self.connection.alias),\n hint=(\n \"%s's Strict Mode fixes many data integrity problems in \"\n ", "meta": {"filepath": "django/db/backends/mysql/validation.py", "language": "python", "file_size": 3093, "cut_index": 614, "middle_length": 229}} +{"prefix": "l import cached_property\nfrom django.utils.version import PY314\n\nfrom .base import Database\n\n\nclass DatabaseFeatures(BaseDatabaseFeatures):\n minimum_database_version = (3, 37)\n test_db_allows_multiple_connections = False\n supports_unspecified_pk = True\n supports_timezones = False\n supports_transactions = True\n atomic_transactions = False\n can_rollback_ddl = True\n can_create_inline_fk = False\n requires_literal_defaults = True\n can_clone_databases = True\n supports_temporal_sub", "suffix": " False\n can_defer_constraint_checks = True\n supports_over_clause = True\n supports_frame_range_fixed_distance = True\n supports_frame_exclusion = True\n supports_aggregate_filter_clause = True\n supports_aggregate_order_by_clause = Database.s", "middle": "traction = True\n ignores_table_name_case = True\n supports_cast_with_precision = False\n time_cast_precision = 3\n can_release_savepoints = True\n has_case_insensitive_like = True\n supports_parentheses_in_compound =", "meta": {"filepath": "django/db/backends/sqlite3/features.py", "language": "python", "file_size": 7086, "cut_index": 716, "middle_length": 229}} +{"prefix": "d functions for serving static files. These are only to be used during\ndevelopment, and SHOULD NOT be used in a production setting.\n\n\"\"\"\n\nimport os\nimport posixpath\n\nfrom django.conf import settings\nfrom django.contrib.staticfiles import finders\nfrom django.http import Http404\nfrom django.views import static\n\n\ndef serve(request, path, insecure=False, **kwargs):\n \"\"\"\n Serve static files below a given point in the directory structure or\n from locations inferred from the staticfiles finders.\n\n To u", "suffix": " \"\"\"\n if not settings.DEBUG and not insecure:\n raise Http404\n normalized_path = posixpath.normpath(path).lstrip(\"/\")\n absolute_path = finders.find(normalized_path)\n if not absolute_path:\n if path.endswith(\"/\") or path == \"\":\n ", "middle": "se, put a URL pattern such as::\n\n from django.contrib.staticfiles import views\n\n path('', views.serve)\n\n in your URLconf.\n\n It uses the django.views.static.serve() view to serve the found files.\n ", "meta": {"filepath": "django/contrib/staticfiles/views.py", "language": "python", "file_size": 1262, "cut_index": 524, "middle_length": 229}} +{"prefix": "Col\nfrom django.db.models.sql.compiler import SQLAggregateCompiler, SQLCompiler\nfrom django.db.models.sql.compiler import SQLDeleteCompiler as BaseSQLDeleteCompiler\nfrom django.db.models.sql.compiler import SQLInsertCompiler\nfrom django.db.models.sql.compiler import SQLUpdateCompiler as BaseSQLUpdateCompiler\n\n__all__ = [\n \"SQLAggregateCompiler\",\n \"SQLCompiler\",\n \"SQLDeleteCompiler\",\n \"SQLInsertCompiler\",\n \"SQLUpdateCompiler\",\n]\n\n\nclass SQLDeleteCompiler(BaseSQLDeleteCompiler):\n def as_sql(", "suffix": "fficient query\n # plan than when using a subquery.\n where, having, qualify = self.query.where.split_having_qualify(\n must_group_by=self.query.group_by is not None\n )\n if self.single_alias or having or qualify:\n ", "middle": "self):\n # Prefer the non-standard DELETE FROM syntax over the SQL generated by\n # the SQLDeleteCompiler's default implementation when multiple tables\n # are involved since MySQL/MariaDB will generate a more e", "meta": {"filepath": "django/db/backends/mysql/compiler.py", "language": "python", "file_size": 3047, "cut_index": 614, "middle_length": 229}} +{"prefix": "mport async_unsafe\nfrom django.utils.dateparse import parse_date, parse_datetime, parse_time\nfrom django.utils.regex_helper import _lazy_re_compile\n\nfrom ._functions import register as register_functions\nfrom .client import DatabaseClient\nfrom .creation import DatabaseCreation\nfrom .features import DatabaseFeatures\nfrom .introspection import DatabaseIntrospection\nfrom .operations import DatabaseOperations\nfrom .schema import DatabaseSchemaEditor\n\n\ndef decoder(conv_func):\n \"\"\"\n Convert bytestrings from", "suffix": "umn(data):\n if data[\"max_length\"] is None:\n return \"varchar\"\n return \"varchar(%(max_length)s)\" % data\n\n\nDatabase.register_converter(\"bool\", b\"1\".__eq__)\nDatabase.register_converter(\"date\", decoder(parse_date))\nDatabase.register_converter(\"time", "middle": " Python's sqlite3 interface to a regular string.\n \"\"\"\n return lambda s: conv_func(s.decode())\n\n\ndef adapt_date(val):\n return val.isoformat()\n\n\ndef adapt_datetime(val):\n return val.isoformat(\" \")\n\n\ndef _get_varchar_col", "meta": {"filepath": "django/db/backends/sqlite3/base.py", "language": "python", "file_size": 15095, "cut_index": 921, "middle_length": 229}} +{"prefix": "1615),\n }\n cast_data_types = {\n \"AutoField\": \"signed integer\",\n \"BigAutoField\": \"signed integer\",\n \"SmallAutoField\": \"signed integer\",\n \"CharField\": \"char(%(max_length)s)\",\n \"DecimalField\": \"decimal(%(max_digits)s, %(decimal_places)s)\",\n \"TextField\": \"char\",\n \"IntegerField\": \"signed integer\",\n \"BigIntegerField\": \"signed integer\",\n \"SmallIntegerField\": \"signed integer\",\n \"PositiveBigIntegerField\": \"unsigned integer\",\n \"Positiv", "suffix": "XTRACT format cannot be passed in parameters.\n _extract_format_re = _lazy_re_compile(r\"[A-Z_]+\")\n\n def date_extract_sql(self, lookup_type, sql, params):\n # https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html\n if lookup_type ", "middle": "eIntegerField\": \"unsigned integer\",\n \"PositiveSmallIntegerField\": \"unsigned integer\",\n \"DurationField\": \"signed integer\",\n }\n cast_char_field_without_max_length = \"char\"\n explain_prefix = \"EXPLAIN\"\n\n # E", "meta": {"filepath": "django/db/backends/mysql/operations.py", "language": "python", "file_size": 17469, "cut_index": 1331, "middle_length": 229}} +{"prefix": "teger_field_ranges = {\n \"SmallIntegerField\": (-32768, 32767),\n \"IntegerField\": (-2147483648, 2147483647),\n \"BigIntegerField\": (-9223372036854775808, 9223372036854775807),\n \"PositiveBigIntegerField\": (0, 9223372036854775807),\n \"PositiveSmallIntegerField\": (0, 32767),\n \"PositiveIntegerField\": (0, 2147483647),\n \"SmallAutoField\": (-32768, 32767),\n \"AutoField\": (-2147483648, 2147483647),\n \"BigAutoField\": (-9223372036854775808, 9223372036854775807),\n ", "suffix": " type to use for the Cast() function, if different from\n # DatabaseWrapper.data_types.\n cast_data_types = {}\n # CharField data type if the max_length argument isn't provided.\n cast_char_field_without_max_length = None\n\n # Start and end point", "middle": " }\n set_operators = {\n \"union\": \"UNION\",\n \"intersection\": \"INTERSECT\",\n \"difference\": \"EXCEPT\",\n }\n # Mapping of Field.get_internal_type() (typically the model field's class\n # name) to the data", "meta": {"filepath": "django/db/backends/base/operations.py", "language": "python", "file_size": 33304, "cut_index": 1331, "middle_length": 229}} +{"prefix": " connection,\n template=\"SHA2(%%(expressions)s, %s)\" % self.function[3:],\n **extra_context,\n )\n\n\nclass OracleHashMixin:\n def as_oracle(self, compiler, connection, **extra_context):\n return super().as_sql(\n compiler,\n connection,\n template=(\n \"LOWER(RAWTOHEX(STANDARD_HASH(UTL_I18N.STRING_TO_RAW(\"\n \"%(expressions)s, 'AL32UTF8'), '%(function)s')))\"\n ),\n **extra_context,\n )\n\n\n", "suffix": "nction)s'), 'hex')\",\n function=self.function.lower(),\n **extra_context,\n )\n\n\nclass Chr(Transform):\n function = \"CHR\"\n lookup_name = \"chr\"\n output_field = CharField()\n\n def as_mysql(self, compiler, connection, **extr", "middle": "class PostgreSQLSHAMixin:\n def as_postgresql(self, compiler, connection, **extra_context):\n return super().as_sql(\n compiler,\n connection,\n template=\"ENCODE(DIGEST(%(expressions)s, '%(fu", "meta": {"filepath": "django/db/models/functions/text.py", "language": "python", "file_size": 11538, "cut_index": 921, "middle_length": 229}} +{"prefix": "ion import BaseDatabaseCreation\nfrom django.db.backends.postgresql.psycopg_any import errors\nfrom django.db.backends.utils import strip_quotes\n\n\nclass DatabaseCreation(BaseDatabaseCreation):\n def _quote_name(self, name):\n return self.connection.ops.quote_name(name)\n\n def _get_database_create_suffix(self, encoding=None, template=None):\n suffix = \"\"\n if encoding:\n suffix += \" ENCODING '{}'\".format(encoding)\n if template:\n suffix += \" TEMPLATE {}\".format(", "suffix": " raise ImproperlyConfigured(\n \"PostgreSQL does not support collation setting at database \"\n \"creation time.\"\n )\n return self._get_database_create_suffix(\n encoding=test_settings[\"CHARSET", "middle": "self._quote_name(template))\n return suffix and \"WITH\" + suffix\n\n def sql_table_creation_suffix(self):\n test_settings = self.connection.settings_dict[\"TEST\"]\n if test_settings.get(\"COLLATION\") is not None:\n", "meta": {"filepath": "django/db/backends/postgresql/creation.py", "language": "python", "file_size": 3886, "cut_index": 614, "middle_length": 229}} +{"prefix": "ango.utils.functional import cached_property\n\n\nclass DatabaseFeatures(BaseDatabaseFeatures):\n minimum_database_version = (15,)\n allows_group_by_selected_pks = True\n can_return_columns_from_insert = True\n can_return_rows_from_bulk_insert = True\n can_return_rows_from_update = True\n has_real_datatype = True\n has_native_uuid_field = True\n has_native_duration_field = True\n has_native_json_field = True\n can_defer_constraint_checks = True\n has_select_for_update = True\n has_selec", "suffix": "spaces = True\n supports_transactions = True\n can_introspect_materialized_views = True\n can_distinct_on_fields = True\n can_rollback_ddl = True\n schema_editor_uses_clientside_param_binding = True\n supports_combined_alters = True\n nulls_o", "middle": "t_for_update_nowait = True\n has_select_for_update_of = True\n has_select_for_update_skip_locked = True\n has_select_for_no_key_update = True\n can_release_savepoints = True\n supports_comments = True\n supports_table", "meta": {"filepath": "django/db/backends/postgresql/features.py", "language": "python", "file_size": 6960, "cut_index": 716, "middle_length": 229}} +{"prefix": ".db.models.constants import OnConflict\nfrom django.db.models.functions import Cast\nfrom django.utils.regex_helper import _lazy_re_compile\n\n\n@lru_cache\ndef get_json_dumps(encoder):\n if encoder is None:\n return json.dumps\n return partial(json.dumps, cls=encoder)\n\n\nclass DatabaseOperations(BaseDatabaseOperations):\n compiler_module = \"django.db.backends.postgresql.compiler\"\n cast_char_field_without_max_length = \"varchar\"\n explain_prefix = \"EXPLAIN\"\n explain_options = frozenset(\n ", "suffix": "BOSE\",\n \"WAL\",\n ]\n )\n cast_data_types = {\n \"AutoField\": \"integer\",\n \"BigAutoField\": \"bigint\",\n \"SmallAutoField\": \"smallint\",\n }\n\n if is_psycopg3:\n from psycopg.types import numeric\n\n integerf", "middle": "[\n \"ANALYZE\",\n \"BUFFERS\",\n \"COSTS\",\n \"GENERIC_PLAN\",\n \"MEMORY\",\n \"SETTINGS\",\n \"SERIALIZE\",\n \"SUMMARY\",\n \"TIMING\",\n \"VER", "meta": {"filepath": "django/db/backends/postgresql/operations.py", "language": "python", "file_size": 15521, "cut_index": 921, "middle_length": 229}} +{"prefix": "efault = (\n \"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL\"\n \"; SET CONSTRAINTS ALL IMMEDIATE\"\n )\n sql_alter_sequence_type = \"ALTER SEQUENCE IF EXISTS %(sequence)s AS %(type)s\"\n sql_delete_sequence = \"DROP SEQUENCE IF EXISTS %(sequence)s CASCADE\"\n\n sql_create_index = (\n \"CREATE INDEX %(name)s ON %(table)s%(using)s \"\n \"(%(columns)s)%(include)s%(extra)s%(condition)s\"\n )\n sql_create_index_concurrently = (\n \"CREATE INDEX CONCURRENTLY ", "suffix": "s\"\n\n # Setting the constraint to IMMEDIATE to allow changing data in the same\n # transaction.\n sql_create_column_inline_fk = (\n \"CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(on_delete_db)s\"\n \"%(deferrable)s; SET CONSTR", "middle": "%(name)s ON %(table)s%(using)s \"\n \"(%(columns)s)%(include)s%(extra)s%(condition)s\"\n )\n sql_delete_index = \"DROP INDEX IF EXISTS %(name)s\"\n sql_delete_index_concurrently = \"DROP INDEX CONCURRENTLY IF EXISTS %(name)", "meta": {"filepath": "django/db/backends/postgresql/schema.py", "language": "python", "file_size": 14772, "cut_index": 921, "middle_length": 229}} +{"prefix": " # Cygwin requires some special voodoo to set the environment variables\n # properly so that Oracle will see them.\n if platform.system().upper().startswith(\"CYGWIN\"):\n try:\n import ctypes\n except ImportError as e:\n raise ImproperlyConfigured(\n \"Error loading ctypes: %s; \"\n \"the Oracle backend requires ctypes to \"\n \"operate correctly under Cygwin.\" % e\n )\n kernel32 = ctypes.CDLL(\"kernel32\")\n for ", "suffix": "ment.\n (\"NLS_LANG\", \".AL32UTF8\"),\n # This prevents Unicode from getting mangled by getting encoded into\n # the potentially non-Unicode database character set.\n (\"ORA_NCHAR_LITERAL_REPLACE\", \"TRUE\"),\n ]\n)\n\n\n# Some of these imp", "middle": "name, value in environ:\n kernel32.SetEnvironmentVariableA(name, value)\n else:\n os.environ.update(environ)\n\n\n_setup_environment(\n [\n # Oracle takes client-side character set encoding from the environ", "meta": {"filepath": "django/db/backends/oracle/base.py", "language": "python", "file_size": 25945, "cut_index": 1331, "middle_length": 229}} +{"prefix": " # Although GROUP BY select index is supported by Oracle 23c+, it requires\n # GROUP_BY_POSITION_ENABLED to be enabled to avoid backward compatibility\n # issues. Introspection of this settings is not straightforward.\n allows_group_by_select_index = False\n interprets_empty_strings_as_nulls = True\n has_select_for_update = True\n has_select_for_update_nowait = True\n has_select_for_update_skip_locked = True\n has_select_for_update_of = True\n select_for_update_of_column = True\n can_r", "suffix": " supports_transactions = True\n supports_timezones = False\n has_native_duration_field = True\n can_defer_constraint_checks = True\n supports_partially_nullable_unique_constraints = False\n supports_deferrable_unique_constraints = True\n trunca", "middle": "eturn_columns_from_insert = True\n can_return_rows_from_update = True\n supports_subqueries_in_group_by = False\n ignores_unnecessary_order_by_in_subqueries = False\n supports_tuple_comparison_against_subquery = False\n ", "meta": {"filepath": "django/db/backends/oracle/features.py", "language": "python", "file_size": 10084, "cut_index": 921, "middle_length": 229}} +{"prefix": "mment\"]\n)\nTableInfo = namedtuple(\"TableInfo\", [*BaseTableInfo._fields, \"comment\"])\n\n\nclass DatabaseIntrospection(BaseDatabaseIntrospection):\n cache_bust_counter = 1\n\n # Maps type objects to Django Field types.\n data_types_reverse = {\n oracledb.DB_TYPE_DATE: \"DateField\",\n oracledb.DB_TYPE_BINARY_DOUBLE: \"FloatField\",\n oracledb.DB_TYPE_BLOB: \"BinaryField\",\n oracledb.DB_TYPE_CHAR: \"CharField\",\n oracledb.DB_TYPE_CLOB: \"TextField\",\n oracledb.DB_TYPE_INTERVAL_DS:", "suffix": "_TIMESTAMP: \"DateTimeField\",\n oracledb.DB_TYPE_VARCHAR: \"CharField\",\n }\n\n def get_field_type(self, data_type, description):\n if data_type == oracledb.NUMBER:\n precision, scale = description[4:6]\n if scale == 0:\n ", "middle": " \"DurationField\",\n oracledb.DB_TYPE_NCHAR: \"CharField\",\n oracledb.DB_TYPE_NCLOB: \"TextField\",\n oracledb.DB_TYPE_NVARCHAR: \"CharField\",\n oracledb.DB_TYPE_NUMBER: \"DecimalField\",\n oracledb.DB_TYPE", "meta": {"filepath": "django/db/backends/oracle/introspection.py", "language": "python", "file_size": 15917, "cut_index": 921, "middle_length": 229}} +{"prefix": "olumn)s %(type)s%(collation)s\"\n sql_alter_column_null = \"MODIFY %(column)s NULL\"\n sql_alter_column_not_null = \"MODIFY %(column)s NOT NULL\"\n sql_alter_column_default = \"MODIFY %(column)s DEFAULT %(default)s\"\n sql_alter_column_no_default = \"MODIFY %(column)s DEFAULT NULL\"\n sql_alter_column_no_default_null = sql_alter_column_no_default\n\n sql_create_column_inline_fk = (\n \"CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(on_delete_db)\"\n \"s%(deferrable)s\"\n )\n sql_d", "suffix": "time, datetime.datetime)):\n return \"'%s'\" % value\n elif isinstance(value, datetime.timedelta):\n return \"'%s'\" % duration_iso_string(value)\n elif isinstance(value, str):\n return \"'%s'\" % value.replace(\"'\", \"''\"", "middle": "elete_table = \"DROP TABLE %(table)s CASCADE CONSTRAINTS\"\n sql_create_index = \"CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s\"\n\n def quote_value(self, value):\n if isinstance(value, (datetime.date, datetime.", "meta": {"filepath": "django/db/backends/oracle/schema.py", "language": "python", "file_size": 10849, "cut_index": 921, "middle_length": 229}} +{"prefix": "import checks\nfrom django.db.backends.base.validation import BaseDatabaseValidation\n\n\nclass DatabaseValidation(BaseDatabaseValidation):\n def check_field_type(self, field, field_type):\n \"\"\"Oracle doesn't support a database index on some data types.\"\"\"\n errors = []\n if field.db_index and field_type.lower() in self.connection._limited_data_types:\n errors.append(\n checks.Warning(\n \"Oracle does not support a database index on %s columns.\"\n ", "suffix": "t=(\n \"An index won't be created. Silence this warning if \"\n \"you don't care about it.\"\n ),\n obj=field,\n id=\"fields.W162\",\n )\n )", "middle": " % field_type,\n hin", "meta": {"filepath": "django/db/backends/oracle/validation.py", "language": "python", "file_size": 860, "cut_index": 529, "middle_length": 52}} +{"prefix": "fines the reference interface.\"\"\"\n\n def references_table(self, table):\n \"\"\"\n Return whether or not this instance references the specified table.\n \"\"\"\n return False\n\n def references_column(self, table, column):\n \"\"\"\n Return whether or not this instance references the specified column.\n \"\"\"\n return False\n\n def references_index(self, table, index):\n \"\"\"\n Return whether or not this instance references the specified index.\n \"\"\"", "suffix": "e, old_column, new_column):\n \"\"\"\n Rename all references to the old_column to the new_column.\n \"\"\"\n pass\n\n def __repr__(self):\n return \"<%s %r>\" % (self.__class__.__name__, str(self))\n\n def __str__(self):\n rai", "middle": "\n return False\n\n def rename_table_references(self, old_table, new_table):\n \"\"\"\n Rename all references to the old_name to the new_table.\n \"\"\"\n pass\n\n def rename_column_references(self, tabl", "meta": {"filepath": "django/db/backends/ddl_references.py", "language": "python", "file_size": 8619, "cut_index": 716, "middle_length": 229}} +{"prefix": "import BaseDatabaseClient\n\n\nclass DatabaseClient(BaseDatabaseClient):\n executable_name = \"psql\"\n\n @classmethod\n def settings_to_cmd_args_env(cls, settings_dict, parameters):\n args = [cls.executable_name]\n options = settings_dict[\"OPTIONS\"]\n\n host = settings_dict.get(\"HOST\")\n port = settings_dict.get(\"PORT\")\n dbname = settings_dict.get(\"NAME\")\n user = settings_dict.get(\"USER\")\n passwd = settings_dict.get(\"PASSWORD\")\n passfile = options.get(\"pas", "suffix": "f not dbname and not service:\n # Connect to the default 'postgres' db.\n dbname = \"postgres\"\n if user:\n args += [\"-U\", user]\n if host:\n args += [\"-h\", host]\n if port:\n args += [\"-p\"", "middle": "sfile\")\n service = options.get(\"service\")\n sslmode = options.get(\"sslmode\")\n sslrootcert = options.get(\"sslrootcert\")\n sslcert = options.get(\"sslcert\")\n sslkey = options.get(\"sslkey\")\n\n i", "meta": {"filepath": "django/db/backends/postgresql/client.py", "language": "python", "file_size": 2044, "cut_index": 563, "middle_length": 229}} +{"prefix": " this if the database ENGINE setting is empty (None or empty\nstring).\n\nEach of these API functions, except connection.close(), raise\nImproperlyConfigured.\n\"\"\"\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db.backends.base.base import BaseDatabaseWrapper\nfrom django.db.backends.base.client import BaseDatabaseClient\nfrom django.db.backends.base.creation import BaseDatabaseCreation\nfrom django.db.backends.base.introspection import BaseDatabaseIntrospection\nfrom django.db.backends.base.op", "suffix": " \"Please supply the ENGINE value. Check \"\n \"settings documentation for more details.\"\n )\n\n\ndef ignore(*args, **kwargs):\n pass\n\n\nclass DatabaseOperations(BaseDatabaseOperations):\n quote_name = complain\n\n\nclass DatabaseClient(BaseDataba", "middle": "erations import BaseDatabaseOperations\nfrom django.db.backends.dummy.features import DummyDatabaseFeatures\n\n\ndef complain(*args, **kwargs):\n raise ImproperlyConfigured(\n \"settings.DATABASES is improperly configured. \"\n ", "meta": {"filepath": "django/db/backends/dummy/base.py", "language": "python", "file_size": 2217, "cut_index": 563, "middle_length": 229}} +{"prefix": "ld? All core backends implement this correctly, but other\n # databases such as SQL Server do not.\n supports_nullable_unique_constraints = True\n\n # Does the backend allow inserting duplicate rows when a unique_together\n # constraint exists and some fields are nullable but not all of them?\n supports_partially_nullable_unique_constraints = True\n\n # Does the backend supports specifying whether NULL values should be\n # considered distinct in unique constraints?\n supports_nulls_distinct_un", "suffix": " can_return_rows_from_bulk_insert = False\n can_return_rows_from_update = False\n has_bulk_insert = True\n uses_savepoints = True\n can_release_savepoints = False\n\n # If True, don't use integer foreign keys referring to, e.g., positive\n # int", "middle": "ique_constraints = False\n\n # Does the backend support initially deferrable unique constraints?\n supports_deferrable_unique_constraints = False\n\n can_use_chunked_reads = True\n can_return_columns_from_insert = False\n ", "meta": {"filepath": "django/db/backends/base/features.py", "language": "python", "file_size": 18285, "cut_index": 1331, "middle_length": 229}} +{"prefix": "__\"\nRAN_DB_VERSION_CHECK = set()\n\nlogger = logging.getLogger(\"django.db.backends.base\")\n\n\nclass BaseDatabaseWrapper:\n \"\"\"Represent a database connection.\"\"\"\n\n # Mapping of Field objects to their column types.\n data_types = {}\n # Mapping of Field objects to their SQL suffix such as AUTOINCREMENT.\n data_types_suffix = {}\n # Mapping of Field objects to their SQL for CHECK constraints.\n data_type_check_constraints = {}\n ops = None\n vendor = \"unknown\"\n display_name = \"unknown\"\n S", "suffix": "Validation\n\n queries_limit = 9000\n\n def __init__(self, settings_dict, alias=DEFAULT_DB_ALIAS):\n # Connection related attributes.\n # The underlying database connection.\n self.connection = None\n # `settings_dict` should be a", "middle": "chemaEditorClass = None\n # Classes instantiated in __init__().\n client_class = None\n creation_class = None\n features_class = None\n introspection_class = None\n ops_class = None\n validation_class = BaseDatabase", "meta": {"filepath": "django/db/backends/base/base.py", "language": "python", "file_size": 28546, "cut_index": 1331, "middle_length": 229}} +{"prefix": ", Index\n\nFieldInfo = namedtuple(\"FieldInfo\", [*BaseFieldInfo._fields, \"is_autofield\", \"comment\"])\nTableInfo = namedtuple(\"TableInfo\", [*BaseTableInfo._fields, \"comment\"])\n\n\nclass DatabaseIntrospection(BaseDatabaseIntrospection):\n # Maps type codes to Django Field types.\n data_types_reverse = {\n 16: \"BooleanField\",\n 17: \"BinaryField\",\n 20: \"BigIntegerField\",\n 21: \"SmallIntegerField\",\n 23: \"IntegerField\",\n 25: \"TextField\",\n 700: \"FloatField\",\n 701:", "suffix": "meField\",\n 1186: \"DurationField\",\n 1266: \"TimeField\",\n 1700: \"DecimalField\",\n 2950: \"UUIDField\",\n 3802: \"JSONField\",\n }\n # A hook for subclasses.\n index_default_access_method = \"btree\"\n\n ignored_tables = []\n\n ", "middle": " \"FloatField\",\n 869: \"GenericIPAddressField\",\n 1042: \"CharField\", # blank-padded\n 1043: \"CharField\",\n 1082: \"DateField\",\n 1083: \"TimeField\",\n 1114: \"DateTimeField\",\n 1184: \"DateTi", "meta": {"filepath": "django/db/backends/postgresql/introspection.py", "language": "python", "file_size": 12717, "cut_index": 921, "middle_length": 229}} +{"prefix": ".connection.alias]\n user = settings_dict.get(\"SAVED_USER\") or settings_dict[\"USER\"]\n password = settings_dict.get(\"SAVED_PASSWORD\") or settings_dict[\"PASSWORD\"]\n settings_dict = {**settings_dict, \"USER\": user, \"PASSWORD\": password}\n DatabaseWrapper = type(self.connection)\n return DatabaseWrapper(settings_dict, alias=self.connection.alias)\n\n def _create_test_db(self, verbosity=1, autoclobber=False, keepdb=False):\n parameters = self._get_test_db_params()\n wi", "suffix": " )\n except Exception as e:\n if \"ORA-01543\" not in str(e):\n # All errors except \"tablespace already exists\" cancel\n # tests\n self.log(\"Go", "middle": "th self._maindb_connection.cursor() as cursor:\n if self._test_database_create():\n try:\n self._execute_test_db_creation(\n cursor, parameters, verbosity, keepdb\n ", "meta": {"filepath": "django/db/backends/oracle/creation.py", "language": "python", "file_size": 21081, "cut_index": 1331, "middle_length": 229}} +{"prefix": "):\n # Oracle uses NUMBER(5), NUMBER(11), and NUMBER(19) for integer fields.\n # SmallIntegerField uses NUMBER(11) instead of NUMBER(5), which is used by\n # SmallAutoField, to preserve backward compatibility.\n integer_field_ranges = {\n \"SmallIntegerField\": (-99999999999, 99999999999),\n \"IntegerField\": (-99999999999, 99999999999),\n \"BigIntegerField\": (-9999999999999999999, 9999999999999999999),\n \"PositiveBigIntegerField\": (0, 9999999999999999999),\n \"PositiveSmallI", "suffix": "999999999999),\n }\n set_operators = {**BaseDatabaseOperations.set_operators, \"difference\": \"MINUS\"}\n\n # TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.\n _sequence_reset_sql = \"\"\"\nDECLARE\n table_value integer;\n seq_value integer", "middle": "ntegerField\": (0, 99999999999),\n \"PositiveIntegerField\": (0, 99999999999),\n \"SmallAutoField\": (-99999, 99999),\n \"AutoField\": (-99999999999, 99999999999),\n \"BigAutoField\": (-9999999999999999999, 9999999", "meta": {"filepath": "django/db/backends/oracle/operations.py", "language": "python", "file_size": 29468, "cut_index": 1331, "middle_length": 229}} +{"prefix": "sions import Col\nfrom django.utils import timezone\nfrom django.utils.dateparse import parse_date, parse_datetime, parse_time\nfrom django.utils.functional import cached_property\n\nfrom .base import Database\n\nUNSUPPORTED_DATETIME_AGGREGATES = (\n models.Sum,\n models.Avg,\n models.Variance,\n models.StdDev,\n)\nDATETIME_FIELDS = (models.DateField, models.DateTimeField, models.TimeField)\n\n\nclass DatabaseOperations(BaseDatabaseOperations):\n cast_char_field_without_max_length = \"text\"\n cast_data_types", "suffix": " jsonfield_datatype_values = frozenset([\"null\", \"false\", \"true\"])\n\n def check_expression_support(self, expression):\n if isinstance(expression, UNSUPPORTED_DATETIME_AGGREGATES):\n for expr in expression.get_source_expressions():\n ", "middle": " = {\n \"DateField\": \"TEXT\",\n \"DateTimeField\": \"TEXT\",\n }\n explain_prefix = \"EXPLAIN QUERY PLAN\"\n # List of datatypes to that cannot be extracted with JSON_EXTRACT() on\n # SQLite. Use JSON_TYPE() instead.\n", "meta": {"filepath": "django/db/backends/sqlite3/operations.py", "language": "python", "file_size": 15892, "cut_index": 921, "middle_length": 229}} +{"prefix": "late backend-specific methods for opening a client shell.\"\"\"\n\n # This should be a string representing the name of the executable\n # (e.g., \"psql\"). Subclasses must override this.\n executable_name = None\n\n def __init__(self, connection):\n # connection is an instance of BaseDatabaseWrapper.\n self.connection = connection\n\n def __del__(self):\n del self.connection\n\n @classmethod\n def settings_to_cmd_args_env(cls, settings_dict, parameters):\n raise NotImplementedEr", "suffix": "ust provide a \"\n \"settings_to_cmd_args_env() method or override a runshell().\"\n )\n\n def runshell(self, parameters):\n args, env = self.settings_to_cmd_args_env(\n self.connection.settings_dict, parameters\n )\n ", "middle": "ror(\n \"subclasses of BaseDatabaseClient m", "meta": {"filepath": "django/db/backends/base/client.py", "language": "python", "file_size": 989, "cut_index": 582, "middle_length": 52}} +{"prefix": "\"TableInfo\", [\"name\", \"type\"])\n\n# Structure returned by the DB-API cursor.description interface (PEP 249)\nFieldInfo = namedtuple(\n \"FieldInfo\",\n \"name type_code display_size internal_size precision scale null_ok \"\n \"default collation\",\n)\n\n\nclass BaseDatabaseIntrospection:\n \"\"\"Encapsulate backend-specific introspection utilities.\"\"\"\n\n data_types_reverse = {}\n on_delete_types = {\n \"CASCADE\": DB_CASCADE,\n \"NO ACTION\": DO_NOTHING,\n \"SET DEFAULT\": DB_SET_DEFAULT,\n \"S", "suffix": "pe(self, data_type, description):\n \"\"\"\n Hook for a database backend to use the cursor description to\n match a Django field type to a database column.\n\n For Oracle, the column data_type on its own is insufficient to\n disti", "middle": "ET NULL\": DB_SET_NULL,\n # DB_RESTRICT - \"RESTRICT\" is not supported.\n }\n\n def __init__(self, connection):\n self.connection = connection\n\n def __del__(self):\n del self.connection\n\n def get_field_ty", "meta": {"filepath": "django/db/backends/base/introspection.py", "language": "python", "file_size": 8317, "cut_index": 716, "middle_length": 229}} +{"prefix": "Level, adapt, adapters, errors, pq, sql\n from psycopg.postgres import types\n from psycopg.types.json import Jsonb\n from psycopg.types.range import Range, RangeDumper\n from psycopg.types.string import TextLoader\n\n Inet = ipaddress.ip_address\n\n DateRange = DateTimeRange = DateTimeTZRange = NumericRange = Range\n RANGE_TYPES = (Range,)\n\n TSRANGE_OID = types[\"tsrange\"].oid\n TSTZRANGE_OID = types[\"tstzrange\"].oid\n orig_tz_loader_cls = adapters.get_loader(\n types[\"timestamptz\"]", "suffix": "oader(adapt.Loader):\n \"\"\"\n Load a PostgreSQL timestamptz using the a specific timezone.\n The timezone can be None too, in which case it will be chopped.\n \"\"\"\n\n timezone = None\n\n def __init__(self, oid, context):\n ", "middle": ".oid,\n pq.Format.TEXT,\n )\n\n def mogrify(sql, params, connection):\n with connection.cursor() as cursor:\n return ClientCursor(cursor.connection).mogrify(sql, params)\n\n # Adapters.\n class BaseTzL", "meta": {"filepath": "django/db/backends/postgresql/psycopg_any.py", "language": "python", "file_size": 4074, "cut_index": 614, "middle_length": 229}} +{"prefix": "import shutil\n\nfrom django.db.backends.base.client import BaseDatabaseClient\n\n\nclass DatabaseClient(BaseDatabaseClient):\n executable_name = \"sqlplus\"\n wrapper_name = \"rlwrap\"\n\n @staticmethod\n def connect_string(settings_dict):\n from django.db.backends.oracle.utils import dsn\n\n return '%s/\"%s\"@%s' % (\n settings_dict[\"USER\"],\n settings_dict[\"PASSWORD\"],\n dsn(settings_dict),\n )\n\n @classmethod\n def settings_to_cmd_args_env(cls, settings_dic", "suffix": ":\n args = [cls.executable_name, \"-L\", cls.connect_string(settings_dict)]\n wrapper_path = shutil.which(cls.wrapper_name)\n if wrapper_path:\n args = [wrapper_path, *args]\n args.extend(parameters)\n return args, Non", "middle": "t, parameters)", "meta": {"filepath": "django/db/backends/oracle/client.py", "language": "python", "file_size": 784, "cut_index": 512, "middle_length": 14}} +{"prefix": "t:skip\n SQLAggregateCompiler,\n SQLCompiler,\n SQLDeleteCompiler,\n SQLInsertCompiler as BaseSQLInsertCompiler,\n SQLUpdateCompiler,\n)\n\n__all__ = [\n \"SQLAggregateCompiler\",\n \"SQLCompiler\",\n \"SQLDeleteCompiler\",\n \"SQLInsertCompiler\",\n \"SQLUpdateCompiler\",\n]\n\n\nclass InsertUnnest(list):\n \"\"\"\n Sentinel value to signal DatabaseOperations.bulk_insert_sql() that the\n UNNEST strategy should be used for the bulk insert.\n \"\"\"\n\n def __str__(self):\n return \"UNNEST(%s)\" % ", "suffix": " the query.\n if (\n # The optimization is not worth doing if there is a single\n # row as it will result in the same number of placeholders.\n len(value_rows) <= 1\n # Lack of fields denote the usage of the DE", "middle": "\", \".join(self)\n\n\nclass SQLInsertCompiler(BaseSQLInsertCompiler):\n def assemble_as_sql(self, fields, value_rows):\n # Specialize bulk-insertion of literal values through UNNEST to\n # reduce the time spent planning", "meta": {"filepath": "django/db/backends/postgresql/compiler.py", "language": "python", "file_size": 2478, "cut_index": 563, "middle_length": 229}} +{"prefix": "atabase\n\n\nclass BoundVar:\n \"\"\"\n A late-binding cursor variable that can be passed to Cursor.execute\n as a parameter, in order to receive the id of the row created by an\n insert statement.\n \"\"\"\n\n types = {\n \"AutoField\": int,\n \"BigAutoField\": int,\n \"SmallAutoField\": int,\n \"IntegerField\": int,\n \"BigIntegerField\": int,\n \"SmallIntegerField\": int,\n \"PositiveBigIntegerField\": int,\n \"PositiveSmallIntegerField\": int,\n \"PositiveIntegerFi", "suffix": "\n\n def __init__(self, field):\n internal_type = getattr(field, \"target_field\", field).get_internal_type()\n self.db_type = self.types.get(internal_type, str)\n self.bound_param = None\n\n def bind_parameter(self, cursor):\n self", "middle": "eld\": int,\n \"BooleanField\": int,\n \"FloatField\": Database.DB_TYPE_BINARY_DOUBLE,\n \"DateTimeField\": Database.DB_TYPE_TIMESTAMP,\n \"DateField\": datetime.date,\n \"DecimalField\": decimal.Decimal,\n }", "meta": {"filepath": "django/db/backends/oracle/utils.py", "language": "python", "file_size": 2752, "cut_index": 563, "middle_length": 229}} +{"prefix": "port DecimalField, DurationField, Func\n\n\nclass IntervalToSeconds(Func):\n function = \"\"\n template = \"\"\"\n EXTRACT(day from %(expressions)s) * 86400 +\n EXTRACT(hour from %(expressions)s) * 3600 +\n EXTRACT(minute from %(expressions)s) * 60 +\n EXTRACT(second from %(expressions)s)\n \"\"\"\n\n def __init__(self, expression, *, output_field=None, **extra):\n super().__init__(\n expression, output_field=output_field or DecimalField(), **extra\n )\n\n\nclass SecondsToInterval(Fun", "suffix": "on = \"NUMTODSINTERVAL\"\n template = \"%(function)s(%(expressions)s, 'SECOND')\"\n\n def __init__(self, expression, *, output_field=None, **extra):\n super().__init__(\n expression, output_field=output_field or DurationField(), **extra\n ", "middle": "c):\n functi", "meta": {"filepath": "django/db/backends/oracle/functions.py", "language": "python", "file_size": 812, "cut_index": 536, "middle_length": 14}} +{"prefix": "ss BaseDatabaseValidation:\n \"\"\"Encapsulate backend-specific validation.\"\"\"\n\n def __init__(self, connection):\n self.connection = connection\n\n def __del__(self):\n del self.connection\n\n def check(self, **kwargs):\n return []\n\n def check_field(self, field, **kwargs):\n errors = []\n # Backends may implement a check_field_type() method.\n if (\n hasattr(self, \"check_field_type\")\n and\n # Ignore any related fields.\n not", "suffix": " for feature in field.model._meta.required_db_features\n )\n if db_supports_all_required_features:\n field_type = field.db_type(self.connection)\n # Ignore non-concrete fields.\n if fie", "middle": " getattr(field, \"remote_field\", None)\n ):\n # Ignore fields with unsupported features.\n db_supports_all_required_features = all(\n getattr(self.connection.features, feature, False)\n ", "meta": {"filepath": "django/db/backends/base/validation.py", "language": "python", "file_size": 1119, "cut_index": 515, "middle_length": 229}} +{"prefix": "m django.db.models.functions.mixins import (\n FixDurationInputMixin,\n NumericOutputFieldMixin,\n)\n\n__all__ = [\n \"Aggregate\",\n \"AnyValue\",\n \"Avg\",\n \"BitAnd\",\n \"BitOr\",\n \"BitXor\",\n \"Count\",\n \"Max\",\n \"Min\",\n \"StdDev\",\n \"StringAgg\",\n \"Sum\",\n \"Variance\",\n]\n\n\nclass AggregateFilter(Func):\n arity = 1\n template = \" FILTER (WHERE %(expressions)s)\"\n\n def as_sql(self, compiler, connection, **extra_context):\n if not connection.features.supports_aggregate_filter", "suffix": "xt)\n except FullResultSet:\n return \"\", ()\n\n @property\n def condition(self):\n return self.source_expressions[0]\n\n def __str__(self):\n return self.arg_joiner.join(str(arg) for arg in self.source_expressions)\n\n\nclass A", "middle": "_clause:\n raise NotSupportedError(\n \"Aggregate filter clauses are not supported on this database backend.\"\n )\n try:\n return super().as_sql(compiler, connection, **extra_conte", "meta": {"filepath": "django/db/models/aggregates.py", "language": "python", "file_size": 15427, "cut_index": 921, "middle_length": 229}} +{"prefix": "without a (Django-specific) contribute_to_class()\n # method to type.__new__() so that they're properly initialized\n # (i.e. __set_name__()).\n contributable_attrs = {}\n for obj_name, obj in attrs.items():\n if _has_contribute_to_class(obj):\n contributable_attrs[obj_name] = obj\n else:\n new_attrs[obj_name] = obj\n new_class = super_new(cls, name, bases, new_attrs, **kwargs)\n\n abstract = getattr(attr_meta, \"abstract\", Fa", "suffix": "p_config = apps.get_containing_app_config(module)\n\n if getattr(meta, \"app_label\", None) is None:\n if app_config is None:\n if not abstract:\n raise RuntimeError(\n \"Model class %s.%s d", "middle": "lse)\n meta = attr_meta or getattr(new_class, \"Meta\", None)\n base_meta = getattr(new_class, \"_meta\", None)\n\n app_label = None\n\n # Look for an application configuration to attach the model to.\n ap", "meta": {"filepath": "django/db/models/base.py", "language": "python", "file_size": 99353, "cut_index": 3790, "middle_length": 229}} +{"prefix": "Enum\nfrom enum import property as enum_property\n\nfrom django.utils.functional import Promise\n\n__all__ = [\"Choices\", \"IntegerChoices\", \"TextChoices\"]\n\n\nclass ChoicesType(EnumType):\n \"\"\"A metaclass for creating a enum choices.\"\"\"\n\n def __new__(metacls, classname, bases, classdict, **kwds):\n labels = []\n for key in classdict._member_names:\n value = classdict[key]\n if (\n isinstance(value, (list, tuple))\n and len(value) > 1\n a", "suffix": "label)\n # Use dict.__setitem__() to suppress defenses against double\n # assignment in enum's classdict.\n dict.__setitem__(classdict, key, value)\n cls = super().__new__(metacls, classname, bases, classdict, **kwds)\n ", "middle": "nd isinstance(value[-1], (Promise, str))\n ):\n *value, label = value\n value = tuple(value)\n else:\n label = key.replace(\"_\", \" \").title()\n labels.append(", "meta": {"filepath": "django/db/models/enums.py", "language": "python", "file_size": 2367, "cut_index": 563, "middle_length": 229}} +{"prefix": "jango.core.exceptions import FieldFetchBlocked\n\n\nclass FetchMode:\n __slots__ = ()\n\n track_peers = False\n\n def fetch(self, fetcher, instance):\n raise NotImplementedError(\"Subclasses must implement this method.\")\n\n\nclass FetchOne(FetchMode):\n __slots__ = ()\n\n def fetch(self, fetcher, instance):\n fetcher.fetch_one(instance)\n\n def __reduce__(self):\n return \"FETCH_ONE\"\n\n\nFETCH_ONE = FetchOne()\n\n\nclass FetchPeers(FetchMode):\n __slots__ = ()\n\n track_peers = True\n\n de", "suffix": " fetcher.fetch_many(instances)\n else:\n fetcher.fetch_one(instance)\n\n def __reduce__(self):\n return \"FETCH_PEERS\"\n\n\nFETCH_PEERS = FetchPeers()\n\n\nclass Raise(FetchMode):\n __slots__ = ()\n\n def fetch(self, fetcher, instance)", "middle": "f fetch(self, fetcher, instance):\n instances = [\n peer\n for peer_weakref in instance._state.peers\n if (peer := peer_weakref()) is not None\n ]\n if len(instances) > 1:\n ", "meta": {"filepath": "django/db/models/fetch_modes.py", "language": "python", "file_size": 1249, "cut_index": 518, "middle_length": 229}} +{"prefix": "self.get_prep_lhs()\n if hasattr(self.lhs, \"get_bilateral_transforms\"):\n bilateral_transforms = self.lhs.get_bilateral_transforms()\n else:\n bilateral_transforms = []\n if bilateral_transforms:\n # Warn the user as soon as possible if they are trying to apply\n # a bilateral transformation on a nested QuerySet: that won't work.\n from django.db.models.sql.query import Query # avoid circular import\n\n if isinstance(rhs, Query):\n", "suffix": "al_transforms(self, value):\n for transform in self.bilateral_transforms:\n value = transform(value)\n return value\n\n def __repr__(self):\n return f\"{self.__class__.__name__}({self.lhs!r}, {self.rhs!r})\"\n\n def batch_proces", "middle": " raise NotImplementedError(\n \"Bilateral transformations on nested querysets are not implemented.\"\n )\n self.bilateral_transforms = bilateral_transforms\n\n def apply_bilater", "meta": {"filepath": "django/db/models/lookups.py", "language": "python", "file_size": 28513, "cut_index": 1331, "middle_length": 229}} +{"prefix": "der, track each time a Manager instance is created.\n creation_counter = 0\n\n # Set to True for the 'objects' managers that are automatically created.\n auto_created = False\n\n #: If set to True the manager will be serialized into migrations and will\n #: thus be available in e.g. RunPython operations.\n use_in_migrations = False\n\n def __new__(cls, *args, **kwargs):\n # Capture the arguments to make returning them trivial.\n obj = super().__new__(cls)\n obj._constructor_args", "suffix": " def __str__(self):\n \"\"\"Return \"app_label.model_label.manager_name\".\"\"\"\n return \"%s.%s\" % (self.model._meta.label, self.name)\n\n def __class_getitem__(cls, *args, **kwargs):\n return cls\n\n def deconstruct(self):\n \"\"\"\n ", "middle": " = (args, kwargs)\n return obj\n\n def __init__(self):\n super().__init__()\n self._set_creation_counter()\n self.model = None\n self.name = None\n self._db = None\n self._hints = {}\n\n ", "meta": {"filepath": "django/db/models/manager.py", "language": "python", "file_size": 6866, "cut_index": 716, "middle_length": 229}} +{"prefix": "nverting lookups (fk__somecol). The contents\n# describe the relation in Model terms (model Options and Fields for both\n# sides of the relation. The join_field is the field backing the relation.\nPathInfo = namedtuple(\n \"PathInfo\",\n \"from_opts to_opts target_fields join_field m2m direct filtered_relation\",\n)\n\n\ndef subclasses(cls):\n yield cls\n for subclass in cls.__subclasses__():\n yield from subclasses(subclass)\n\n\nclass Q(tree.Node):\n \"\"\"\n Encapsulate filters as objects that can then ", "suffix": "args, _connector=None, _negated=False, **kwargs):\n self._check_connector(_connector)\n super().__init__(\n children=[*args, *sorted(kwargs.items())],\n connector=_connector,\n negated=_negated,\n )\n\n @cla", "middle": "be combined logically (using\n `&` and `|`).\n \"\"\"\n\n # Connection types\n AND = \"AND\"\n OR = \"OR\"\n XOR = \"XOR\"\n default = AND\n conditional = True\n connectors = (None, AND, OR, XOR)\n\n def __init__(self, *", "meta": {"filepath": "django/db/models/query_utils.py", "language": "python", "file_size": 20366, "cut_index": 1331, "middle_length": 229}} +{"prefix": "\n\n\ndef make_model_tuple(model):\n \"\"\"\n Take a model or a string of the form \"app_label.ModelName\" and return a\n corresponding (\"app_label\", \"modelname\") tuple. If a tuple is passed in,\n assume it's a valid model tuple already and return it unchanged.\n \"\"\"\n try:\n if isinstance(model, tuple):\n model_tuple = model\n elif isinstance(model, str):\n app_label, model_name = model.split(\".\")\n model_tuple = app_label, model_name.lower()\n else:\n ", "suffix": "erence '%s'. String model references \"\n \"must be of the form 'app_label.ModelName'.\" % model\n )\n\n\ndef resolve_callables(mapping):\n \"\"\"\n Generate key/value pairs for the given mapping where the values are\n evaluated if they're cal", "middle": " model_tuple = model._meta.app_label, model._meta.model_name\n assert len(model_tuple) == 2\n return model_tuple\n except (ValueError, AssertionError):\n raise ValueError(\n \"Invalid model ref", "meta": {"filepath": "django/db/models/utils.py", "language": "python", "file_size": 2558, "cut_index": 563, "middle_length": 229}} +{"prefix": "erce an expression to a new field type.\"\"\"\n\n function = \"CAST\"\n template = \"%(function)s(%(expressions)s AS %(db_type)s)\"\n\n def __init__(self, expression, output_field):\n super().__init__(expression, output_field=output_field)\n\n def as_sql(self, compiler, connection, **extra_context):\n extra_context[\"db_type\"] = self.output_field.cast_db_type(connection)\n return super().as_sql(compiler, connection, **extra_context)\n\n def as_sqlite(self, compiler, connection, **extra_conte", "suffix": "ns)s)\"\n sql, params = super().as_sql(\n compiler, connection, template=template, **extra_context\n )\n format_string = \"%H:%M:%f\" if db_type == \"time\" else \"%Y-%m-%d %H:%M:%f\"\n params = (format_string", "middle": "xt):\n db_type = self.output_field.db_type(connection)\n if db_type in {\"datetime\", \"time\"}:\n # Use strftime as datetime/time don't keep fractional seconds.\n template = \"strftime(%%s, %(expressio", "meta": {"filepath": "django/db/models/functions/comparison.py", "language": "python", "file_size": 6848, "cut_index": 716, "middle_length": 229}} +{"prefix": "go.db.models.fields import TextField\nfrom django.db.models.fields.json import JSONField\nfrom django.db.models.functions import Cast\n\n\nclass JSONArray(Func):\n function = \"JSON_ARRAY\"\n output_field = JSONField()\n\n def as_sql(self, compiler, connection, **extra_context):\n if not connection.features.supports_json_field:\n raise NotSupportedError(\n \"JSONFields are not supported on this database backend.\"\n )\n return super().as_sql(compiler, connection, **", "suffix": "LL values in the\n # array, mapping them to JSON null values, which matches the behavior\n # of SQLite.\n null_on_null = \"NULL ON NULL\" if len(self.get_source_expressions()) > 0 else \"\"\n\n return self.as_sql(\n compiler,\n ", "middle": "extra_context)\n\n def as_native(self, compiler, connection, *, returning, **extra_context):\n # PostgreSQL 16+ and Oracle remove SQL NULL values from the array by\n # default. Adds the NULL ON NULL clause to keep NU", "meta": {"filepath": "django/db/models/functions/json.py", "language": "python", "file_size": 4668, "cut_index": 614, "middle_length": 229}} +{"prefix": "ixins import (\n FixDecimalInputMixin,\n NumericOutputFieldMixin,\n)\nfrom django.db.models.lookups import Transform\n\n\nclass Abs(Transform):\n function = \"ABS\"\n lookup_name = \"abs\"\n\n\nclass ACos(NumericOutputFieldMixin, Transform):\n function = \"ACOS\"\n lookup_name = \"acos\"\n\n\nclass ASin(NumericOutputFieldMixin, Transform):\n function = \"ASIN\"\n lookup_name = \"asin\"\n\n\nclass ATan(NumericOutputFieldMixin, Transform):\n function = \"ATAN\"\n lookup_name = \"atan\"\n\n\nclass ATan2(NumericOutputFieldM", "suffix": "n >= (5, 0, 0):\n return self.as_sql(compiler, connection)\n # This function is usually ATan2(y, x), returning the inverse tangent\n # of y / x, but it's ATan2(x, y) on SpatiaLite < 5.0.0.\n # Cast integers to float to avoid inc", "middle": "ixin, Func):\n function = \"ATAN2\"\n arity = 2\n\n def as_sqlite(self, compiler, connection, **extra_context):\n if not getattr(\n connection.ops, \"spatialite\", False\n ) or connection.ops.spatial_versio", "meta": {"filepath": "django/db/models/functions/math.py", "language": "python", "file_size": 6140, "cut_index": 716, "middle_length": 229}} +{"prefix": "\n# the test database.\nTEST_DATABASE_PREFIX = \"test_\"\n\n\nclass BaseDatabaseCreation:\n \"\"\"\n Encapsulate backend-specific differences pertaining to creation and\n destruction of the test database.\n \"\"\"\n\n # If this backend's destroy_test_db() closes the database connection, this\n # attribute must be set to the name of the connection closing method (e.g.\n # \"close\" on Oracle, \"close_pool\" on MongoDB) to avoid failures in some\n # backends tests.\n destroy_test_db_connection_close_method = ", "suffix": ":\n sys.stderr.write(msg + os.linesep)\n\n # RemovedInDjango70Warning: When the deprecation ends, replace with:\n # def create_test_db(self, verbosity=1, autoclobber=False, keepdb=False):\n def create_test_db(\n self, verbosity=1, autoclob", "middle": "None\n\n def __init__(self, connection):\n self.connection = connection\n\n def __del__(self):\n del self.connection\n\n def _nodb_cursor(self):\n return self.connection._nodb_cursor()\n\n def log(self, msg)", "meta": {"filepath": "django/db/backends/base/creation.py", "language": "python", "file_size": 17375, "cut_index": 921, "middle_length": 229}} +{"prefix": ".db.models.aggregates import * # NOQA\nfrom django.db.models.aggregates import __all__ as aggregates_all\nfrom django.db.models.constraints import * # NOQA\nfrom django.db.models.constraints import __all__ as constraints_all\nfrom django.db.models.deletion import (\n CASCADE,\n DB_CASCADE,\n DB_SET_DEFAULT,\n DB_SET_NULL,\n DO_NOTHING,\n PROTECT,\n RESTRICT,\n SET,\n SET_DEFAULT,\n SET_NULL,\n ProtectedError,\n RestrictedError,\n)\nfrom django.db.models.enums import * # NOQA\nfrom django", "suffix": " RowRange,\n Subquery,\n Value,\n ValueRange,\n When,\n Window,\n WindowFrame,\n WindowFrameExclusion,\n)\nfrom django.db.models.fetch_modes import FETCH_ONE, FETCH_PEERS, RAISE\nfrom django.db.models.fields import * # NOQA\nfrom django.db.mode", "middle": ".db.models.enums import __all__ as enums_all\nfrom django.db.models.expressions import (\n Case,\n Exists,\n Expression,\n ExpressionList,\n ExpressionWrapper,\n F,\n Func,\n JSONNull,\n OrderBy,\n OuterRef,\n ", "meta": {"filepath": "django/db/models/__init__.py", "language": "python", "file_size": 3346, "cut_index": 614, "middle_length": 229}} +{"prefix": "\n nullable=field.null,\n fail_on_restricted=False,\n )\n if field.null and not connections[using].features.can_defer_constraint_checks:\n collector.add_field_update(field, None, sub_objs)\n\n\ndef PROTECT(collector, field, sub_objs, using):\n raise ProtectedError(\n \"Cannot delete some instances of model '%s' because they are \"\n \"referenced through a protected foreign key: '%s.%s'\"\n % (\n field.remote_field.model.__name__,\n sub_objs[0].__class__", "suffix": " field.model)\n\n\ndef SET(value):\n if callable(value):\n\n def set_on_delete(collector, field, sub_objs, using):\n collector.add_field_update(field, value(), sub_objs)\n\n else:\n\n def set_on_delete(collector, field, sub_objs, using)", "middle": ".__name__,\n field.name,\n ),\n sub_objs,\n )\n\n\ndef RESTRICT(collector, field, sub_objs, using):\n collector.add_restricted_objects(field, sub_objs)\n collector.add_dependency(field.remote_field.model,", "meta": {"filepath": "django/db/models/deletion.py", "language": "python", "file_size": 22132, "cut_index": 1331, "middle_length": 229}} +{"prefix": " Index:\n suffix = \"idx\"\n # The max length of the name of the index (restricted to 30 for\n # cross-database compatibility with Oracle)\n max_name_length = 30\n\n def __init__(\n self,\n *expressions,\n fields=(),\n name=None,\n db_tablespace=None,\n opclasses=(),\n condition=None,\n include=None,\n ):\n if opclasses and not name:\n raise ValueError(\"An index must be named to use opclasses.\")\n if not isinstance(condition, (No", "suffix": "t, tuple)):\n raise ValueError(\"Index.fields must be a list or tuple.\")\n if not isinstance(opclasses, (list, tuple)):\n raise ValueError(\"Index.opclasses must be a list or tuple.\")\n if not expressions and not fields:\n ", "middle": "neType, Q)):\n raise ValueError(\"Index.condition must be a Q instance.\")\n if condition and not name:\n raise ValueError(\"An index must be named to use condition.\")\n if not isinstance(fields, (lis", "meta": {"filepath": "django/db/models/indexes.py", "language": "python", "file_size": 15578, "cut_index": 921, "middle_length": 229}} +{"prefix": "mpiler.select, klass_info,\n # and annotations.\n results = compiler.execute_sql(\n chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size\n )\n select, klass_info, annotation_col_map = (\n compiler.select,\n compiler.klass_info,\n compiler.annotation_col_map,\n )\n model_cls = klass_info[\"model\"]\n select_fields = klass_info[\"select_fields\"]\n model_fields_start, model_fields_end = select_fields[0], select_fields[", "suffix": "lated_objects = [\n (\n field,\n related_objs,\n attnames := [\n (\n field.attname\n if from_field == \"self\"\n else quer", "middle": "-1] + 1\n init_list = [\n f[0].target.attname for f in select[model_fields_start:model_fields_end]\n ]\n related_populators = get_related_populators(klass_info, select, db, fetch_mode)\n known_re", "meta": {"filepath": "django/db/models/query.py", "language": "python", "file_size": 118093, "cut_index": 3790, "middle_length": 229}} +{"prefix": "tial\n\nfrom django.db.models.utils import make_model_tuple\nfrom django.dispatch import Signal\n\nclass_prepared = Signal()\n\n\nclass ModelSignal(Signal):\n \"\"\"\n Signal subclass that allows the sender to be lazily specified as a string\n of the `app_label.ModelName` form.\n \"\"\"\n\n def _lazy_method(self, method, apps, receiver, sender, **kwargs):\n from django.db.models.options import Options\n\n # This partial takes a single optional argument named \"sender\".\n partial_method = partial(", "suffix": "ial_method(sender)\n\n def connect(self, receiver, sender=None, weak=True, dispatch_uid=None, apps=None):\n self._lazy_method(\n super().connect,\n apps,\n receiver,\n sender,\n weak=weak,\n ", "middle": "method, receiver, **kwargs)\n if isinstance(sender, str):\n apps = apps or Options.default_apps\n apps.lazy_model_operation(partial_method, make_model_tuple(sender))\n else:\n return part", "meta": {"filepath": "django/db/models/signals.py", "language": "python", "file_size": 1622, "cut_index": 537, "middle_length": 229}} +{"prefix": "imalField, FloatField, IntegerField\nfrom django.db.models.functions import Cast\n\n\nclass FixDecimalInputMixin:\n def as_postgresql(self, compiler, connection, **extra_context):\n # Cast FloatField to DecimalField as PostgreSQL doesn't support the\n # following function signatures:\n # - LOG(double, double)\n # - MOD(double, double)\n output_field = DecimalField(decimal_places=sys.float_info.dig, max_digits=1000)\n clone = self.copy()\n clone.set_source_expressions(", "suffix": "expression in self.get_source_expressions()\n ]\n )\n return clone.as_sql(compiler, connection, **extra_context)\n\n\nclass FixDurationInputMixin:\n def as_mysql(self, compiler, connection, **extra_context):\n sql, params = super", "middle": "\n [\n (\n Cast(expression, output_field)\n if isinstance(expression.output_field, FloatField)\n else expression\n )\n for ", "meta": {"filepath": "django/db/models/functions/mixins.py", "language": "python", "file_size": 2382, "cut_index": 563, "middle_length": 229}} +{"prefix": "ql_alter_column_default = \"ALTER COLUMN %(column)s SET DEFAULT %(default)s\"\n sql_alter_column_no_default = \"ALTER COLUMN %(column)s DROP DEFAULT\"\n sql_alter_column_no_default_null = sql_alter_column_no_default\n sql_delete_column = \"ALTER TABLE %(table)s DROP COLUMN %(column)s\"\n sql_rename_column = (\n \"ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s\"\n )\n sql_update_with_default = (\n \"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL\"\n ", "suffix": "(name)s %(constraint)s\"\n sql_pk_constraint = \"PRIMARY KEY (%(columns)s)\"\n\n sql_create_check = \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)\"\n sql_delete_check = sql_delete_constraint\n\n sql_create_unique = (\n \"ALTER TAB", "middle": " )\n\n sql_unique_constraint = \"UNIQUE (%(columns)s)%(deferrable)s\"\n sql_check_constraint = \"CHECK (%(check)s)\"\n sql_delete_constraint = \"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s\"\n sql_constraint = \"CONSTRAINT %", "meta": {"filepath": "django/db/backends/base/schema.py", "language": "python", "file_size": 83683, "cut_index": 3790, "middle_length": 229}} +{"prefix": "ombine(other, self.BITLEFTSHIFT, False)\n\n def bitrightshift(self, other):\n return self._combine(other, self.BITRIGHTSHIFT, False)\n\n def __xor__(self, other):\n if getattr(self, \"conditional\", False) and getattr(other, \"conditional\", False):\n return Q(self) ^ Q(other)\n raise NotImplementedError(\n \"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations.\"\n )\n\n def bitxor(self, other):\n return self._combine(other, self.BITXOR, False", "suffix": "), and .bitxor() for bitwise logical operations.\"\n )\n\n def bitor(self, other):\n return self._combine(other, self.BITOR, False)\n\n def __radd__(self, other):\n return self._combine(other, self.ADD, True)\n\n def __rsub__(self, othe", "middle": ")\n\n def __or__(self, other):\n if getattr(self, \"conditional\", False) and getattr(other, \"conditional\", False):\n return Q(self) | Q(other)\n raise NotImplementedError(\n \"Use .bitand(), .bitor(", "meta": {"filepath": "django/db/models/expressions.py", "language": "python", "file_size": 77894, "cut_index": 3790, "middle_length": 229}} +{"prefix": "eatest, Least, NullIf\nfrom .datetime import (\n Extract,\n ExtractDay,\n ExtractHour,\n ExtractIsoWeekDay,\n ExtractIsoYear,\n ExtractMinute,\n ExtractMonth,\n ExtractQuarter,\n ExtractSecond,\n ExtractWeek,\n ExtractWeekDay,\n ExtractYear,\n Now,\n Trunc,\n TruncDate,\n TruncDay,\n TruncHour,\n TruncMinute,\n TruncMonth,\n TruncQuarter,\n TruncSecond,\n TruncTime,\n TruncWeek,\n TruncYear,\n)\nfrom .json import JSONArray, JSONObject\nfrom .math import (\n Abs,", "suffix": ".text import (\n MD5,\n SHA1,\n SHA224,\n SHA256,\n SHA384,\n SHA512,\n Chr,\n Concat,\n ConcatPair,\n Left,\n Length,\n Lower,\n LPad,\n LTrim,\n Ord,\n Repeat,\n Replace,\n Reverse,\n Right,\n RPad,\n RTrim,\n ", "middle": "\n ACos,\n ASin,\n ATan,\n ATan2,\n Ceil,\n Cos,\n Cot,\n Degrees,\n Exp,\n Floor,\n Ln,\n Log,\n Mod,\n Pi,\n Power,\n Radians,\n Random,\n Round,\n Sign,\n Sin,\n Sqrt,\n Tan,\n)\nfrom ", "meta": {"filepath": "django/db/models/functions/__init__.py", "language": "python", "file_size": 2782, "cut_index": 563, "middle_length": 229}} +{"prefix": "ne\n\n def get_tzname(self):\n # Timezone conversions must happen to the input datetime *before*\n # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the\n # database as 2016-01-01 01:00:00 +00:00. Any results should be\n # based on the input datetime not the stored datetime.\n tzname = None\n if settings.USE_TZ:\n if self.tzinfo is None:\n tzname = timezone.get_current_timezone_name()\n else:\n tzname = timezon", "suffix": "a):\n if self.lookup_name is None:\n self.lookup_name = lookup_name\n if self.lookup_name is None:\n raise ValueError(\"lookup_name must be provided\")\n self.tzinfo = tzinfo\n super().__init__(expression, **extra)", "middle": "e._get_timezone_name(self.tzinfo)\n return tzname\n\n\nclass Extract(TimezoneMixin, Transform):\n lookup_name = None\n output_field = IntegerField()\n\n def __init__(self, expression, lookup_name=None, tzinfo=None, **extr", "meta": {"filepath": "django/db/models/functions/datetime.py", "language": "python", "file_size": 12835, "cut_index": 921, "middle_length": 229}} +{"prefix": "ther a tuple of tuples, or a single\n tuple of two strings. Normalize it to a tuple of tuples, so that\n calling code can uniformly expect that.\n \"\"\"\n try:\n if not option_together:\n return ()\n if not isinstance(option_together, (tuple, list)):\n raise TypeError\n first_element = option_together[0]\n if not isinstance(first_element, (tuple, list)):\n option_together = (option_together,)\n # Normalize everything to tuples\n return ", "suffix": "ther\n\n\ndef make_immutable_fields_list(name, data):\n return ImmutableList(data, warning=IMMUTABLE_WARNING % name)\n\n\nclass Options:\n FORWARD_PROPERTIES = {\n \"fields\",\n \"many_to_many\",\n \"concrete_fields\",\n \"local_concrete_fie", "middle": "tuple(tuple(ot) for ot in option_together)\n except TypeError:\n # If the value of option_together isn't valid, return it\n # verbatim; this will be picked up by the check framework later.\n return option_toge", "meta": {"filepath": "django/db/models/options.py", "language": "python", "file_size": 39672, "cut_index": 2151, "middle_length": 229}} +{"prefix": "iolation_error_message = _(\"Constraint “%(name)s” is violated.\")\n violation_error_code = None\n violation_error_message = None\n\n non_db_attrs = (\"violation_error_code\", \"violation_error_message\")\n\n def __init__(\n self, *, name, violation_error_code=None, violation_error_message=None\n ):\n self.name = name\n if violation_error_code is not None:\n self.violation_error_code = violation_error_code\n if violation_error_message is not None:\n self.violati", "suffix": "sql(self, model, schema_editor):\n raise NotImplementedError(\"This method must be implemented by a subclass.\")\n\n def create_sql(self, model, schema_editor):\n raise NotImplementedError(\"This method must be implemented by a subclass.\")\n\n d", "middle": "on_error_message = violation_error_message\n else:\n self.violation_error_message = self.default_violation_error_message\n\n @property\n def contains_expressions(self):\n return False\n\n def constraint_", "meta": {"filepath": "django/db/models/constraints.py", "language": "python", "file_size": 28470, "cut_index": 1331, "middle_length": 229}} +{"prefix": " return mark_safe(output)\n else:\n return output\n\n\nclass CommentNode(Node):\n child_nodelists = ()\n\n def render(self, context):\n return \"\"\n\n\nclass CsrfTokenNode(Node):\n child_nodelists = ()\n\n def render(self, context):\n csrf_token = context.get(\"csrf_token\")\n if csrf_token:\n if csrf_token == \"NOTPROVIDED\":\n return format_html(\"\")\n else:\n return format_html(\n '',\n csrf_token,\n )\n else:\n # It's very probable that the token is missing because of\n # misconfiguration, so we raise a warning\n ", "meta": {"filepath": "django/template/defaulttags.py", "language": "python", "file_size": 55083, "cut_index": 2151, "middle_length": 229}} +{"prefix": "_keys)\n\n\nclass RelatedField(FieldCacheMixin, Field):\n \"\"\"Base class that all relational fields inherit from.\"\"\"\n\n # Field flags\n one_to_many = False\n one_to_one = False\n many_to_many = False\n many_to_one = False\n\n def __init__(\n self,\n related_name=None,\n related_query_name=None,\n limit_choices_to=None,\n **kwargs,\n ):\n self._related_name = related_name\n self._related_query_name = related_query_name\n self._limit_choices_to = limi", "suffix": "field.model\n\n def check(self, **kwargs):\n return [\n *super().check(**kwargs),\n *self._check_related_name_is_valid(),\n *self._check_related_query_name_is_valid(),\n *self._check_relation_model_exists(),\n ", "middle": "t_choices_to\n super().__init__(**kwargs)\n\n @cached_property\n def related_model(self):\n # Can't cache this property until all the models are loaded.\n apps.check_models_ready()\n return self.remote_", "meta": {"filepath": "django/db/models/fields/related.py", "language": "python", "file_size": 83508, "cut_index": 3790, "middle_length": 229}} +{"prefix": "_aliases=with_col_aliases)\n order_by = self.get_order_by()\n self.where, self.having, self.qualify = self.query.where.split_having_qualify(\n must_group_by=self.query.group_by is not None\n )\n extra_select = self.get_extra_select(order_by, self.select)\n self.has_extra_select = bool(extra_select)\n group_by = self.get_group_by(self.select + extra_select, order_by)\n return extra_select, order_by, group_by\n\n def get_group_by(self, select, order_by):\n ", "suffix": "orrect\".\n \"\"\"\n # Some examples:\n # SomeModel.objects.annotate(Count('somecol'))\n # GROUP BY: all fields of the model\n #\n # SomeModel.objects.values('name').annotate(Count('somecol'))\n # GROUP B", "middle": " \"\"\"\n Return a list of 2-tuples of form (sql, params).\n\n The logic of what exactly the GROUP BY clause contains is hard\n to describe in other words than \"if it passes the test suite,\n then it is c", "meta": {"filepath": "django/db/models/sql/compiler.py", "language": "python", "file_size": 96049, "cut_index": 3790, "middle_length": 229}} +{"prefix": "xpression\"):\n yield from get_paths_from_expression(rhs)\n elif hasattr(child, \"resolve_expression\"):\n yield from get_paths_from_expression(child)\n\n\ndef get_child_with_renamed_prefix(prefix, replacement, child):\n from django.db.models.query import QuerySet\n\n if isinstance(child, Node):\n return rename_prefix_from_q(prefix, replacement, child)\n if isinstance(child, tuple):\n lhs, rhs = child\n if lhs.startswith(prefix + LOOKUP_SEP):\n lhs = ", "suffix": "ild, F):\n child = child.copy()\n if child.name.startswith(prefix + LOOKUP_SEP):\n child.name = child.name.replace(prefix, replacement, 1)\n elif isinstance(child, QuerySet):\n # QuerySet may contain OuterRef() references whic", "middle": "lhs.replace(prefix, replacement, 1)\n if not isinstance(rhs, F) and hasattr(rhs, \"resolve_expression\"):\n rhs = get_child_with_renamed_prefix(prefix, replacement, rhs)\n return lhs, rhs\n\n if isinstance(ch", "meta": {"filepath": "django/db/models/sql/query.py", "language": "python", "file_size": 123905, "cut_index": 3790, "middle_length": 229}} +{"prefix": "\n\n# Connection types\nAND = \"AND\"\nOR = \"OR\"\nXOR = \"XOR\"\n\n\nclass WhereNode(tree.Node):\n \"\"\"\n An SQL WHERE clause.\n\n The class is tied to the Query class that created it (in order to create\n the correct SQL).\n\n A child is usually an expression producing boolean values. Most likely the\n expression is a Lookup instance.\n\n However, a child could also be any class with as_sql() and either\n relabeled_clone() method or relabel_aliases() and clone() methods and\n contains_aggregate attribute", "suffix": "hat\n should be included in the WHERE clause, one for those parts of self\n that must be included in the HAVING clause, and one for those parts\n that refer to window functions.\n \"\"\"\n if not self.contains_aggregate and not s", "middle": ".\n \"\"\"\n\n default = AND\n resolved = False\n conditional = True\n\n def split_having_qualify(self, negated=False, must_group_by=False):\n \"\"\"\n Return three possibly None nodes: one for those parts of self t", "meta": {"filepath": "django/db/models/sql/where.py", "language": "python", "file_size": 12317, "cut_index": 921, "middle_length": 229}} +{"prefix": "Exact,\n TupleGreaterThan,\n TupleGreaterThanOrEqual,\n TupleIn,\n TupleIsNull,\n TupleLessThan,\n TupleLessThanOrEqual,\n)\nfrom django.utils.functional import cached_property\n\n\nclass AttributeSetter:\n def __init__(self, name, value):\n setattr(self, name, value)\n\n\nclass CompositeAttribute:\n def __init__(self, field):\n self.field = field\n\n @property\n def attnames(self):\n return [field.attname for field in self.field.fields]\n\n def __get__(self, instance, cls=None", "suffix": "lues = (None,) * length\n\n if not isinstance(values, (list, tuple)):\n raise ValueError(f\"{self.field.name!r} must be a list or a tuple.\")\n if length != len(values):\n raise ValueError(f\"{self.field.name!r} must have {lengt", "middle": "):\n return tuple(getattr(instance, attname) for attname in self.attnames)\n\n def __set__(self, instance, values):\n attnames = self.attnames\n length = len(attnames)\n\n if values is None:\n va", "meta": {"filepath": "django/db/models/fields/composite.py", "language": "python", "file_size": 5731, "cut_index": 716, "middle_length": 229}} +{"prefix": "l__ = [\"GeneratedField\"]\n\n\nclass GeneratedField(Field):\n generated = True\n db_returning = True\n\n _query = None\n output_field = None\n\n def __init__(self, *, expression, output_field, db_persist, **kwargs):\n if kwargs.setdefault(\"editable\", False):\n raise ValueError(\"GeneratedField cannot be editable.\")\n if not kwargs.setdefault(\"blank\", True):\n raise ValueError(\"GeneratedField must be blank.\")\n if kwargs.get(\"default\", NOT_PROVIDED) is not NOT_PROVIDE", "suffix": " if db_persist not in (True, False):\n raise ValueError(\"GeneratedField.db_persist must be True or False.\")\n\n self.expression = expression\n self.output_field = output_field\n self.db_persist = db_persist\n self.has_null", "middle": "D:\n raise ValueError(\"GeneratedField cannot have a default.\")\n if kwargs.get(\"db_default\", NOT_PROVIDED) is not NOT_PROVIDED:\n raise ValueError(\"GeneratedField cannot have a database default.\")\n ", "meta": {"filepath": "django/db/models/fields/generated.py", "language": "python", "file_size": 8461, "cut_index": 716, "middle_length": 229}} +{"prefix": "\"Value must be valid JSON.\"),\n }\n _default_hint = (\"dict\", \"{}\")\n\n def __init__(\n self,\n verbose_name=None,\n name=None,\n encoder=None,\n decoder=None,\n **kwargs,\n ):\n if encoder and not callable(encoder):\n raise ValueError(\"The encoder parameter must be a callable object.\")\n if decoder and not callable(decoder):\n raise ValueError(\"The decoder parameter must be a callable object.\")\n self.encoder = encoder\n ", "suffix": "check_supported(databases))\n return errors\n\n def _check_supported(self, databases):\n errors = []\n for db in databases:\n if not router.allow_migrate_model(db, self.model):\n continue\n connection = ", "middle": "self.decoder = decoder\n super().__init__(verbose_name, name, **kwargs)\n\n def check(self, **kwargs):\n errors = super().check(**kwargs)\n databases = kwargs.get(\"databases\") or []\n errors.extend(self._", "meta": {"filepath": "django/db/models/fields/json.py", "language": "python", "file_size": 27921, "cut_index": 1331, "middle_length": 229}} +{"prefix": "django.db.models.fields import FloatField, IntegerField\n\n__all__ = [\n \"CumeDist\",\n \"DenseRank\",\n \"FirstValue\",\n \"Lag\",\n \"LastValue\",\n \"Lead\",\n \"NthValue\",\n \"Ntile\",\n \"PercentRank\",\n \"Rank\",\n \"RowNumber\",\n]\n\n\nclass CumeDist(Func):\n function = \"CUME_DIST\"\n output_field = FloatField()\n window_compatible = True\n\n\nclass DenseRank(Func):\n function = \"DENSE_RANK\"\n output_field = IntegerField()\n window_compatible = True\n\n\nclass FirstValue(Func):\n arity = 1\n f", "suffix": "se ValueError(\n \"%s requires a non-null source expression.\" % self.__class__.__name__\n )\n if offset is None or offset <= 0:\n raise ValueError(\n \"%s requires a positive integer for the offset.\"\n ", "middle": "unction = \"FIRST_VALUE\"\n window_compatible = True\n\n\nclass LagLeadFunction(Func):\n window_compatible = True\n\n def __init__(self, expression, offset=1, default=None, **extra):\n if expression is None:\n rai", "meta": {"filepath": "django/db/models/functions/window.py", "language": "python", "file_size": 2841, "cut_index": 563, "middle_length": 229}} +{"prefix": "ER\n\n\nclass MultiJoin(Exception):\n \"\"\"\n Used by join construction code to indicate the point at which a\n multi-valued join was attempted (if the caller wants to treat that\n exceptionally).\n \"\"\"\n\n def __init__(self, names_pos, path_with_names):\n self.level = names_pos\n # The path travelled, this includes the path to the multijoin.\n self.names_with_path = path_with_names\n\n\nclass Empty:\n pass\n\n\nclass Join:\n \"\"\"\n Used by sql.Query and sql.SQLCompiler to generate JO", "suffix": "All entries in alias_map\n must be Join compatible by providing the following attributes and methods:\n - table_name (string)\n - table_alias (possible alias for the table, can be None)\n - join_type (can be None for those entries that ", "middle": "IN clauses into the\n FROM entry. For example, the SQL generated could be\n LEFT OUTER JOIN \"sometable\" T1\n ON (\"othertable\".\"sometable_id\" = \"sometable\".\"id\")\n\n This class is primarily used in Query.alias_map. ", "meta": {"filepath": "django/db/models/sql/datastructures.py", "language": "python", "file_size": 7280, "cut_index": 716, "middle_length": 229}} +{"prefix": "se\n# attname. For example, this gets the primary key value of object \"obj\":\n#\n# getattr(obj, opts.pk.attname)\n\n\ndef _empty(of_cls):\n new = Empty()\n new.__class__ = of_cls\n return new\n\n\ndef return_None():\n return None\n\n\n@total_ordering\nclass Field(RegisterLookupMixin):\n \"\"\"Base class for all field types\"\"\"\n\n # Designates whether empty strings fundamentally are allowed at the\n # database level.\n empty_strings_allowed = True\n empty_values = list(validators.EMPTY_VALUES)\n\n # Th", "suffix": "counter = 0\n auto_creation_counter = -1\n default_validators = [] # Default set of validators\n default_error_messages = {\n \"invalid_choice\": _(\"Value %(value)r is not a valid choice.\"),\n \"null\": _(\"This field cannot be null.\"),\n ", "middle": "ese track each time a Field instance is created. Used to retain order.\n # The auto_creation_counter is used for fields that Django implicitly\n # creates, creation_counter is used for all user-specified fields.\n creation_", "meta": {"filepath": "django/db/models/fields/__init__.py", "language": "python", "file_size": 103134, "cut_index": 3790, "middle_length": 229}} +{"prefix": "odels.fields import UUIDField\n\n\nclass UUID4(Func):\n function = \"UUIDV4\"\n arity = 0\n output_field = UUIDField()\n\n def as_sql(self, compiler, connection, **extra_context):\n if connection.features.supports_uuid4_function:\n return super().as_sql(compiler, connection, **extra_context)\n raise NotSupportedError(\"UUID4 is not supported on this database backend.\")\n\n def as_postgresql(self, compiler, connection, **extra_context):\n if connection.features.is_postgresql_18:", "suffix": "on, **extra_context):\n if not connection.features.supports_uuid4_function:\n if connection.mysql_is_mariadb:\n raise NotSupportedError(\"UUID4 requires MariaDB version 11.7 or later.\")\n raise NotSupportedError(\"UUID", "middle": "\n return self.as_sql(compiler, connection, **extra_context)\n return self.as_sql(\n compiler, connection, function=\"GEN_RANDOM_UUID\", **extra_context\n )\n\n def as_mysql(self, compiler, connecti", "meta": {"filepath": "django/db/models/functions/uuid.py", "language": "python", "file_size": 3593, "cut_index": 614, "middle_length": 229}} +{"prefix": "SIZE,\n NO_RESULTS,\n ROW_COUNT,\n)\nfrom django.db.models.sql.query import Query\n\n__all__ = [\"DeleteQuery\", \"UpdateQuery\", \"InsertQuery\", \"AggregateQuery\"]\n\n\nclass DeleteQuery(Query):\n \"\"\"A DELETE SQL query.\"\"\"\n\n compiler = \"SQLDeleteCompiler\"\n\n def do_query(self, table, where, using):\n self.alias_map = {table: self.alias_map[table]}\n self.where = where\n return self.get_compiler(using).execute_sql(ROW_COUNT)\n\n def delete_batch(self, pk_list, using):\n \"\"\"\n Se", "suffix": "leted = 0\n field = self.get_meta().pk\n for offset in range(0, len(pk_list), GET_ITERATOR_CHUNK_SIZE):\n self.clear_where()\n self.add_filter(\n f\"{field.attname}__in\",\n pk_list[offset : offset ", "middle": "t up and execute delete queries for all the objects in pk_list.\n\n More than one physical query may be executed if there are a\n lot of values in pk_list.\n \"\"\"\n # number of objects deleted\n num_de", "meta": {"filepath": "django/db/models/sql/subqueries.py", "language": "python", "file_size": 5993, "cut_index": 716, "middle_length": 229}} +{"prefix": "hecks\nfrom django.utils.functional import cached_property\n\nNOT_PROVIDED = object()\n\n\nclass FieldCacheMixin:\n \"\"\"\n An API for working with the model's fields value cache.\n\n Subclasses must set self.cache_name to a unique entry for the cache -\n typically the field’s name.\n \"\"\"\n\n @cached_property\n def cache_name(self):\n raise NotImplementedError\n\n def get_cached_value(self, instance, default=NOT_PROVIDED):\n try:\n return instance._state.fields_cache[self.cache_na", "suffix": "_cached_value(self, instance, value):\n instance._state.fields_cache[self.cache_name] = value\n\n def delete_cached_value(self, instance):\n del instance._state.fields_cache[self.cache_name]\n\n\nclass CheckFieldDefaultMixin:\n _default_hint = ", "middle": "me]\n except KeyError:\n if default is NOT_PROVIDED:\n raise\n return default\n\n def is_cached(self, instance):\n return self.cache_name in instance._state.fields_cache\n\n def set", "meta": {"filepath": "django/db/models/fields/mixins.py", "language": "python", "file_size": 1947, "cut_index": 537, "middle_length": 229}} +{"prefix": "eld = field\n self.storage = field.storage\n self._committed = True\n\n def __eq__(self, other):\n # Older code may be expecting FileField values to be simple strings.\n # By overriding the == operator, it can remain backwards compatibility.\n if hasattr(other, \"name\"):\n return self.name == other.name\n return self.name == other\n\n def __hash__(self):\n return hash(self.name)\n\n def __bool__(self):\n return bool(self.name)\n\n # The standard F", "suffix": " \"The '%s' attribute has no file associated with it.\" % self.field.name\n )\n\n def _get_file(self):\n self._require_file()\n if getattr(self, \"_file\", None) is None:\n self._file = self.storage.open(self.nam", "middle": "ile contains most of the necessary properties, but\n # FieldFiles can be instantiated without a name, so that needs to\n # be checked for here.\n\n def _require_file(self):\n if not self:\n raise ValueError(\n", "meta": {"filepath": "django/db/models/fields/files.py", "language": "python", "file_size": 20242, "cut_index": 1331, "middle_length": 229}} +{"prefix": "urlsplit\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.urls import re_path\nfrom django.views.static import serve\n\n\ndef static(prefix, view=serve, **kwargs):\n \"\"\"\n Return a URL pattern for serving files in debug mode.\n\n from django.conf import settings\n from django.conf.urls.static import static\n\n urlpatterns = [\n # ... the rest of your URLconf goes here ...\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n ", "suffix": "gured(\"Empty static prefix not permitted\")\n elif not settings.DEBUG or urlsplit(prefix).netloc:\n # No-op if not in debug mode or a non-local prefix.\n return []\n return [\n re_path(\n r\"^%s(?P.*)$\" % re.escape(prefi", "middle": "\"\"\"\n if not prefix:\n raise ImproperlyConfi", "meta": {"filepath": "django/conf/urls/static.py", "language": "python", "file_size": 908, "cut_index": 547, "middle_length": 52}} +{"prefix": "ated_objects\nfrom django.db.models.query_utils import DeferredAttribute\nfrom django.db.models.utils import AltersData, resolve_callables\nfrom django.utils.functional import cached_property\n\n\nclass ForeignKeyDeferredAttribute(DeferredAttribute):\n def __set__(self, instance, value):\n if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(\n instance\n ):\n self.field.delete_cached_value(instance)\n instance.__dict__[self.field.attname] = value\n", "suffix": "tures.supports_over_clause:\n raise NotSupportedError(\n \"Prefetching from a limited queryset is only supported on backends \"\n \"that support window functions.\"\n )\n low_mark, high_mark = queryset.quer", "middle": "\n\ndef _filter_prefetch_queryset(queryset, field_name, instances):\n predicate = Q(**{f\"{field_name}__in\": instances})\n db = queryset._db or DEFAULT_DB_ALIAS\n if queryset.query.is_sliced:\n if not connections[db].fea", "meta": {"filepath": "django/db/models/fields/related_descriptors.py", "language": "python", "file_size": 69743, "cut_index": 3790, "middle_length": 229}} +{"prefix": "om django.utils.functional import cached_property\nfrom django.utils.hashable import make_hashable\n\nfrom ..utils import get_blank_choice_label\nfrom .mixins import FieldCacheMixin\n\n\nclass ForeignObjectRel(FieldCacheMixin):\n \"\"\"\n Used by ForeignObject to store information about the relation.\n\n ``_meta.get_fields()`` returns this class to provide access to the field\n flags for the reverse relation.\n \"\"\"\n\n # Field flags\n auto_created = True\n concrete = False\n editable = False\n is_re", "suffix": "lf,\n field,\n to,\n related_name=None,\n related_query_name=None,\n limit_choices_to=None,\n parent_link=False,\n on_delete=None,\n ):\n self.field = field\n self.model = to\n self.related_name", "middle": "lation = True\n\n # Reverse relations are always nullable (Django can't enforce that a\n # foreign key on the related model points to this model).\n null = True\n empty_strings_allowed = False\n\n def __init__(\n se", "meta": {"filepath": "django/db/models/fields/reverse_related.py", "language": "python", "file_size": 12624, "cut_index": 921, "middle_length": 229}} +{"prefix": " self.deep_deconstruct(obj.keywords),\n )\n elif isinstance(obj, COMPILED_REGEX_TYPE):\n return RegexObject(obj)\n elif isinstance(obj, type):\n # If this is a type that implements 'deconstruct' as an instance\n # method, avoid treating this as being deconstructible itself - see\n # #22951\n return obj\n elif hasattr(obj, \"deconstruct\"):\n deconstructed = obj.deconstruct()\n if isinstance(obj, models.Field", "suffix": "_deconstruct(value) for value in args],\n {key: self.deep_deconstruct(value) for key, value in kwargs.items()},\n )\n else:\n return obj\n\n def only_relation_agnostic_fields(self, fields):\n \"\"\"\n Retur", "middle": "):\n # we have a field which also returns a name\n deconstructed = deconstructed[1:]\n path, args, kwargs = deconstructed\n return (\n path,\n [self.deep", "meta": {"filepath": "django/db/migrations/autodetector.py", "language": "python", "file_size": 90088, "cut_index": 3790, "middle_length": 229}} +{"prefix": "jango.db import DatabaseError\n\n\nclass AmbiguityError(Exception):\n \"\"\"More than one migration matches a name prefix.\"\"\"\n\n pass\n\n\nclass BadMigrationError(Exception):\n \"\"\"There's a bad migration (unreadable/bad format/etc.).\"\"\"\n\n pass\n\n\nclass CircularDependencyError(Exception):\n \"\"\"There's an impossible-to-resolve circular dependency.\"\"\"\n\n pass\n\n\nclass InconsistentMigrationHistory(Exception):\n \"\"\"An applied migration has some of its dependencies not applied.\"\"\"\n\n pass\n\n\nclass InvalidBas", "suffix": "ror):\n \"\"\"An attempt on a node is made that is not available in the graph.\"\"\"\n\n def __init__(self, message, node, origin=None):\n self.message = message\n self.origin = origin\n self.node = node\n\n def __str__(self):\n retur", "middle": "esError(ValueError):\n \"\"\"A model's base classes can't be resolved.\"\"\"\n\n pass\n\n\nclass IrreversibleError(RuntimeError):\n \"\"\"An irreversible migration is about to be reversed.\"\"\"\n\n pass\n\n\nclass NodeNotFoundError(LookupEr", "meta": {"filepath": "django/db/migrations/exceptions.py", "language": "python", "file_size": 1204, "cut_index": 518, "middle_length": 229}} +{"prefix": "= key\n self.children = set()\n self.parents = set()\n\n def __eq__(self, other):\n return self.key == other\n\n def __lt__(self, other):\n return self.key < other\n\n def __hash__(self):\n return hash(self.key)\n\n def __getitem__(self, item):\n return self.key[item]\n\n def __str__(self):\n return str(self.key)\n\n def __repr__(self):\n return \"<%s: (%r, %r)>\" % (self.__class__.__name__, self.key[0], self.key[1])\n\n def add_child(self, child):\n ", "suffix": "moved, for example.)\n\n After the migration graph is processed, all dummy nodes should be removed.\n If there are any left, a nonexistent dependency error is raised.\n \"\"\"\n\n def __init__(self, key, origin, error_message):\n super().__init__(", "middle": " self.children.add(child)\n\n def add_parent(self, parent):\n self.parents.add(parent)\n\n\nclass DummyNode(Node):\n \"\"\"\n A node that doesn't correspond to a migration file on disk.\n (A squashed migration that was re", "meta": {"filepath": "django/db/migrations/graph.py", "language": "python", "file_size": 13149, "cut_index": 921, "middle_length": 229}} +{"prefix": "ations\n and you are returned a list of equal or shorter length - operations\n are merged into one if possible.\n\n For example, a CreateModel and an AddField can be optimized into a\n new CreateModel, and CreateModel and DeleteModel can be optimized into\n nothing.\n \"\"\"\n\n def optimize(self, operations, app_label):\n \"\"\"\n Main optimization entry point. Pass in a list of Operation instances,\n get out a new list of Operation instances.\n\n Unfortunately, due to the scop", "suffix": "stead, the optimizer looks at each\n individual operation and scans forwards in the list to see if there\n are any matches, stopping at boundaries - operations which can't\n be optimized over (RunSQL, operations on the same field/model, e", "middle": "e of the optimization (two combinable\n operations might be separated by several hundred others), this can't be\n done as a peephole optimization with checks/output implemented on\n the Operations themselves; in", "meta": {"filepath": "django/db/migrations/optimizer.py", "language": "python", "file_size": 3255, "cut_index": 614, "middle_length": 229}} +{"prefix": "nctional import classproperty\nfrom django.utils.timezone import now\n\nfrom .exceptions import MigrationSchemaMissing\n\n\nclass MigrationRecorder:\n \"\"\"\n Deal with storing migration records in the database.\n\n Because this table is actually itself used for dealing with model\n creation, it's the one thing we can't do normally via migrations.\n We manually handle table creation/schema updating (using schema backend)\n and then have a floating model to do queries with.\n\n If a migration is unapplie", "suffix": "gistryNotReady if installed apps import\n MigrationRecorder.\n \"\"\"\n if cls._migration_class is None:\n\n class Migration(models.Model):\n app = models.CharField(max_length=255)\n name = models.CharFie", "middle": "d its row is removed from the table. Having\n a row in the table always means a migration is applied.\n \"\"\"\n\n _migration_class = None\n\n @classproperty\n def Migration(cls):\n \"\"\"\n Lazy load to avoid AppRe", "meta": {"filepath": "django/db/migrations/recorder.py", "language": "python", "file_size": 3827, "cut_index": 614, "middle_length": 229}} +{"prefix": " and not isinstance(f.related_model, str)\n ):\n related_fields_models.add(f.model)\n related_models.append(f.related_model)\n # Reverse accessors of foreign keys to proxy models are attached to their\n # concrete proxied model.\n opts = m._meta\n if opts.proxy and m in related_fields_models:\n related_models.append(opts.concrete_model)\n return related_models\n\n\ndef get_related_models_tuples(model):\n \"\"\"\n Return a list of typical (app_label, model_name) tupl", "suffix": ":\n \"\"\"\n Return all models that have a direct or indirect relationship\n to the given model.\n\n Relationships are either defined by explicit relational fields, like\n ForeignKey, ManyToManyField or OneToOneField, or by inheriting from another\n ", "middle": "es for all related\n models for the given model.\n \"\"\"\n return {\n (rel_mod._meta.app_label, rel_mod._meta.model_name)\n for rel_mod in _get_related_models(model)\n }\n\n\ndef get_related_models_recursive(model)", "meta": {"filepath": "django/db/migrations/state.py", "language": "python", "file_size": 42119, "cut_index": 2151, "middle_length": 229}} +{"prefix": "django.utils.inspect import get_func_args\nfrom django.utils.module_loading import module_dir\nfrom django.utils.timezone import now\n\n\nclass OperationWriter:\n def __init__(self, operation, indentation=2):\n self.operation = operation\n self.buff = []\n self.indentation = indentation\n\n def serialize(self):\n def _write(_arg_name, _arg_value):\n if _arg_name in self.operation.serialization_expand_args and isinstance(\n _arg_value, (list, tuple, dict)\n ", "suffix": "ring, key_imports = MigrationWriter.serialize(key)\n arg_string, arg_imports = MigrationWriter.serialize(value)\n args = arg_string.splitlines()\n if len(args) > 1:\n ", "middle": " ):\n if isinstance(_arg_value, dict):\n self.feed(\"%s={\" % _arg_name)\n self.indent()\n for key, value in _arg_value.items():\n key_st", "meta": {"filepath": "django/db/migrations/writer.py", "language": "python", "file_size": 11933, "cut_index": 921, "middle_length": 229}} +{"prefix": "from .fields import AddField, AlterField, RemoveField, RenameField\nfrom .models import (\n AddConstraint,\n AddIndex,\n AlterConstraint,\n AlterIndexTogether,\n AlterModelManagers,\n AlterModelOptions,\n AlterModelTable,\n AlterModelTableComment,\n AlterOrderWithRespectTo,\n AlterUniqueTogether,\n CreateModel,\n DeleteModel,\n RemoveConstraint,\n RemoveIndex,\n RenameIndex,\n RenameModel,\n)\nfrom .special import RunPython, RunSQL, SeparateDatabaseAndState\n\n__all__ = [\n \"Cre", "suffix": "ex\",\n \"AddField\",\n \"RemoveField\",\n \"AlterField\",\n \"RenameField\",\n \"AddConstraint\",\n \"RemoveConstraint\",\n \"AlterConstraint\",\n \"SeparateDatabaseAndState\",\n \"RunSQL\",\n \"RunPython\",\n \"AlterOrderWithRespectTo\",\n \"AlterModelMa", "middle": "ateModel\",\n \"DeleteModel\",\n \"AlterModelTable\",\n \"AlterModelTableComment\",\n \"AlterUniqueTogether\",\n \"RenameModel\",\n \"AlterIndexTogether\",\n \"AlterModelOptions\",\n \"AddIndex\",\n \"RemoveIndex\",\n \"RenameInd", "meta": {"filepath": "django/db/migrations/operations/__init__.py", "language": "python", "file_size": 1008, "cut_index": 512, "middle_length": 229}} +{"prefix": "ns or {}\n self.bases = bases or (models.Model,)\n self.managers = managers or []\n super().__init__(name)\n # Sanity-check that there are no duplicated field names, bases, or\n # manager names\n _check_for_duplicates(\"fields\", (name for name, _ in self.fields))\n _check_for_duplicates(\n \"bases\",\n (\n (\n base._meta.label_lower\n if hasattr(base, \"_meta\")\n else base.lower() if", "suffix": " kwargs = {\n \"name\": self.name,\n \"fields\": self.fields,\n }\n if self.options:\n kwargs[\"options\"] = self.options\n if self.bases and self.bases != (models.Model,):\n kwargs[\"bases\"] = self.bases\n", "middle": " isinstance(base, str) else base\n )\n for base in self.bases\n ),\n )\n _check_for_duplicates(\"managers\", (name for name, _ in self.managers))\n\n def deconstruct(self):\n ", "meta": {"filepath": "django/db/migrations/operations/models.py", "language": "python", "file_size": 45901, "cut_index": 2151, "middle_length": 229}} +{"prefix": "templates.\n\nThe django.template namespace contains two independent subsystems:\n\n1. Multiple Template Engines: support for pluggable template backends,\n built-in backends and backend-independent APIs\n2. Django Template Language: Django's own template engine, including its\n built-in loaders, context processors, tags and filters.\n\nIdeally these subsystems would be implemented in distinct packages. However\nkeeping them together made the implementation of Multiple Template Engines\nless disruptive .\n\nHere's a", "suffix": "late.context\n- django.template.context_processors\n- django.template.loaders.*\n- django.template.debug\n- django.template.defaultfilters\n- django.template.defaulttags\n- django.template.engine\n- django.template.loader_tags\n- django.template.smartif\n\nShared:\n\n", "middle": " breakdown of which modules belong to which subsystem.\n\nMultiple Template Engines:\n\n- django.template.backends.*\n- django.template.loader\n- django.template.response\n\nDjango Template Language:\n\n- django.template.base\n- django.temp", "meta": {"filepath": "django/template/__init__.py", "language": "python", "file_size": 1865, "cut_index": 537, "middle_length": 229}} +{"prefix": "= template.Template(s)\n\n(t is now a compiled template, and its render() method can be called multiple\ntimes with multiple contexts)\n\n>>> c = template.Context({'test':True, 'varvalue': 'Hello'})\n>>> t.render(c)\n'

Hello

'\n>>> c = template.Context({'test':False, 'varvalue': 'Hello'})\n>>> t.render(c)\n''\n\"\"\"\n\nimport inspect\nimport logging\nimport re\nimport warnings\nfrom enum import Enum\n\nfrom django.template.context import BaseContext\nfrom django.utils.deprecation import RemovedIn", "suffix": "zy_re_compile\nfrom django.utils.safestring import SafeData, SafeString, mark_safe\nfrom django.utils.text import get_text_list, smart_split, unescape_string_literal\nfrom django.utils.timezone import template_localtime\nfrom django.utils.translation import ge", "middle": "Django70Warning, django_file_prefixes\nfrom django.utils.formats import localize\nfrom django.utils.html import conditional_escape\nfrom django.utils.inspect import getfullargspec, signature\nfrom django.utils.regex_helper import _la", "meta": {"filepath": "django/template/base.py", "language": "python", "file_size": 44608, "cut_index": 2151, "middle_length": 229}} +{"prefix": "rgs)\n\n context.dicts.append(self)\n self.context = context\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args, **kwargs):\n self.context.pop()\n\n\nclass BaseContext:\n def __init__(self, dict_=None):\n self._reset_dicts(dict_)\n\n def _reset_dicts(self, value=None):\n builtins = {\"True\": True, \"False\": False, \"None\": None}\n self.dicts = [builtins]\n if isinstance(value, BaseContext):\n self.dicts += value.dicts[1:]\n elif ", "suffix": "cts = self.dicts[:]\n return duplicate\n\n def __repr__(self):\n return repr(self.dicts)\n\n def __iter__(self):\n return reversed(self.dicts)\n\n def push(self, *args, **kwargs):\n dicts = []\n for d in args:\n i", "middle": "value is not None:\n self.dicts.append(value)\n\n def __copy__(self):\n duplicate = BaseContext()\n duplicate.__class__ = self.__class__\n duplicate.__dict__ = copy(self.__dict__)\n duplicate.di", "meta": {"filepath": "django/template/context.py", "language": "python", "file_size": 9482, "cut_index": 921, "middle_length": 229}} +{"prefix": "t (\n Exact,\n GreaterThan,\n GreaterThanOrEqual,\n In,\n IsNull,\n LessThan,\n LessThanOrEqual,\n)\n\n\ndef get_normalized_value(value, lhs):\n from django.db.models import Model\n\n if isinstance(value, Model):\n if not value._is_pk_set():\n raise ValueError(\"Model instances passed to related filters must be saved.\")\n value_list = []\n sources = composite.unnest(lhs.output_field.path_infos[-1].target_fields)\n for source in sources:\n while not isi", "suffix": "_list.append(getattr(value, source.attname))\n except AttributeError:\n # A case like\n # Restaurant.objects.filter(place=restaurant_instance), where\n # place is a OneToOneField and the primary key of Re", "middle": "nstance(value, source.model) and source.remote_field:\n source = source.remote_field.model._meta.get_field(\n source.remote_field.field_name\n )\n try:\n value", "meta": {"filepath": "django/db/models/fields/related_lookups.py", "language": "python", "file_size": 6094, "cut_index": 716, "middle_length": 229}} +{"prefix": "dels.sql import Query\nfrom django.db.models.sql.where import AND, OR, WhereNode\n\n\nclass Tuple(Func):\n allows_composite_expressions = True\n function = \"\"\n output_field = models.Field()\n\n def __len__(self):\n return len(self.source_expressions)\n\n def __iter__(self):\n return iter(self.source_expressions)\n\n def as_sqlite(self, compiler, connection):\n if connection.get_database_version() < (3, 37) and isinstance(\n first_expr := self.source_expressions[0], Tuple\n ", "suffix": "return self.as_sql(compiler, connection)\n\n\nclass TupleLookupMixin:\n allows_composite_expressions = True\n\n def get_prep_lookup(self):\n if self.rhs_is_direct_value():\n self.check_rhs_is_tuple_or_list()\n self.check_rhs_lengt", "middle": " ):\n first_expr = first_expr.copy()\n first_expr.function = \"VALUES\"\n return Tuple(first_expr, *self.source_expressions[1:]).as_sql(\n compiler, connection\n )\n ", "meta": {"filepath": "django/db/models/fields/tuple_lookups.py", "language": "python", "file_size": 15377, "cut_index": 921, "middle_length": 229}} +{"prefix": "those directories, and open and\n read the Python files, looking for a class called Migration, which should\n inherit from django.db.migrations.Migration. See\n django.db.migrations.migration for what that looks like.\n\n Some migrations will be marked as \"replacing\" another set of migrations.\n These are loaded into a separate set of migrations away from the main ones.\n If all the migrations they replace are either unapplied or missing from\n disk, then they are injected into the main set, re", "suffix": "probably fine. We're already not just operating\n in memory.\n \"\"\"\n\n def __init__(\n self,\n connection,\n load=True,\n ignore_no_migrations=False,\n replace_migrations=True,\n ):\n self.connection = connection\n", "middle": "placing the named\n migrations. Any dependency pointers to the replaced migrations are\n re-pointed to the new migration.\n\n This does mean that this class MUST also talk to the database as well as\n to disk, but this is ", "meta": {"filepath": "django/db/migrations/loader.py", "language": "python", "file_size": 18744, "cut_index": 1331, "middle_length": 229}} +{"prefix": "s base class has a built-in noninteractive mode, but the\n interactive subclass is what the command-line arguments will use.\n \"\"\"\n\n def __init__(self, defaults=None, specified_apps=None, dry_run=None):\n self.defaults = defaults or {}\n self.specified_apps = specified_apps or set()\n self.dry_run = dry_run\n\n def ask_initial(self, app_label):\n \"\"\"Should we create an initial migration for the app?\"\"\"\n # If it was specified on the command line, definitely true\n ", "suffix": "plate will have these; the Python\n # file check will ensure we skip South ones.\n try:\n app_config = apps.get_app_config(app_label)\n except LookupError: # It's a fake app.\n return self.defaults.get(\"ask_initial\", ", "middle": " if app_label in self.specified_apps:\n return True\n # Otherwise, we look to see if it has a migrations module\n # without any Python files in it, apart from __init__.py.\n # Apps from the new app tem", "meta": {"filepath": "django/db/migrations/questioner.py", "language": "python", "file_size": 13568, "cut_index": 921, "middle_length": 229}} +{"prefix": "ort RECURSIVE_RELATIONSHIP_CONSTANT\n\nFieldReference = namedtuple(\"FieldReference\", \"to through\")\n\nCOMPILED_REGEX_TYPE = type(re.compile(\"\"))\n\n\nclass RegexObject:\n def __init__(self, obj):\n self.pattern = obj.pattern\n self.flags = obj.flags\n\n def __eq__(self, other):\n if not isinstance(other, RegexObject):\n return NotImplemented\n return self.pattern == other.pattern and self.flags == other.flags\n\n\ndef get_migration_name_timestamp():\n return datetime.datetime.no", "suffix": "scope of recursive and\n unscoped model relationship.\n \"\"\"\n if isinstance(model, str):\n if model == RECURSIVE_RELATIONSHIP_CONSTANT:\n if app_label is None or model_name is None:\n raise TypeError(\n ", "middle": "w().strftime(\"%Y%m%d_%H%M\")\n\n\ndef resolve_relation(model, app_label=None, model_name=None):\n \"\"\"\n Turn a model class or model reference string and return a model tuple.\n\n app_label and model_name are used to resolve the ", "meta": {"filepath": "django/db/migrations/utils.py", "language": "python", "file_size": 4401, "cut_index": 614, "middle_length": 229}} +{"prefix": "eld = field\n\n @cached_property\n def model_name_lower(self):\n return self.model_name.lower()\n\n @cached_property\n def name_lower(self):\n return self.name.lower()\n\n def is_same_model_operation(self, operation):\n return self.model_name_lower == operation.model_name_lower\n\n def is_same_field_operation(self, operation):\n return (\n self.is_same_model_operation(operation)\n and self.name_lower == operation.name_lower\n )\n\n def references_mo", "suffix": " (app_label, self.model_name_lower),\n self.field,\n (app_label, name_lower),\n )\n )\n return False\n\n def references_field(self, model_name, name, app_label):\n model_name_lo", "middle": "del(self, name, app_label):\n name_lower = name.lower()\n if name_lower == self.model_name_lower:\n return True\n if self.field:\n return bool(\n field_references(\n ", "meta": {"filepath": "django/db/migrations/operations/fields.py", "language": "python", "file_size": 12787, "cut_index": 921, "middle_length": 229}} +{"prefix": "rt receiver\nfrom django.template import engines\nfrom django.template.backends.django import DjangoTemplates\nfrom django.utils._os import to_path\nfrom django.utils.autoreload import autoreload_started, file_changed, is_django_path\n\n\ndef get_template_directories():\n # Iterate through each template backend and find\n # any template_loader that has a 'get_dirs' method.\n # Collect the directories, filtering out Django templates.\n cwd = Path.cwd()\n items = set()\n for backend in engines.all():\n ", "suffix": "attr(loader, \"get_dirs\"):\n continue\n items.update(\n cwd / to_path(directory)\n for directory in loader.get_dirs()\n if directory and not is_django_path(directory)\n )\n return", "middle": " if not isinstance(backend, DjangoTemplates):\n continue\n\n items.update(cwd / to_path(dir) for dir in backend.engine.dirs if dir)\n\n for loader in backend.engine.template_loaders:\n if not has", "meta": {"filepath": "django/template/autoreload.py", "language": "python", "file_size": 2063, "cut_index": 563, "middle_length": 229}} +{"prefix": "aries to be merged into a\ntemplate context. Each function takes the request object as its only parameter\nand returns a dictionary to add to the context.\n\nThese are referenced from the 'context_processors' option of the configuration\nof a DjangoTemplates backend and used by RequestContext.\n\"\"\"\n\nimport itertools\n\nfrom django.conf import settings\nfrom django.middleware.csp import get_nonce\nfrom django.middleware.csrf import get_token\nfrom django.utils.csp import CONTEXT_KEY as CSP_CONTEXT_KEY\nfrom django.utils", "suffix": " \"\"\"\n\n def _get_val():\n token = get_token(request)\n if token is None:\n # In order to be able to provide debugging info in the\n # case of misconfiguration, we use a sentinel value\n # instead of returning an ", "middle": ".functional import SimpleLazyObject, lazy\n\n\ndef csrf(request):\n \"\"\"\n Context processor that provides a CSRF token, or the string 'NOTPROVIDED'\n if it has not been provided by either a view decorator or the middleware\n ", "meta": {"filepath": "django/template/context_processors.py", "language": "python", "file_size": 2707, "cut_index": 563, "middle_length": 229}} +{"prefix": "\n\n - operations: A list of Operation instances, probably from\n django.db.migrations.operations\n - dependencies: A list of tuples of (app_path, migration_name)\n - run_before: A list of tuples of (app_path, migration_name)\n - replaces: A list of migration_names\n\n Note that all migrations come out of migrations and into the Loader or\n Graph as instances, having been initialized with their app label and name.\n \"\"\"\n\n # Operations to apply during this migration, in order.\n ope", "suffix": " migration added to their dependencies). Useful to make third-party\n # apps' migrations run after your AUTH_USER replacement, for example.\n run_before = []\n\n # Migration names in this app that this migration replaces. If this is\n # non-empty, t", "middle": "rations = []\n\n # Other migrations that should be run before this migration.\n # Should be a list of (app, migration_name).\n dependencies = []\n\n # Other migrations that should be run after this one (i.e. have\n # this", "meta": {"filepath": "django/db/migrations/migration.py", "language": "python", "file_size": 9765, "cut_index": 921, "middle_length": 229}} +{"prefix": "ON = \"p\"\n SQL = \"s\"\n MIXED = \"?\"\n\n\nclass Operation:\n \"\"\"\n Base class for migration operations.\n\n It's responsible for both mutating the in-memory model state\n (see db/migrations/state.py) to represent what it performs, as well\n as actually performing it against a live database.\n\n Note that some operations won't modify memory state at all (e.g. data\n copying operations), and some will need their modifications to be\n optionally specified by the user (e.g. custom Python code snipp", "suffix": " reversible = True\n\n # Can this migration be represented as SQL? (things like RunPython cannot)\n reduces_to_sql = True\n\n # Should this operation be forced as atomic even on backends with no\n # DDL transaction support (i.e., does it have no DDL", "middle": "ets)\n\n Due to the way this class deals with deconstruction, it should be\n considered immutable.\n \"\"\"\n\n # If this migration can be run in reverse.\n # Some operations are impossible to reverse, like deleting data.\n ", "meta": {"filepath": "django/db/migrations/operations/base.py", "language": "python", "file_size": 5927, "cut_index": 716, "middle_length": 229}} +{"prefix": "ic\nfrom django.utils.text import slugify as _slugify\nfrom django.utils.text import wrap\nfrom django.utils.timesince import timesince, timeuntil\nfrom django.utils.translation import gettext, ngettext\n\nfrom .base import VARIABLE_ATTRIBUTE_SEPARATOR\nfrom .library import Library\n\nregister = Library()\n\n\n#######################\n# STRING DECORATOR #\n#######################\n\n\ndef stringfilter(func):\n \"\"\"\n Decorator for filters which should only receive strings. The object\n passed as the first positional", "suffix": "unwrap(func), \"is_safe\", False):\n result = mark_safe(result)\n return result\n\n return _dec\n\n\n###################\n# STRINGS #\n###################\n\n\n@register.filter(is_safe=True)\n@stringfilter\ndef addslashes(value):\n \"\"\"\n A", "middle": " argument will be converted to a string.\n \"\"\"\n\n @wraps(func)\n def _dec(first, *args, **kwargs):\n first = str(first)\n result = func(first, *args, **kwargs)\n if isinstance(first, SafeData) and getattr(", "meta": {"filepath": "django/template/defaultfilters.py", "language": "python", "file_size": 28417, "cut_index": 1331, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\" # 31 janvier 2024\nTIME_FORMAT = \"H\\xa0\\\\h\\xa0i\" # 13 h 40\nDATETIME_FORMAT = \"j F Y, H\\xa0\\\\h\\xa0i\" # 31 janvier 2024, 13 h 40\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"Y-m-d\"\nSHORT_DATETIME_FORMAT = \"Y-m-d H\\xa0\\\\h\\xa0i\"\nFIRST_DAY_OF_WEEK = 0 # Dimanche\n\n#", "suffix": "5'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-05-15 14:30:57'\n \"%y-%m-%d %H:%M:%S\", # '06-05-15 14:30:57'\n \"%Y-%m-%d %H:%M:%S.%f\", # '2006-05-15 14:30:57.000200'\n \"%y-%m-%d %H:%M:%S.%f\", # '06-05-15 14:30:57.000200'\n \"%Y-", "middle": " The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-05-15'\n \"%y-%m-%d\", # '06-05-1", "meta": {"filepath": "django/conf/locale/fr_CA/formats.py", "language": "python", "file_size": 1177, "cut_index": 518, "middle_length": 229}} +{"prefix": "rt Template, TemplateDoesNotExist\n\n\nclass Loader:\n def __init__(self, engine):\n self.engine = engine\n\n def get_template(self, template_name, skip=None):\n \"\"\"\n Call self.get_template_sources() and return a Template object for\n the first template matching template_name. If skip is provided, ignore\n template origins in skip. This is used to avoid recursion during\n template extending.\n \"\"\"\n tried = []\n\n for origin in self.get_template_sources(", "suffix": "in)\n except TemplateDoesNotExist:\n tried.append((origin, \"Source does not exist\"))\n continue\n else:\n return Template(\n contents,\n origin,\n ", "middle": "template_name):\n if skip is not None and origin in skip:\n tried.append((origin, \"Skipped to avoid recursion\"))\n continue\n\n try:\n contents = self.get_contents(orig", "meta": {"filepath": "django/template/loaders/base.py", "language": "python", "file_size": 1636, "cut_index": 537, "middle_length": 229}} +{"prefix": "for loading templates from the filesystem.\n\"\"\"\n\nfrom django.core.exceptions import SuspiciousFileOperation\nfrom django.template import Origin, TemplateDoesNotExist\nfrom django.utils._os import safe_join\n\nfrom .base import Loader as BaseLoader\n\n\nclass Loader(BaseLoader):\n def __init__(self, engine, dirs=None):\n super().__init__(engine)\n self.dirs = dirs\n\n def get_dirs(self):\n return self.dirs if self.dirs is not None else self.engine.dirs\n\n def get_contents(self, origin):\n ", "suffix": "elf, template_name):\n \"\"\"\n Return an Origin object pointing to an absolute path in each directory\n in template_dirs. For security reasons, if a path doesn't lie inside\n one of the template_dirs it is excluded from the result set", "middle": " try:\n with open(origin.name, encoding=self.engine.file_charset) as fp:\n return fp.read()\n except FileNotFoundError:\n raise TemplateDoesNotExist(origin)\n\n def get_template_sources(s", "meta": {"filepath": "django/template/loaders/filesystem.py", "language": "python", "file_size": 1506, "cut_index": 524, "middle_length": 229}} +{"prefix": "nit Test framework.\"\"\"\n\nfrom django.test.client import AsyncClient, AsyncRequestFactory, Client, RequestFactory\nfrom django.test.testcases import (\n LiveServerTestCase,\n SimpleTestCase,\n TestCase,\n TransactionTestCase,\n skipIfDBFeature,\n skipUnlessAnyDBFeature,\n skipUnlessDBFeature,\n)\nfrom django.test.utils import (\n ignore_warnings,\n modify_settings,\n override_settings,\n override_system_checks,\n tag,\n)\n\n__all__ = [\n \"AsyncClient\",\n \"AsyncRequestFactory\",\n \"Clien", "suffix": "actionTestCase\",\n \"SimpleTestCase\",\n \"LiveServerTestCase\",\n \"skipIfDBFeature\",\n \"skipUnlessAnyDBFeature\",\n \"skipUnlessDBFeature\",\n \"ignore_warnings\",\n \"modify_settings\",\n \"override_settings\",\n \"override_system_checks\",\n \"tag\",", "middle": "t\",\n \"RequestFactory\",\n \"TestCase\",\n \"Trans", "meta": {"filepath": "django/test/__init__.py", "language": "python", "file_size": 834, "cut_index": 523, "middle_length": 52}} +{"prefix": "ecord.args[\"sql\"] = formatted_sql = format_sql(sql)\n\n if extra_sql := getattr(record, \"sql\", None):\n if extra_sql == sql:\n record.sql = formatted_sql\n else:\n record.sql = format_sql(extra_sql)\n\n return super().format(record)\n\n\nclass DebugSQLTextTestResult(unittest.TextTestResult):\n def __init__(self, stream, descriptions, verbosity):\n self.logger = logging.getLogger(\"django.db.backends\")\n self.logger.setLe", "suffix": ").\n sql = \"\"\n else:\n self.handler.stream.seek(0)\n sql = self.handler.stream.read()\n return sql\n\n def startTest(self, test):\n self.handler = logging.StreamHandler(io.StringIO())\n self.handler.s", "middle": "vel(logging.DEBUG)\n self.handler = None\n super().__init__(stream, descriptions, verbosity)\n\n def _read_logger_stream(self):\n if self.handler is None:\n # Error before tests e.g. in setUpTestData(", "meta": {"filepath": "django/test/runner.py", "language": "python", "file_size": 44605, "cut_index": 2151, "middle_length": 229}} +{"prefix": "re.signals import setting_changed\nfrom django.db import connections, router\nfrom django.db.utils import ConnectionRouter\nfrom django.dispatch import Signal, receiver\nfrom django.utils import timezone\nfrom django.utils.formats import FORMAT_SETTINGS, reset_format_cache\nfrom django.utils.functional import empty\nfrom django.utils.log import configure_logging\n\ntemplate_rendered = Signal()\n\n# Most setting_changed receivers are supposed to be added below,\n# except for cases where the receiver is related to a cont", "suffix": ":\n from django.core.cache import caches, close_caches\n\n close_caches()\n caches._settings = caches.settings = caches.configure_settings(None)\n caches._connections = Local()\n\n\n@receiver(setting_changed)\ndef update_installed_apps(*", "middle": "rib app.\n\n# Settings that may not work well when using 'override_settings' (#19031)\nCOMPLEX_OVERRIDE_SETTINGS = {\"DATABASES\"}\n\n\n@receiver(setting_changed)\ndef clear_cache_handlers(*, setting, **kwargs):\n if setting == \"CACHES\"", "meta": {"filepath": "django/test/signals.py", "language": "python", "file_size": 7644, "cut_index": 716, "middle_length": 229}} +{"prefix": ",\n and ones that will be used for the state change. This allows operations\n that don't support state change to have it applied, or have operations\n that affect the state or not the database, or so on.\n \"\"\"\n\n category = OperationCategory.MIXED\n serialization_expand_args = [\"database_operations\", \"state_operations\"]\n\n def __init__(self, database_operations=None, state_operations=None):\n self.database_operations = database_operations or []\n self.state_operations = state_opera", "suffix": "rations\"] = self.state_operations\n return (self.__class__.__qualname__, [], kwargs)\n\n def state_forwards(self, app_label, state):\n for state_operation in self.state_operations:\n state_operation.state_forwards(app_label, state)\n\n", "middle": "tions or []\n\n def deconstruct(self):\n kwargs = {}\n if self.database_operations:\n kwargs[\"database_operations\"] = self.database_operations\n if self.state_operations:\n kwargs[\"state_ope", "meta": {"filepath": "django/db/migrations/operations/special.py", "language": "python", "file_size": 8146, "cut_index": 716, "middle_length": 229}} +{"prefix": "ate\nfrom .context import Context, _builtin_context_processors\nfrom .exceptions import TemplateDoesNotExist\nfrom .library import import_library\n\n\nclass Engine:\n default_builtins = [\n \"django.template.defaulttags\",\n \"django.template.defaultfilters\",\n \"django.template.loader_tags\",\n ]\n\n def __init__(\n self,\n dirs=None,\n app_dirs=False,\n context_processors=None,\n debug=False,\n loaders=None,\n string_if_invalid=\"\",\n file_charset", "suffix": " is None:\n loaders = [\"django.template.loaders.filesystem.Loader\"]\n if app_dirs:\n loaders += [\"django.template.loaders.app_directories.Loader\"]\n loaders = [(\"django.template.loaders.cached.Loader\", loaders)]\n", "middle": "=\"utf-8\",\n libraries=None,\n builtins=None,\n autoescape=True,\n ):\n if dirs is None:\n dirs = []\n if context_processors is None:\n context_processors = []\n if loaders", "meta": {"filepath": "django/template/engine.py", "language": "python", "file_size": 8401, "cut_index": 716, "middle_length": 229}} +{"prefix": "r registering template tags and filters. Compiled filter and\n template tag functions are stored in the filters and tags attributes.\n The filter, simple_tag, and inclusion_tag methods provide a convenient\n way to register callables as tags.\n \"\"\"\n\n def __init__(self):\n self.filters = {}\n self.tags = {}\n\n def tag(self, name=None, compile_function=None):\n if name is None and compile_function is None:\n # @register.tag()\n return self.tag_function\n ", "suffix": "@register.tag(name='somename')\n def dec(func):\n return self.tag(name, func)\n\n return dec\n elif name is not None and compile_function is not None:\n # register.tag('somename', somefunc)\n ", "middle": " elif name is not None and compile_function is None:\n if callable(name):\n # @register.tag\n return self.tag_function(name)\n else:\n # @register.tag('somename') or ", "meta": {"filepath": "django/template/library.py", "language": "python", "file_size": 17247, "cut_index": 921, "middle_length": 229}} +{"prefix": "__repr__(self):\n return f\"<{self.__class__.__qualname__}: blocks={self.blocks!r}>\"\n\n def add_blocks(self, blocks):\n for name, block in blocks.items():\n self.blocks[name].insert(0, block)\n\n def pop(self, name):\n try:\n return self.blocks[name].pop()\n except IndexError:\n return None\n\n def push(self, name, block):\n self.blocks[name].append(block)\n\n def get_block(self, name):\n try:\n return self.blocks[name][-1]\n ", "suffix": "(self):\n return \"\" % (self.name, self.nodelist)\n\n def render(self, context):\n block_context = context.render_context.get(BLOCK_CONTEXT_KEY)\n with context.push():\n if block_context is None:\n ", "middle": " except IndexError:\n return None\n\n\nclass BlockNode(Node):\n def __init__(self, name, nodelist, parent=None):\n self.name = name\n self.nodelist = nodelist\n self.parent = parent\n\n def __repr__", "meta": {"filepath": "django/template/loader_tags.py", "language": "python", "file_size": 13526, "cut_index": 921, "middle_length": 229}} +{"prefix": "enotation\n# 'bp' = binding power (left = lbp, right = rbp)\n\n\nclass TokenBase:\n \"\"\"\n Base class for operators and literals, mainly for debugging and for\n throwing syntax errors.\n \"\"\"\n\n id = None # node/token type name\n value = None # used by literals\n first = second = None # used by tree nodes\n\n def nud(self, parser):\n # Null denotation - called in prefix context\n raise parser.error_class(\n \"Not expecting '%s' in this position in if tag.\" % self.id\n ", "suffix": " \"\"\"\n Return what to display in error messages for this node\n \"\"\"\n return self.id\n\n def __repr__(self):\n out = [str(x) for x in [self.id, self.first, self.second] if x is not None]\n return \"(\" + \" \".join(out) + \"", "middle": ")\n\n def led(self, left, parser):\n # Left denotation - called in infix context\n raise parser.error_class(\n \"Not expecting '%s' as infix operator in if tag.\" % self.id\n )\n\n def display(self):\n ", "meta": {"filepath": "django/template/smartif.py", "language": "python", "file_size": 6478, "cut_index": 716, "middle_length": 229}} +{"prefix": "ured, SuspiciousFileOperation\nfrom django.template.utils import get_app_template_dirs\nfrom django.utils._os import safe_join\nfrom django.utils.functional import cached_property\n\n\nclass BaseEngine:\n # Core methods: engines have to provide their own implementation\n # (except for from_string which is optional).\n\n def __init__(self, params):\n \"\"\"\n Initialize the template engine.\n\n `params` is a dict of configuration settings.\n \"\"\"\n params = params.copy()", "suffix": "}\".format(\", \".join(params))\n )\n\n def check(self, **kwargs):\n return []\n\n @property\n def app_dirname(self):\n raise ImproperlyConfigured(\n \"{} doesn't support loading templates from installed \"\n \"appli", "middle": "\n self.name = params.pop(\"NAME\")\n self.dirs = list(params.pop(\"DIRS\"))\n self.app_dirs = params.pop(\"APP_DIRS\")\n if params:\n raise ImproperlyConfigured(\n \"Unknown parameters: {", "meta": {"filepath": "django/template/backends/base.py", "language": "python", "file_size": 2801, "cut_index": 563, "middle_length": 229}} +{"prefix": "r, Warning\nfrom django.template import TemplateDoesNotExist\nfrom django.template.context import make_context\nfrom django.template.engine import Engine\nfrom django.template.library import InvalidTemplateLibrary\n\nfrom .base import BaseEngine\n\n\nclass DjangoTemplates(BaseEngine):\n app_dirname = \"templates\"\n\n def __init__(self, params):\n params = params.copy()\n options = params.pop(\"OPTIONS\").copy()\n options.setdefault(\"autoescape\", True)\n options.setdefault(\"debug\", settings.DE", "suffix": "ne = Engine(self.dirs, self.app_dirs, **options)\n\n def check(self, **kwargs):\n return [\n *self._check_string_if_invalid_is_string(),\n *self._check_for_template_tags_with_the_same_name(),\n ]\n\n def _check_string_if_i", "middle": "BUG)\n options.setdefault(\"file_charset\", \"utf-8\")\n libraries = options.get(\"libraries\", {})\n options[\"libraries\"] = self.get_templatetag_libraries(libraries)\n super().__init__(params)\n self.engi", "meta": {"filepath": "django/template/backends/django.py", "language": "python", "file_size": 5963, "cut_index": 716, "middle_length": 229}} +{"prefix": "ssertEqual(\n executed,\n self.num,\n \"%d queries executed, %d expected\\nCaptured queries were:\\n%s\"\n % (\n executed,\n self.num,\n \"\\n\".join(\n \"%d. %s\" % (i, query[\"sql\"])\n for i, query in enumerate(self.captured_queries, start=1)\n ),\n ),\n )\n\n\nclass _AssertTemplateUsedContext:\n def __init__(self, test_case, template_name, msg_prefix=\"\", count=None):\n ", "suffix": "mplate_render(self, sender, signal, template, context, **kwargs):\n self.rendered_templates.append(template)\n self.context.append(copy(context))\n\n @property\n def rendered_template_names(self):\n return [\n (\n ", "middle": " self.test_case = test_case\n self.template_name = template_name\n self.msg_prefix = msg_prefix\n self.count = count\n\n self.rendered_templates = []\n self.context = ContextList()\n\n def on_te", "meta": {"filepath": "django/test/testcases.py", "language": "python", "file_size": 68958, "cut_index": 3790, "middle_length": 229}} +{"prefix": "erlyConfigured\nfrom django.utils.deprecation import (\n RemovedInDjango70Warning,\n django_file_prefixes,\n warn_about_external_use,\n)\nfrom django.utils.functional import LazyObject, empty\n\nENVIRONMENT_VARIABLE = \"DJANGO_SETTINGS_MODULE\"\nDEFAULT_STORAGE_ALIAS = \"default\"\nSTATICFILES_STORAGE_ALIAS = \"staticfiles\"\n\n# RemovedInDjango70Warning.\nUSE_BLANK_CHOICE_DASH_DEPRECATED_MSG = (\n \"The USE_BLANK_CHOICE_DASH setting is deprecated. If you wish to define \"\n \"your own default blank choice label, ov", "suffix": "SSWORD\",\n \"EMAIL_HOST_USER\",\n \"EMAIL_PORT\",\n \"EMAIL_SSL_CERTFILE\",\n \"EMAIL_SSL_KEYFILE\",\n \"EMAIL_TIMEOUT\",\n \"EMAIL_USE_SSL\",\n \"EMAIL_USE_TLS\",\n}\nEMAIL_SETTING_DEPRECATED_MSG = (\n \"The {name} setting is deprecated. Migrate to MAILERS", "middle": "erride \"\n \"django.db.models.fields.BLANK_CHOICE_LABEL in your app's ready() method.\"\n)\n\n# RemovedInDjango70Warning.\nDEPRECATED_EMAIL_SETTINGS = {\n \"EMAIL_BACKEND\",\n \"EMAIL_FILE_PATH\",\n \"EMAIL_HOST\",\n \"EMAIL_HOST_PA", "meta": {"filepath": "django/conf/__init__.py", "language": "python", "file_size": 14243, "cut_index": 921, "middle_length": 229}} +{"prefix": "is true\n# * Receive x-headers\nINTERNAL_IPS = []\n\n# Hosts/domain names that are valid for this site.\n# \"*\" matches anything, \".example.com\" matches example.com and all subdomains\nALLOWED_HOSTS = []\n\n# Local time zone for this installation. All choices can be found here:\n# https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all\n# systems may support all possibilities). When USE_TZ is True, this is\n# interpreted as the default user time zone.\nTIME_ZONE = \"America/Chicago\"\n\n# If you set this ", "suffix": "ed in LANGUAGES (below), the project must\n# provide the necessary translations and locale definitions.\nLANGUAGE_CODE = \"en-us\"\n\n# Languages we provide translations for, out of the box.\nLANGUAGES = [\n (\"af\", gettext_noop(\"Afrikaans\")),\n (\"ar\", gettext", "middle": "to True, Django will use timezone-aware datetimes.\nUSE_TZ = True\n\n# Language code for this installation. Valid choices can be found here:\n# https://www.iana.org/assignments/language-subtag-registry/\n# If LANGUAGE_CODE is not list", "meta": {"filepath": "django/conf/global_settings.py", "language": "python", "file_size": 23658, "cut_index": 1331, "middle_length": 229}} +{"prefix": "from them in order, caching the result.\n\"\"\"\n\nimport hashlib\n\nfrom django.template import TemplateDoesNotExist\nfrom django.template.backends.django import copy_exception\n\nfrom .base import Loader as BaseLoader\n\n\nclass Loader(BaseLoader):\n def __init__(self, engine, loaders):\n self.get_template_cache = {}\n self.loaders = engine.get_template_loaders(loaders)\n super().__init__(engine)\n\n def get_dirs(self):\n for loader in self.loaders:\n if hasattr(loader, \"get_dirs\"):", "suffix": "hat gives this loader its name. Often many of the\n templates attempted will be missing, so memory use is of concern here.\n To keep it in check, caching behavior is a little complicated when a\n template is not found. See ticket #26306 f", "middle": "\n yield from loader.get_dirs()\n\n def get_contents(self, origin):\n return origin.loader.get_contents(origin)\n\n def get_template(self, template_name, skip=None):\n \"\"\"\n Perform the caching t", "meta": {"filepath": "django/template/loaders/cached.py", "language": "python", "file_size": 3716, "cut_index": 614, "middle_length": 229}} +{"prefix": " U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020\n# SPACE.\n# https://infra.spec.whatwg.org/#ascii-whitespace\nASCII_WHITESPACE = _lazy_re_compile(r\"[\\t\\n\\f\\r ]+\")\n\n# https://html.spec.whatwg.org/#attributes-3\nBOOLEAN_ATTRIBUTES = {\n \"allowfullscreen\",\n \"async\",\n \"autofocus\",\n \"autoplay\",\n \"checked\",\n \"controls\",\n \"default\",\n \"defer \",\n \"disabled\",\n \"formnovalidate\",\n \"hidden\",\n \"ismap\",\n \"itemscope\",\n \"loop\",\n \"multiple\",\n \"muted\",\n \"nomodule\",\n \"no", "suffix": "b(\" \", string)\n\n\ndef normalize_attributes(attributes):\n normalized = []\n for name, value in attributes:\n if name == \"class\" and value:\n # Special case handling of 'class' attribute, so that comparisons\n # of DOM instances", "middle": "validate\",\n \"open\",\n \"playsinline\",\n \"readonly\",\n \"required\",\n \"reversed\",\n \"selected\",\n # Attributes for deprecated tags.\n \"truespeed\",\n}\n\n\ndef normalize_whitespace(string):\n return ASCII_WHITESPACE.su", "meta": {"filepath": "django/test/html.py", "language": "python", "file_size": 8869, "cut_index": 716, "middle_length": 229}} +{"prefix": "wards?).\n \"\"\"\n plan = []\n if clean_start:\n applied = {}\n else:\n applied = dict(self.loader.applied_migrations)\n for target in targets:\n # If the target is (app_label, None), that means unmigrate\n # everything\n if target[1] is None:\n for root in self.loader.graph.root_nodes():\n if root[0] == target[0]:\n for migration in self.loader.graph.backwards_plan(root):\n ", "suffix": "g, it's likely a replaced migration.\n # Reload the graph without replacements.\n elif (\n self.loader.replace_migrations\n and target not in self.loader.graph.node_map\n ):\n self.loa", "middle": " if migration in applied:\n plan.append((self.loader.graph.nodes[migration], True))\n applied.pop(migration)\n # If the target is missin", "meta": {"filepath": "django/db/migrations/executor.py", "language": "python", "file_size": 19029, "cut_index": 1331, "middle_length": 229}} +{"prefix": "ule contains generic exceptions used by template backends. Although,\ndue to historical reasons, the Django template language also internally uses\nthese exceptions, other exceptions specific to the DTL should not be added\nhere.\n\"\"\"\n\n\nclass TemplateDoesNotExist(Exception):\n \"\"\"\n The exception used when a template does not exist. Optional arguments:\n\n backend\n The template backend class used when raising this exception.\n\n tried\n A list of sources that were tried when finding the templ", "suffix": "list of intermediate TemplateDoesNotExist exceptions. This is used to\n encapsulate multiple exceptions when loading templates from multiple\n engines.\n \"\"\"\n\n def __init__(self, msg, tried=None, backend=None, chain=None):\n self.bac", "middle": "ate. This\n is formatted as a list of tuples containing (origin, status), where\n origin is an Origin object or duck type and status is a string with the\n reason the template wasn't found.\n\n chain\n A ", "meta": {"filepath": "django/template/exceptions.py", "language": "python", "file_size": 1342, "cut_index": 524, "middle_length": 229}} +{"prefix": "rs = [\"template_name\", \"context_data\", \"_post_render_callbacks\"]\n\n def __init__(\n self,\n template,\n context=None,\n content_type=None,\n status=None,\n charset=None,\n using=None,\n headers=None,\n ):\n # It would seem obvious to call these next two members 'template' and\n # 'context', but those names are reserved as part of the test Client\n # API. To avoid the name collision, we use different names.\n self.template_name = tem", "suffix": "Response. It's defined in the base class\n # to minimize code duplication.\n # It's called self._request because self.request gets overwritten by\n # django.test.client.Client. Unlike template_name and context_data,\n # _request sho", "middle": "plate\n self.context_data = context\n\n self.using = using\n\n self._post_render_callbacks = []\n\n # _request stores the current request object in subclasses that know\n # about requests, like Template", "meta": {"filepath": "django/template/response.py", "language": "python", "file_size": 5584, "cut_index": 716, "middle_length": 229}} +{"prefix": "o.core.exceptions import ImproperlyConfigured\nfrom django.template import Origin, TemplateDoesNotExist\nfrom django.utils.html import conditional_escape\n\nfrom .base import BaseEngine\nfrom .utils import csrf_input_lazy, csrf_token_lazy\n\n\nclass TemplateStrings(BaseEngine):\n app_dirname = \"template_strings\"\n\n def __init__(self, params):\n params = params.copy()\n options = params.pop(\"OPTIONS\").copy()\n if options:\n raise ImproperlyConfigured(\"Unknown options: {}\".format(\", \".", "suffix": "ter_template_filenames(template_name):\n try:\n with open(template_file, encoding=\"utf-8\") as fp:\n template_code = fp.read()\n except FileNotFoundError:\n tried.append(\n ", "middle": "join(options)))\n super().__init__(params)\n\n def from_string(self, template_code):\n return Template(template_code)\n\n def get_template(self, template_name):\n tried = []\n for template_file in self.i", "meta": {"filepath": "django/template/backends/dummy.py", "language": "python", "file_size": 1751, "cut_index": 537, "middle_length": 229}} +{"prefix": "Template\nfrom django.test.signals import template_rendered\nfrom django.urls import get_script_prefix, set_script_prefix\nfrom django.utils.translation import deactivate\nfrom django.utils.version import PYPY\n\ntry:\n import jinja2\nexcept ImportError:\n jinja2 = None\n\n\n__all__ = (\n \"Approximate\",\n \"ContextList\",\n \"isolate_lru_cache\",\n \"garbage_collect\",\n \"get_runner\",\n \"CaptureQueriesContext\",\n \"ignore_warnings\",\n \"isolate_apps\",\n \"modify_settings\",\n \"override_settings\",\n \"o", "suffix": ", val, places=7):\n self.val = val\n self.places = places\n\n def __repr__(self):\n return repr(self.val)\n\n def __eq__(self, other):\n return self.val == other or round(abs(self.val - other), self.places) == 0\n\n\nclass ContextLis", "middle": "verride_system_checks\",\n \"tag\",\n \"requires_tz_support\",\n \"setup_databases\",\n \"setup_test_environment\",\n \"teardown_test_environment\",\n)\n\nTZ_SUPPORT = hasattr(time, \"tzset\")\n\n\nclass Approximate:\n def __init__(self", "meta": {"filepath": "django/test/utils.py", "language": "python", "file_size": 33543, "cut_index": 1331, "middle_length": 229}} +{"prefix": "RMANENTLY,\n HTTPStatus.FOUND,\n HTTPStatus.SEE_OTHER,\n HTTPStatus.TEMPORARY_REDIRECT,\n HTTPStatus.PERMANENT_REDIRECT,\n ]\n)\n\n\nclass RedirectCycleError(Exception):\n \"\"\"The test client has been asked to follow a redirect loop.\"\"\"\n\n def __init__(self, message, last_response):\n super().__init__(message)\n self.last_response = last_response\n self.redirect_chain = last_response.redirect_chain\n\n\nclass FakePayload(IOBase):\n \"\"\"\n A wrapper around BytesIO t", "suffix": "l life.\n \"\"\"\n\n def __init__(self, initial_bytes=None):\n self.__content = BytesIO()\n self.__len = 0\n self.read_started = False\n if initial_bytes is not None:\n self.write(initial_bytes)\n\n def __len__(self):\n ", "middle": "hat restricts what can be read since data from\n the network can't be sought and cannot be read outside of its content\n length. This makes sure that views can't do anything under the test client\n that wouldn't work in rea", "meta": {"filepath": "django/test/client.py", "language": "python", "file_size": 56053, "cut_index": 2151, "middle_length": 229}} +{"prefix": "ls.deletion import DatabaseOnDelete\nfrom django.utils.functional import LazyObject, Promise\nfrom django.utils.version import get_docs_version\n\nFUNCTION_TYPES = (types.FunctionType, types.BuiltinFunctionType, types.MethodType)\n\nif isinstance(functools._lru_cache_wrapper, type):\n # When using CPython's _functools C module, LRU cache function decorators\n # present as a class and not a function, so add that class to the list of\n # function types. In the pure Python implementation and PyPy they present\n", "suffix": "NotImplementedError(\n \"Subclasses of BaseSerializer must implement the serialize() method.\"\n )\n\n\nclass BaseSequenceSerializer(BaseSerializer):\n def _format(self):\n raise NotImplementedError(\n \"Subclasses of BaseSequen", "middle": " # as normal functions which are already handled.\n FUNCTION_TYPES += (functools._lru_cache_wrapper,)\n\n\nclass BaseSerializer:\n def __init__(self, value):\n self.value = value\n\n def serialize(self):\n raise ", "meta": {"filepath": "django/db/migrations/serializer.py", "language": "python", "file_size": 14835, "cut_index": 921, "middle_length": 229}} +{"prefix": "s\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.functional import cached_property\nfrom django.utils.module_loading import import_string\n\n\nclass InvalidTemplateEngineError(ImproperlyConfigured):\n pass\n\n\nclass EngineHandler:\n def __init__(self, templates=None):\n \"\"\"\n templates is an optional list of template engine definitions\n (structured like settings.TEMPLATES).\n \"\"\"\n self._templates = templates\n se", "suffix": "lates:\n try:\n # This will raise an exception if 'BACKEND' doesn't exist or\n # isn't a string containing at least one dot.\n default_name = tpl[\"BACKEND\"].rsplit(\".\", 2)[-2]\n except Exception", "middle": "lf._engines = {}\n\n @cached_property\n def templates(self):\n if self._templates is None:\n self._templates = settings.TEMPLATES\n\n templates = {}\n backend_names = []\n for tpl in self._temp", "meta": {"filepath": "django/template/utils.py", "language": "python", "file_size": 3571, "cut_index": 614, "middle_length": 229}} +{"prefix": " functools\n\nfrom django.conf import settings\nfrom django.urls import LocalePrefixPattern, URLResolver, get_resolver, path\nfrom django.views.i18n import set_language\n\n\ndef i18n_patterns(*urls, prefix_default_language=True):\n \"\"\"\n Add the language code prefix to every URL pattern within this function.\n This may only be used in the root URLconf, not in an included URLconf.\n \"\"\"\n if not settings.USE_I18N:\n return list(urls)\n return [\n URLResolver(\n LocalePrefixPattern(", "suffix": "erns() (LocalePrefixPattern) is used in the URLconf,\n `True` if the default language should be prefixed\n )\n \"\"\"\n for url_pattern in get_resolver(urlconf).url_patterns:\n if isinstance(url_pattern.pattern, LocalePrefixPattern):\n ", "middle": "prefix_default_language=prefix_default_language),\n list(urls),\n )\n ]\n\n\n@functools.cache\ndef is_language_prefix_patterns_used(urlconf):\n \"\"\"\n Return a tuple of two booleans: (\n `True` if i18n_patt", "meta": {"filepath": "django/conf/urls/i18n.py", "language": "python", "file_size": 1166, "cut_index": 518, "middle_length": 229}} +{"prefix": "tCase)):\n # List of browsers to dynamically create test classes for.\n browsers = []\n # A selenium hub URL to test against.\n selenium_hub = None\n # The external host Selenium Hub can reach.\n external_host = None\n # Sentinel value to differentiate browser-specific instances.\n browser = None\n # Run browsers in headless mode.\n headless = False\n\n def __new__(cls, name, bases, attrs):\n \"\"\"\n Dynamically create new classes and add them to the test module when\n m", "suffix": " # it.\n if test_class.browser or not any(\n name.startswith(\"test\") and callable(value) for name, value in attrs.items()\n ):\n return test_class\n elif test_class.browsers:\n # Reuse the created test class ", "middle": "ultiple browsers specs are provided (e.g. --selenium=firefox,chrome).\n \"\"\"\n test_class = super().__new__(cls, name, bases, attrs)\n # If the test class is either browser-specific or a test base, return\n ", "meta": {"filepath": "django/test/selenium.py", "language": "python", "file_size": 10493, "cut_index": 921, "middle_length": 229}} +{"prefix": "TemplateDoesNotExist, TemplateSyntaxError\nfrom django.utils.functional import cached_property\nfrom django.utils.module_loading import import_string\n\nfrom .base import BaseEngine\nfrom .utils import csrf_input_lazy, csrf_token_lazy\n\n\nclass Jinja2(BaseEngine):\n app_dirname = \"jinja2\"\n\n def __init__(self, params):\n params = params.copy()\n options = params.pop(\"OPTIONS\").copy()\n super().__init__(params)\n\n self.context_processors = options.pop(\"context_processors\", [])\n\n e", "suffix": " options.setdefault(\"autoescape\", True)\n options.setdefault(\"auto_reload\", settings.DEBUG)\n options.setdefault(\n \"undefined\", jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined\n )\n\n self.env = environ", "middle": "nvironment = options.pop(\"environment\", \"jinja2.Environment\")\n environment_cls = import_string(environment)\n\n if \"loader\" not in options:\n options[\"loader\"] = jinja2.FileSystemLoader(self.template_dirs)\n ", "meta": {"filepath": "django/template/backends/jinja2.py", "language": "python", "file_size": 4036, "cut_index": 614, "middle_length": 229}} +{"prefix": "ateDoesNotExist\n\n\ndef get_template(template_name, using=None):\n \"\"\"\n Load and return a template for the given name.\n\n Raise TemplateDoesNotExist if no such template exists.\n \"\"\"\n chain = []\n engines = _engine_list(using)\n for engine in engines:\n try:\n return engine.get_template(template_name)\n except TemplateDoesNotExist as e:\n chain.append(e)\n\n raise TemplateDoesNotExist(template_name, chain=chain)\n\n\ndef select_template(template_name_list, using=N", "suffix": "name_list, str):\n raise TypeError(\n \"select_template() takes an iterable of template names but got a \"\n \"string: %r. Use get_template() if you want to load a single \"\n \"template by name.\" % template_name_list\n ", "middle": "one):\n \"\"\"\n Load and return a template for one of the given names.\n\n Try names in order and return the first template found.\n\n Raise TemplateDoesNotExist if no such template exists.\n \"\"\"\n if isinstance(template_", "meta": {"filepath": "django/template/loader.py", "language": "python", "file_size": 2054, "cut_index": 563, "middle_length": 229}} +{"prefix": " \"name\": \"Afrikaans\",\n \"name_local\": \"Afrikaans\",\n },\n \"ar\": {\n \"bidi\": True,\n \"code\": \"ar\",\n \"name\": \"Arabic\",\n \"name_local\": \"العربيّة\",\n },\n \"ar-dz\": {\n \"bidi\": True,\n \"code\": \"ar-dz\",\n \"name\": \"Algerian Arabic\",\n \"name_local\": \"العربية الجزائرية\",\n },\n \"ast\": {\n \"bidi\": False,\n \"code\": \"ast\",\n \"name\": \"Asturian\",\n \"name_local\": \"asturianu\",\n },\n \"az\": {\n \"bidi\": True,\n \"cod", "suffix": " \"bidi\": False,\n \"code\": \"bg\",\n \"name\": \"Bulgarian\",\n \"name_local\": \"български\",\n },\n \"bn\": {\n \"bidi\": False,\n \"code\": \"bn\",\n \"name\": \"Bengali\",\n \"name_local\": \"বাংলা\",\n },\n \"br\": {\n ", "middle": "e\": \"az\",\n \"name\": \"Azerbaijani\",\n \"name_local\": \"Azərbaycanca\",\n },\n \"be\": {\n \"bidi\": False,\n \"code\": \"be\",\n \"name\": \"Belarusian\",\n \"name_local\": \"беларуская\",\n },\n \"bg\": {\n ", "meta": {"filepath": "django/conf/locale/__init__.py", "language": "python", "file_size": 14004, "cut_index": 921, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"Y년 n월 j일\"\nTIME_FORMAT = \"A g:i\"\nDATETIME_FORMAT = \"Y년 n월 j일 g:i A\"\nYEAR_MONTH_FORMAT = \"Y년 n월\"\nMONTH_DAY_FORMAT = \"n월 j일\"\nSHORT_DATE_FORMAT = \"Y-n-j\"\nSHORT_DATETIME_FORMAT = \"Y-n-j H:i\"\n# FIRST_DAY_OF_WEEK =\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/", "suffix": "Oct 25 2006'\n # \"%b %d, %Y\", # 'Oct 25, 2006'\n # \"%d %b %Y\", # '25 Oct 2006'\n # \"%d %b, %Y\", #'25 Oct, 2006'\n # \"%B %d %Y\", # 'October 25 2006'\n # \"%B %d, %Y\", #'October 25, 2006'\n # \"%d %B %Y\", # '25 October 2006'\n # \"%d %B, %Y\"", "middle": "datetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%m/%d/%Y\", # '10/25/2006'\n \"%m/%d/%y\", # '10/25/06'\n # \"%b %d %Y\", # '", "meta": {"filepath": "django/conf/locale/ko/formats.py", "language": "python", "file_size": 2060, "cut_index": 537, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d E Y р.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"d E Y р. H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"d F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://doc", "suffix": "# '14:30:59.000200'\n \"%H:%M\", # '14:30'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d %B %Y %H:%M:%S\", # '", "middle": "s.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d %B %Y\", # '25 October 2006'\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # '14:30:59'\n \"%H:%M:%S.%f\", ", "meta": {"filepath": "django/conf/locale/uk/formats.py", "language": "python", "file_size": 1241, "cut_index": 518, "middle_length": 229}} +{"prefix": "ngs use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%", "suffix": "\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30:59.000200'\n \"%d/%m/%Y %H:%M\", # '25/10/2006 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \"\\xa0\" # non-breaking sp", "middle": "m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'", "meta": {"filepath": "django/conf/locale/fr/formats.py", "language": "python", "file_size": 938, "cut_index": 606, "middle_length": 52}} +{"prefix": "ngs use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j N Y\"\nTIME_FORMAT = r\"H:i\"\nDATETIME_FORMAT = r\"j N Y H:i\"\nYEAR_MONTH_FORMAT = r\"F Y\"\nMONTH_DAY_FORMAT = r\"j \\d\\e F\"\nSHORT_DATE_FORMAT = r\"d/m/Y\"\nSHORT_DATETIME_FORMAT = r\"d/m/Y H:i\"\nFIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_I", "suffix": " \"%d/%m/%y\", # '31/12/09'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\",\n \"%d/%m/%Y %H:%M:%S.%f\",\n \"%d/%m/%Y %H:%M\",\n \"%d/%m/%y %H:%M:%S\",\n \"%d/%m/%y %H:%M:%S.%f\",\n \"%d/%m/%y %H:%M\",\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \".\"", "middle": "NPUT_FORMATS = [\n \"%d/%m/%Y\", # '31/12/2009'\n ", "meta": {"filepath": "django/conf/locale/es_AR/formats.py", "language": "python", "file_size": 935, "cut_index": 606, "middle_length": 52}} +{"prefix": "ngo.conf import settings\nfrom django.template.backends.django import DjangoTemplates\nfrom django.template.loader import get_template\nfrom django.utils.functional import cached_property\nfrom django.utils.module_loading import import_string\n\n\n@functools.lru_cache\ndef get_default_renderer():\n renderer_class = import_string(settings.FORM_RENDERER)\n return renderer_class()\n\n\nclass BaseRenderer:\n form_template_name = \"django/forms/div.html\"\n formset_template_name = \"django/forms/formsets/div.html\"\n ", "suffix": "te_name, context, request=None):\n template = self.get_template(template_name)\n return template.render(context, request=request).strip()\n\n\nclass EngineMixin:\n def get_template(self, template_name):\n return self.engine.get_template(te", "middle": " field_template_name = \"django/forms/field.html\"\n\n bound_field_class = None\n\n def get_template(self, template_name):\n raise NotImplementedError(\"subclasses must implement get_template()\")\n\n def render(self, templa", "meta": {"filepath": "django/forms/renderers.py", "language": "python", "file_size": 2141, "cut_index": 563, "middle_length": 229}} +{"prefix": "ngs use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y, H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y, H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\",\n ", "suffix": "\nTIME_INPUT_FORMATS = [\n \"%H:%M\",\n \"%H:%M:%S\",\n \"%H:%M:%S.%f\",\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y, %H:%M\",\n \"%d.%m.%Y, %H:%M:%S\",\n \"%d.%B.%Y, %H:%M\",\n \"%d.%B.%Y, %H:%M:%S\",\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \".\"\nNUMBER", "middle": " \"%d.%b.%Y\",\n \"%d %B %Y\",\n \"%A, %d %B %Y\",\n]", "meta": {"filepath": "django/conf/locale/ro/formats.py", "language": "python", "file_size": 928, "cut_index": 606, "middle_length": 52}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"Y-m-d\"\nSHORT_DATETIME_FORMAT = \"Y-m-d H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/d", "suffix": "S = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-10-25 14:30:59'\n \"%Y-%m-%d %H:%M:%S.%f\", # '2006-10-25 14:30:59.000200'\n \"%Y-%m-%d %H:%M\", # '2006-10-25 14:30'\n \"%m/%d/%Y %H:%M:%S\", # '10/25/2006 14:30:59'\n \"%m/%d/%Y %H:%M:%S.%f\", # '10/25/2006 14:", "middle": "atetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%m/%d/%Y\", # '10/25/2006'\n \"%m/%d/%y\", # '10/25/06'\n]\nDATETIME_INPUT_FORMAT", "meta": {"filepath": "django/conf/locale/sv/formats.py", "language": "python", "file_size": 1311, "cut_index": 524, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. E Y\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j. E Y G:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y G:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/d", "suffix": "6'\n # \"%d. %b. %Y\", # '25. Oct. 2006'\n]\n# Kept ISO formats as one is in first position\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # '04:30:59'\n \"%H.%M\", # '04.30'\n \"%H:%M\", # '04:30'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '05.01.", "middle": "atetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '05.01.2006'\n \"%d.%m.%y\", # '05.01.06'\n \"%d. %m. %Y\", # '5. 1. 2006'\n \"%d. %m. %y\", # '5. 1. 06'\n # \"%d. %B %Y\", # '25. October 200", "meta": {"filepath": "django/conf/locale/cs/formats.py", "language": "python", "file_size": 1539, "cut_index": 537, "middle_length": 229}} +{"prefix": "# This file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"Y. F j.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"Y. F j. H:i\"\nYEAR_MONTH_FORMAT = \"Y. F\"\nMONTH_DAY_FORMAT = \"F j.\"\nSHORT_DATE_FORMAT = \"Y.m.d.\"\nSHORT_DATETIME_FORMAT = \"Y.m.d. H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see htt", "suffix": "S = [\n \"%Y.%m.%d. %H:%M:%S\", # '2006.10.25. 14:30:59'\n \"%Y.%m.%d. %H:%M:%S.%f\", # '2006.10.25. 14:30:59.000200'\n \"%Y.%m.%d. %H:%M\", # '2006.10.25. 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \" \" # Non-breaking space\nNUMBER_GROUPING =", "middle": "ps://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y.%m.%d.\", # '2006.10.25.'\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # '14:30:59'\n \"%H:%M\", # '14:30'\n]\nDATETIME_INPUT_FORMAT", "meta": {"filepath": "django/conf/locale/hu/formats.py", "language": "python", "file_size": 1001, "cut_index": 512, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. E Y\"\nTIME_FORMAT = \"G.i\"\nDATETIME_FORMAT = r\"j. E Y \\k\\e\\l\\l\\o G.i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j.n.Y\"\nSHORT_DATETIME_FORMAT = \"j.n.Y G.i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see ht", "suffix": "9'\n \"%d.%m.%Y %H.%M.%S.%f\", # '20.3.2014 14.30.59.000200'\n \"%d.%m.%Y %H.%M\", # '20.3.2014 14.30'\n \"%d.%m.%y %H.%M.%S\", # '20.3.14 14.30.59'\n \"%d.%m.%y %H.%M.%S.%f\", # '20.3.14 14.30.59.000200'\n \"%d.%m.%y %H.%M\", # '20.3.14 14.30'\n]\nTIME", "middle": "tps://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '20.3.2014'\n \"%d.%m.%y\", # '20.3.14'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H.%M.%S\", # '20.3.2014 14.30.5", "meta": {"filepath": "django/conf/locale/fi/formats.py", "language": "python", "file_size": 1213, "cut_index": 518, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d F Y\" # 25 Ottobre 2006\nTIME_FORMAT = \"H:i\" # 14:30\nDATETIME_FORMAT = \"l d F Y H:i\" # Mercoledì 25 Ottobre 2006 14:30\nYEAR_MONTH_FORMAT = \"F Y\" # Ottobre 2006\nMONTH_DAY_FORMAT = \"j F\" # 25 Ottobre\nSHORT_DATE_FORMAT = \"d/m/Y\" # 25/12/2009\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\" # 25/10/2009 14:30\nFIRST_DAY_OF_WE", "suffix": "%m/%d\", # '2006/10/25'\n \"%d-%m-%Y\", # '25-10-2006'\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d-%m-%y\", # '25-10-06'\n \"%d/%m/%y\", # '25/10/06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", ", "middle": "EK = 1 # Lunedì\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%Y/", "meta": {"filepath": "django/conf/locale/it/formats.py", "language": "python", "file_size": 1774, "cut_index": 537, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.pyth", "suffix": " [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30:", "middle": "on.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n]\nDATETIME_INPUT_FORMATS =", "meta": {"filepath": "django/conf/locale/fr_BE/formats.py", "language": "python", "file_size": 1154, "cut_index": 518, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y ж.\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j E Y ж. G:i\"\nYEAR_MONTH_FORMAT = \"F Y ж.\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Дүйшөмбү, Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# se", "suffix": "14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n ", "middle": "e https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 ", "meta": {"filepath": "django/conf/locale/ky/formats.py", "language": "python", "file_size": 1178, "cut_index": 518, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j M Y\" # '25 Oct 2006'\nTIME_FORMAT = \"H:i\" # '14:30'\nDATETIME_FORMAT = \"j M Y, H:i\" # '25 Oct 2006, 14:30'\nYEAR_MONTH_FORMAT = \"F Y\" # 'October 2006'\nMONTH_DAY_FORMAT = \"j F\" # '25 October'\nSHORT_DATE_FORMAT = \"d/m/Y\" # '25/10/2006'\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\" # '25/10/2006 14:30'\nFIRST_", "suffix": "\n \"%d/%m/%y\", # '25/10/06'\n \"%d %b %Y\", # '25 Oct 2006'\n \"%d %b, %Y\", # '25 Oct, 2006'\n \"%d %B %Y\", # '25 October 2006'\n \"%d %B, %Y\", # '25 October, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-10-25 14:30:59'\n ", "middle": "DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'", "meta": {"filepath": "django/conf/locale/en_IE/formats.py", "language": "python", "file_size": 1484, "cut_index": 524, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"l, j F, Y\"\nTIME_FORMAT = \"h:i a\"\nDATETIME_FORMAT = \"j F, Y h:i a\"\nYEAR_MONTH_FORMAT = \"F, Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"j.M.Y\"\nSHORT_DATETIME_FORMAT = \"j.M.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # (Monday)\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/", "suffix": ", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n # \"%d %b %Y\", # '25 Oct 2006'\n # \"%d %b, %Y\", # '25 Oct, 2006'\n # \"%d %b. %Y\", # '25 Oct. 2006'\n # \"%d %B %Y\", # '25 October 2006'\n # \"%d %B, %Y\", # '25 October, 2006'\n]\nDATETIME_INPUT_FO", "middle": "library/datetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%m/%d/%Y\", # '10/25/2006'\n \"%m/%d/%y\", # '10/25/06'\n \"%d.%m.%Y\"", "meta": {"filepath": "django/conf/locale/ka/formats.py", "language": "python", "file_size": 1861, "cut_index": 537, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"Y \\m. E j \\d.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = r\"Y \\m. E j \\d., H:i\"\nYEAR_MONTH_FORMAT = r\"Y \\m. F\"\nMONTH_DAY_FORMAT = r\"E j \\d.\"\nSHORT_DATE_FORMAT = \"Y-m-d\"\nSHORT_DATETIME_FORMAT = \"Y-m-d H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https:/", "suffix": "4:30:59'\n \"%H:%M:%S.%f\", # '14:30:59.000200'\n \"%H:%M\", # '14:30'\n \"%H.%M.%S\", # '14.30.59'\n \"%H.%M.%S.%f\", # '14.30.59.000200'\n \"%H.%M\", # '14.30'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-10-25 14:30:59'\n \"%Y-%m", "middle": "/docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # '1", "meta": {"filepath": "django/conf/locale/lt/formats.py", "language": "python", "file_size": 1637, "cut_index": 537, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. E Y.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. E Y. H:i\"\nYEAR_MONTH_FORMAT = \"F Y.\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j.m.Y.\"\nSHORT_DATETIME_FORMAT = \"j.m.Y. H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/dateti", "suffix": "5. 10. 2006.'\n \"%d. %m. %y.\", # '25. 10. 06.'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-10-25 14:30:59'\n \"%Y-%m-%d %H:%M:%S.%f\", # '2006-10-25 14:30:59.000200'\n \"%Y-%m-%d %H:%M\", # '2006-10-25 14:30'\n \"%d.%m.%Y. %H:%M:%S", "middle": "me.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d.%m.%Y.\", # '25.10.2006.'\n \"%d.%m.%y.\", # '25.10.06.'\n \"%d. %m. %Y.\", # '2", "meta": {"filepath": "django/conf/locale/hr/formats.py", "language": "python", "file_size": 1723, "cut_index": 537, "middle_length": 229}} +{"prefix": "the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\" # '20 januari 2009'\nTIME_FORMAT = \"H:i\" # '15:23'\nDATETIME_FORMAT = \"j F Y H:i\" # '20 januari 2009 15:23'\nYEAR_MONTH_FORMAT = \"F Y\" # 'januari 2009'\nMONTH_DAY_FORMAT = \"j F\" # '20 januari'\nSHORT_DATE_FORMAT = \"j-n-Y\" # '20-1-2009'\nSHORT_DATETIME_FORMAT = \"j-n-Y H:i\" # '20-1-2009 15:23'\nFIRST_DAY_OF_WEEK = 1 # Monday (in Dutch 'maandag')\n\n# The *_INPUT_FORMATS strings use the ", "suffix": " \"%d/%m/%y\", # '20/01/09'\n \"%Y/%m/%d\", # '2009/01/20'\n # \"%d %b %Y\", # '20 jan 2009'\n # \"%d %b %y\", # '20 jan 09'\n # \"%d %B %Y\", # '20 januari 2009'\n # \"%d %B %y\", # '20 januari 09'\n]\n# Kept ISO formats as one is in first position\nTIM", "middle": "Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d-%m-%Y\", # '20-01-2009'\n \"%d-%m-%y\", # '20-01-09'\n \"%d/%m/%Y\", # '20/01/2009'\n ", "meta": {"filepath": "django/conf/locale/nl/formats.py", "language": "python", "file_size": 3927, "cut_index": 614, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"N j, Y\"\nTIME_FORMAT = \"P\"\nDATETIME_FORMAT = \"N j, Y, P\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"F j\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y P\"\nFIRST_DAY_OF_WEEK = 0\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#str", "suffix": "25 Oct 2006'\n \"%d %b, %Y\", # '25 Oct, 2006'\n \"%B %d %Y\", # 'October 25 2006'\n \"%B %d, %Y\", # 'October 25, 2006'\n \"%d %B %Y\", # '25 October 2006'\n \"%d %B, %Y\", # '25 October, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", #", "middle": "ftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%m/%d/%Y\", # '10/25/2006'\n \"%m/%d/%y\", # '10/25/06'\n \"%b %d %Y\", # 'Oct 25 2006'\n \"%b %d, %Y\", # 'Oct 25, 2006'\n \"%d %b %Y\", # '", "meta": {"filepath": "django/conf/locale/ht/formats.py", "language": "python", "file_size": 1645, "cut_index": 537, "middle_length": 229}} +{"prefix": " This file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j. F Y G:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y G:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://d", "suffix": ". %b. %Y\", # '25. Oct. 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATO", "middle": "ocs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%y-%m-%d\", # '06-10-25'\n # \"%d. %B %Y\", # '25. October 2006'\n # \"%d", "meta": {"filepath": "django/conf/locale/sk/formats.py", "language": "python", "file_size": 1051, "cut_index": 513, "middle_length": 229}} +{"prefix": "# This file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"d F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"d F\"\nSHORT_DATE_FORMAT = \"d M Y\"\nSHORT_DATETIME_FORMAT = \"d M Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Pazartesi\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://", "suffix": " %Y\", # '25 Eki. 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30:59.000200'\n \"%d/%m/%Y %H:%M\", # '25/10/2006 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \".", "middle": "docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n \"%y-%m-%d\", # '06-10-25'\n # \"%d %B %Y\", # '25 Ekim 2006'\n # \"%d %b.", "meta": {"filepath": "django/conf/locale/tr/formats.py", "language": "python", "file_size": 1019, "cut_index": 512, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j M Y\" # '25 Oct 2006'\nTIME_FORMAT = \"P\" # '2:30 p.m.'\nDATETIME_FORMAT = \"j M Y, P\" # '25 Oct 2006, 2:30 p.m.'\nYEAR_MONTH_FORMAT = \"F Y\" # 'October 2006'\nMONTH_DAY_FORMAT = \"j F\" # '25 October'\nSHORT_DATE_FORMAT = \"d/m/Y\" # '25/10/2006'\nSHORT_DATETIME_FORMAT = \"d/m/Y P\" # '25/10/2006 2:30 p.m.'\nFIRST_DAY_OF_", "suffix": "d/%m/%y\", # '25/10/06'\n # \"%b %d %Y\", # 'Oct 25 2006'\n # \"%b %d, %Y\", # 'Oct 25, 2006'\n # \"%d %b %Y\", # '25 Oct 2006'\n # \"%d %b, %Y\", # '25 Oct, 2006'\n # \"%B %d %Y\", # 'October 25 2006'\n # \"%B %d, %Y\", # 'October 25, 2006'\n # \"%", "middle": "WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%", "meta": {"filepath": "django/conf/locale/en_GB/formats.py", "language": "python", "file_size": 1650, "cut_index": 537, "middle_length": 229}} +{"prefix": " This file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j F Y, G:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"j M Y\"\nSHORT_DATETIME_FORMAT = \"j M Y, G:i\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://do", "suffix": "30:59\n \"%H:%M:%S.%f\", # 14:30:59.000200\n \"%H:%M\", # 14:30\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # 25/10/2006 14:30:59\n \"%d/%m/%Y %H:%M:%S.%f\", # 25/10/2006 14:30:59.000200\n \"%d/%m/%Y %H:%M\", # 25/10/2006 14:30\n]\nDECIMAL_SEP", "middle": "cs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # 25/10/2006\n \"%d %b %Y\", # 25 ต.ค. 2006\n \"%d %B %Y\", # 25 ตุลาคม 2006\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # 14:", "meta": {"filepath": "django/conf/locale/th/formats.py", "language": "python", "file_size": 1072, "cut_index": 513, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org", "suffix": " \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30:59.000", "middle": "/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n]\nDATETIME_INPUT_FORMATS = [\n ", "meta": {"filepath": "django/conf/locale/fr_CH/formats.py", "language": "python", "file_size": 1320, "cut_index": 524, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"Y年n月j日\" # 2016年9月5日\nTIME_FORMAT = \"H:i\" # 20:45\nDATETIME_FORMAT = \"Y年n月j日 H:i\" # 2016年9月5日 20:45\nYEAR_MONTH_FORMAT = \"Y年n月\" # 2016年9月\nMONTH_DAY_FORMAT = \"m月j日\" # 9月5日\nSHORT_DATE_FORMAT = \"Y年n月j日\" # 2016年9月5日\nSHORT_DATETIME_FORMAT = \"Y年n月j日 H:i\" # 2016年9月5日 20:45\nFIRST_DAY_OF_WEEK = 1 # 星期一 (Mon", "suffix": "2016-09-05'\n \"%Y年%n月%j日\", # '2016年9月5日'\n]\n\nTIME_INPUT_FORMATS = [\n \"%H:%M\", # '20:45'\n \"%H:%M:%S\", # '20:45:29'\n \"%H:%M:%S.%f\", # '20:45:29.000200'\n]\n\nDATETIME_INPUT_FORMATS = [\n \"%Y/%m/%d %H:%M\", # '2016/09/05 20:45'\n \"%Y-%m-%d %H:%", "middle": "day)\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y/%m/%d\", # '2016/09/05'\n \"%Y-%m-%d\", # '", "meta": {"filepath": "django/conf/locale/zh_Hans/formats.py", "language": "python", "file_size": 1598, "cut_index": 524, "middle_length": 229}} +{"prefix": "his file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"P\"\nDATETIME_FORMAT = \"j F Y P\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.pytho", "suffix": ".%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n \"%d.%m.%y %H:%M\", #", "middle": "n.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m", "meta": {"filepath": "django/conf/locale/ig/formats.py", "language": "python", "file_size": 1119, "cut_index": 515, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d/m/Y\"\nTIME_FORMAT = \"P\"\nDATETIME_FORMAT = \"d/m/Y P\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y P\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org", "suffix": "0/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30:59.000200'\n \"%d/%m/%Y %H:%M\", # '25/10/2006 14:30'\n \"%d/%m/%y %H:%M:%S\", # '25/10/06 14:30:59'\n \"%d/%m/%y %H:%M:%S.%f\", # '25/10/06 14:30:59.000200'\n \"%d/%m/%y %H:%M\", # '25/", "middle": "/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n \"%Y-%m-%d\", # '2006-10-25'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # '25/1", "meta": {"filepath": "django/conf/locale/el/formats.py", "language": "python", "file_size": 1241, "cut_index": 518, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j M Y\" # '25 Oct 2006'\nTIME_FORMAT = \"P\" # '2:30 p.m.'\nDATETIME_FORMAT = \"j M Y, P\" # '25 Oct 2006, 2:30 p.m.'\nYEAR_MONTH_FORMAT = \"F Y\" # 'October 2006'\nMONTH_DAY_FORMAT = \"j F\" # '25 October'\nSHORT_DATE_FORMAT = \"d/m/Y\" # '25/10/2006'\nSHORT_DATETIME_FORMAT = \"d/m/Y P\" # '25/10/2006 2:30 p.m.'\nFIRST_DAY_OF_", "suffix": "d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n \"%d %b %Y\", # '25 Oct 2006'\n \"%d %b, %Y\", # '25 Oct, 2006'\n \"%d %B %Y\", # '25 October 2006'\n \"%d %B, %Y\", # '25 October, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", #", "middle": "WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%", "meta": {"filepath": "django/conf/locale/ms/formats.py", "language": "python", "file_size": 1522, "cut_index": 537, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/d", "suffix": "25. okt 2006'\n # \"%d %b %Y\", # '25 okt 2006'\n # \"%d. %b. %Y\", # '25. okt. 2006'\n # \"%d %b. %Y\", # '25 okt. 2006'\n # \"%d. %B %Y\", # '25. oktober 2006'\n # \"%d %B %Y\", # '25 oktober 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S", "middle": "atetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n # \"%d. %b %Y\", # '", "meta": {"filepath": "django/conf/locale/nb/formats.py", "language": "python", "file_size": 1552, "cut_index": 537, "middle_length": 229}} +{"prefix": "e same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"j F Y\"\nSHORT_DATETIME_FORMAT = \"j F Y H:i\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#", "suffix": " \"%Y/%m/%d\", # '2006/10/25'\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M\", # '14:30\n \"%H:%M:%S\", # '14:30:59'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y/%m/%d %H:%M\", # '2006/10/25 14:30'\n \"%Y/%m/%d %H:%M:%S\", # '2006/10/25 14:30:59'\n]\nDECIMAL_SEPARATOR = \",\"", "middle": "strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n ", "meta": {"filepath": "django/conf/locale/ar_DZ/formats.py", "language": "python", "file_size": 901, "cut_index": 547, "middle_length": 52}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j N Y\"\nDATETIME_FORMAT = \"j N Y, G.i\"\nTIME_FORMAT = \"G.i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d-m-Y\"\nSHORT_DATETIME_FORMAT = \"d-m-Y G.i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/dat", "suffix": " %Y\", # '25 October 2006'\n \"%m/%d/%y\", # '10/25/06'\n \"%m/%d/%Y\", # '10/25/2009'\n]\n\nTIME_INPUT_FORMATS = [\n \"%H.%M.%S\", # '14.30.59'\n \"%H.%M\", # '14.30'\n]\n\nDATETIME_INPUT_FORMATS = [\n \"%d-%m-%Y %H.%M.%S\", # '25-10-2009 14.30.59'\n \"%d", "middle": "etime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d-%m-%Y\", # '25-10-2009'\n \"%d/%m/%Y\", # '25/10/2009'\n \"%d-%m-%y\", # '25-10-09'\n \"%d/%m/%y\", # '25/10/09'\n \"%d %b %Y\", # '25 Oct 2006',\n \"%d %B", "meta": {"filepath": "django/conf/locale/id/formats.py", "language": "python", "file_size": 1644, "cut_index": 537, "middle_length": 229}} +{"prefix": "s the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\n\n# Formatting for date objects.\nDATE_FORMAT = \"N j, Y\"\n# Formatting for time objects.\nTIME_FORMAT = \"P\"\n# Formatting for datetime objects.\nDATETIME_FORMAT = \"N j, Y, P\"\n# Formatting for date objects when only the year and month are relevant.\nYEAR_MONTH_FORMAT = \"F Y\"\n# Formatting for date objects when only the month and day are relevant.\nMONTH_DAY_FORMAT ", "suffix": "\nFIRST_DAY_OF_WEEK = 0\n\n# Formats to be used when parsing dates from input boxes, in order.\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\n# Note that thes", "middle": "= \"F j\"\n# Short formatting for date objects.\nSHORT_DATE_FORMAT = \"m/d/Y\"\n# Short formatting for datetime objects.\nSHORT_DATETIME_FORMAT = \"m/d/Y P\"\n# First day of week, to be used on calendars.\n# 0 means Sunday, 1 means Monday...", "meta": {"filepath": "django/conf/locale/en/formats.py", "language": "python", "file_size": 2438, "cut_index": 563, "middle_length": 229}} +{"prefix": "e.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F, Y\"\nTIME_FORMAT = \"g:i A\"\n# DATETIME_FORMAT =\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"j M, Y\"\n# SHORT_DATETIME_FORMAT =\nFIRST_DAY_OF_WEEK = 6 # Saturday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [", "suffix": "/10/16\n \"%d-%m-%Y\", # 25-10-2016\n \"%d-%m-%y\", # 25-10-16\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # 14:30:59\n \"%H:%M\", # 14:30\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # 25/10/2006 14:30:59\n \"%d/%m/%Y %H:%M\", # 25/10/2006 14:", "middle": "\n \"%d/%m/%Y\", # 25/10/2016\n \"%d/%m/%y\", # 25", "meta": {"filepath": "django/conf/locale/bn/formats.py", "language": "python", "file_size": 964, "cut_index": 582, "middle_length": 52}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y г.\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j E Y г. G:i\"\nYEAR_MONTH_FORMAT = \"F Y г.\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://", "suffix": " \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n \"%d.%m.%y ", "middle": "docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n", "meta": {"filepath": "django/conf/locale/tk/formats.py", "language": "python", "file_size": 1160, "cut_index": 518, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j \\d\\e F \\d\\e Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = r\"j \\d\\e F \\d\\e Y à\\s H:i\"\nYEAR_MONTH_FORMAT = r\"F \\d\\e Y\"\nMONTH_DAY_FORMAT = r\"j \\d\\e F\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# se", "suffix": " '25/10/06'\n # \"%d de %b de %Y\", # '25 de Out de 2006'\n # \"%d de %b, %Y\", # '25 Out, 2006'\n # \"%d de %B de %Y\", # '25 de Outubro de 2006'\n # \"%d de %B, %Y\", # '25 de Outubro, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2", "middle": "e https://docs.python.org/library/datetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", #", "meta": {"filepath": "django/conf/locale/pt/formats.py", "language": "python", "file_size": 1520, "cut_index": 537, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y. H:i\"\nYEAR_MONTH_FORMAT = \"F Y.\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j.m.Y.\"\nSHORT_DATETIME_FORMAT = \"j.m.Y. H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/dateti", "suffix": " 06.'\n # \"%d. %B %y.\", # '25. October 06.'\n # \"%d. %b '%y.\", # '25. Oct '06.'\n # \"%d. %B '%y.\", #'25. October '06.'\n # \"%d. %b %Y.\", # '25. Oct 2006.'\n # \"%d. %B %Y.\", # '25. October 2006.'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y. %H", "middle": "me.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y.\", # '25.10.2006.'\n \"%d.%m.%y.\", # '25.10.06.'\n \"%d. %m. %Y.\", # '25. 10. 2006.'\n \"%d. %m. %y.\", # '25. 10. 06.'\n # \"%d. %b %y.\", # '25. Oct", "meta": {"filepath": "django/conf/locale/sr_Latn/formats.py", "language": "python", "file_size": 1728, "cut_index": 537, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\n\nDATE_FORMAT = \"j M Y\" # 25 Oct 2006\nTIME_FORMAT = \"P\" # 2:30 p.m.\nDATETIME_FORMAT = \"j M Y, P\" # 25 Oct 2006, 2:30 p.m.\nYEAR_MONTH_FORMAT = \"F Y\" # October 2006\nMONTH_DAY_FORMAT = \"j F\" # 25 October\nSHORT_DATE_FORMAT = \"Y-m-d\"\nSHORT_DATETIME_FORMAT = \"Y-m-d P\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPU", "suffix": "ME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-05-15 14:30:57'\n \"%y-%m-%d %H:%M:%S\", # '06-05-15 14:30:57'\n \"%Y-%m-%d %H:%M:%S.%f\", # '2006-05-15 14:30:57.000200'\n \"%y-%m-%d %H:%M:%S.%f\", # '06-05-15 14:30:57.000200'\n \"%Y-%m-%d %H:%M", "middle": "T_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-05-15'\n \"%y-%m-%d\", # '06-05-15'\n]\nDATETI", "meta": {"filepath": "django/conf/locale/en_CA/formats.py", "language": "python", "file_size": 1166, "cut_index": 518, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j.m.Y\"\nSHORT_DATETIME_FORMAT = \"j.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library", "suffix": " \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200", "middle": "/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%d. %m. %Y\", # '25. 10. 2006'\n \"%d. %m. %y\", # '25. 10. 06'\n]\n\nDATETIME_INPUT_FORMATS = [\n ", "meta": {"filepath": "django/conf/locale/mk/formats.py", "language": "python", "file_size": 1451, "cut_index": 524, "middle_length": 229}} +{"prefix": "his file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j E Y, G:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.", "suffix": "%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n \"%d.%m.%y %H:%M\", # '25.10.06 14:30'\n]\nDECIMAL", "middle": "python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"", "meta": {"filepath": "django/conf/locale/az/formats.py", "language": "python", "file_size": 1087, "cut_index": 515, "middle_length": 229}} +{"prefix": " This file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j E Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j E\"\nSHORT_DATE_FORMAT = \"d-m-Y\"\nSHORT_DATETIME_FORMAT = \"d-m-Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://doc", "suffix": "\"%d. %b. %Y\", # '25. paź. 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPAR", "middle": "s.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%y-%m-%d\", # '06-10-25'\n # \"%d. %B %Y\", # '25. października 2006'\n # ", "meta": {"filepath": "django/conf/locale/pl/formats.py", "language": "python", "file_size": 1032, "cut_index": 513, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y г.\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j E Y г. G:i\"\nYEAR_MONTH_FORMAT = \"F Y г.\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://", "suffix": " \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n \"%d.%m.%y ", "middle": "docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n", "meta": {"filepath": "django/conf/locale/tg/formats.py", "language": "python", "file_size": 1160, "cut_index": 518, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"N j, Y\"\nTIME_FORMAT = \"P\"\nDATETIME_FORMAT = \"N j, Y, P\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"F j\"\nSHORT_DATE_FORMAT = \"m/d/Y\"\nSHORT_DATETIME_FORMAT = \"m/d/Y P\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetim", "suffix": "2006'\n # \"%b %d, %Y\", # 'Oct 25, 2006'\n # \"%d %b %Y\", # '25 Oct 2006'\n # \"%d %b, %Y\", # '25 Oct, 2006'\n # \"%B %d %Y\", # 'October 25 2006'\n # \"%B %d, %Y\", # 'October 25, 2006'\n # \"%d %B %Y\", # '25 October 2006'\n # \"%d %B, %Y\", # ", "middle": "e.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%m/%d/%Y\", # '10/25/2006'\n \"%m/%d/%y\", # '10/25/06'\n # \"%b %d %Y\", # 'Oct 25 ", "meta": {"filepath": "django/conf/locale/ml/formats.py", "language": "python", "file_size": 1597, "cut_index": 537, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"Y年n月j日\" # 2016年9月5日\nTIME_FORMAT = \"H:i\" # 20:45\nDATETIME_FORMAT = \"Y年n月j日 H:i\" # 2016年9月5日 20:45\nYEAR_MONTH_FORMAT = \"Y年n月\" # 2016年9月\nMONTH_DAY_FORMAT = \"m月j日\" # 9月5日\nSHORT_DATE_FORMAT = \"Y年n月j日\" # 2016年9月5日\nSHORT_DATETIME_FORMAT = \"Y年n月j日 H:i\" # 2016年9月5日 20:45\nFIRST_DAY_OF_WEEK = 1 # 星期一 (Mon", "suffix": "2016-09-05'\n \"%Y年%n月%j日\", # '2016年9月5日'\n]\n\nTIME_INPUT_FORMATS = [\n \"%H:%M\", # '20:45'\n \"%H:%M:%S\", # '20:45:29'\n \"%H:%M:%S.%f\", # '20:45:29.000200'\n]\n\nDATETIME_INPUT_FORMATS = [\n \"%Y/%m/%d %H:%M\", # '2016/09/05 20:45'\n \"%Y-%m-%d %H:%", "middle": "day)\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%Y/%m/%d\", # '2016/09/05'\n \"%Y-%m-%d\", # '", "meta": {"filepath": "django/conf/locale/zh_Hant/formats.py", "language": "python", "file_size": 1598, "cut_index": 524, "middle_length": 229}} +{"prefix": "ngs use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j E \\d\\e Y\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = r\"j E \\d\\e Y \\a \\l\\e\\s G:i\"\nYEAR_MONTH_FORMAT = r\"F \\d\\e\\l Y\"\nMONTH_DAY_FORMAT = r\"j E\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y G:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nD", "suffix": "'\n \"%d/%m/%y\", # '31/12/09'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\",\n \"%d/%m/%Y %H:%M:%S.%f\",\n \"%d/%m/%Y %H:%M\",\n \"%d/%m/%y %H:%M:%S\",\n \"%d/%m/%y %H:%M:%S.%f\",\n \"%d/%m/%y %H:%M\",\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR ", "middle": "ATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '31/12/2009", "meta": {"filepath": "django/conf/locale/ca/formats.py", "language": "python", "file_size": 940, "cut_index": 606, "middle_length": 52}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j-E, Y-\\y\\i\\l\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = r\"j-E, Y-\\y\\i\\l G:i\"\nYEAR_MONTH_FORMAT = r\"F Y-\\y\\i\\l\"\nMONTH_DAY_FORMAT = \"j-E\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format synta", "suffix": "%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d-%B, %Y-yil %H:%M:%S\", # '25-Oktabr, 2006-yil 14:30:59'\n \"%d-%B, %Y-yil %H:%M:%S.%f\", # '25-Oktabr, 2006-yi", "middle": "x,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d-%B, %Y-yil\", # '25-Oktabr, 2006-yil'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:", "meta": {"filepath": "django/conf/locale/uz/formats.py", "language": "python", "file_size": 1176, "cut_index": 518, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/d", "suffix": "25. okt 2006'\n # \"%d %b %Y\", # '25 okt 2006'\n # \"%d. %b. %Y\", # '25. okt. 2006'\n # \"%d %b. %Y\", # '25 okt. 2006'\n # \"%d. %B %Y\", # '25. oktober 2006'\n # \"%d %B %Y\", # '25 oktober 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S", "middle": "atetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n # \"%d. %b %Y\", # '", "meta": {"filepath": "django/conf/locale/nn/formats.py", "language": "python", "file_size": 1552, "cut_index": 537, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j F Y\" # '25 Hydref 2006'\nTIME_FORMAT = \"P\" # '2:30 y.b.'\nDATETIME_FORMAT = \"j F Y, P\" # '25 Hydref 2006, 2:30 y.b.'\nYEAR_MONTH_FORMAT = \"F Y\" # 'Hydref 2006'\nMONTH_DAY_FORMAT = \"j F\" # '25 Hydref'\nSHORT_DATE_FORMAT = \"d/m/Y\" # '25/10/2006'\nSHORT_DATETIME_FORMAT = \"d/m/Y P\" # '25/10/2006 2:30 y.", "suffix": " # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y-%m-%d %H:%M:%S\", # '2006-10-25 14:30:59'\n \"%Y-%m-%d %H:%M:%S.%f\", # '2006-10-25 14:30:59.000200'\n \"%Y-%m-%d %H:%M\", # '2006-10-25 14:30'\n \"%d/%m/%Y %H:%M:%S\", #", "middle": "b.'\nFIRST_DAY_OF_WEEK = 1 # 'Dydd Llun'\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", ", "meta": {"filepath": "django/conf/locale/cy/formats.py", "language": "python", "file_size": 1355, "cut_index": 524, "middle_length": 229}} +{"prefix": "FieldMixin):\n \"A Field plus data\"\n\n def __init__(self, form, field, name):\n self.form = form\n self.field = field\n self.name = name\n self.html_name = form.add_prefix(name)\n self.html_initial_name = form.add_initial_prefix(name)\n self.html_initial_id = form.add_initial_prefix(self.auto_id)\n if self.field.label is None:\n self.label = pretty_name(name)\n else:\n self.label = self.field.label\n self.help_text = field.help_tex", "suffix": "ubwidget for each choice.\n\n This property is cached so that only one database query occurs when\n rendering ModelChoiceFields.\n \"\"\"\n id_ = self.field.widget.attrs.get(\"id\") or self.auto_id\n attrs = {\"id\": id_} if id_ else ", "middle": "t or \"\"\n self.renderer = form.renderer\n\n @cached_property\n def subwidgets(self):\n \"\"\"\n Most widgets yield a single subwidget, but others like RadioSelect and\n CheckboxSelectMultiple produce one s", "meta": {"filepath": "django/forms/boundfield.py", "language": "python", "file_size": 13373, "cut_index": 921, "middle_length": 229}} +{"prefix": "utils.translation import gettext as _\n\nfrom .renderers import get_default_renderer\n\n__all__ = (\"BaseForm\", \"Form\")\n\n\nclass DeclarativeFieldsMetaclass(MediaDefiningClass):\n \"\"\"Collect Fields declared on the base classes.\"\"\"\n\n def __new__(mcs, name, bases, attrs):\n # Collect fields from current class and remove them from attrs.\n attrs[\"declared_fields\"] = {\n key: attrs.pop(key)\n for key, value in list(attrs.items())\n if isinstance(value, Field)\n }\n\n ", "suffix": "if hasattr(base, \"declared_fields\"):\n declared_fields.update(base.declared_fields)\n\n # Field shadowing.\n for attr, value in base.__dict__.items():\n if value is None and attr in declared_fields:\n ", "middle": " new_class = super().__new__(mcs, name, bases, attrs)\n\n # Walk through the MRO.\n declared_fields = {}\n for base in reversed(new_class.__mro__):\n # Collect fields from base class.\n ", "meta": {"filepath": "django/forms/forms.py", "language": "python", "file_size": 16112, "cut_index": 921, "middle_length": 229}} +{"prefix": " file_field_list = []\n for f in opts.fields:\n if (\n not f.editable\n or isinstance(f, models.AutoField)\n or f.name not in cleaned_data\n ):\n continue\n if fields is not None and f.name not in fields:\n continue\n if exclude and f.name in exclude:\n continue\n # Leave defaults for fields that aren't in POST data, except for\n # checkbox inputs because they don't appear in POST data if not\n # checked", "suffix": "n form[f.name].field.empty_values\n ):\n continue\n # Defer saving file-type fields until after the other fields, so a\n # callable upload_to can use the values from other fields.\n if isinstance(f, models.FileField):\n ", "middle": ".\n if (\n f.has_default()\n and form[f.name].field.widget.value_omitted_from_data(\n form.data, form.files, form.add_prefix(f.name)\n )\n and cleaned_data.get(f.name) i", "meta": {"filepath": "django/forms/models.py", "language": "python", "file_size": 62211, "cut_index": 2151, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j\\-\\a \\d\\e F Y\" # '26-a de julio 1887'\nTIME_FORMAT = \"H:i\" # '18:59'\nDATETIME_FORMAT = r\"j\\-\\a \\d\\e F Y\\, \\j\\e H:i\" # '26-a de julio 1887, je 18:59'\nYEAR_MONTH_FORMAT = r\"F \\d\\e Y\" # 'julio de 1887'\nMONTH_DAY_FORMAT = r\"j\\-\\a \\d\\e F\" # '26-a de julio'\nSHORT_DATE_FORMAT = \"Y-m-d\" # '1887-07-26'\nSHORT_DATETIME", "suffix": "ior\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '1887-07-26'\n \"%y-%m-%d\", # '87-07-26'\n \"%Y %m %d\", # '1887 07 26'\n \"%Y.%m.%d\", # '1887.07.26'\n \"%d-a de %b %Y\", # '26-a de jul 1887'\n \"%d %b %Y\", # '26 jul 1887'\n \"%d-a de %B %Y\", # '26", "middle": "_FORMAT = \"Y-m-d H:i\" # '1887-07-26 18:59'\nFIRST_DAY_OF_WEEK = 1 # Monday (lundo)\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behav", "meta": {"filepath": "django/conf/locale/eo/formats.py", "language": "python", "file_size": 1715, "cut_index": 537, "middle_length": 229}} +{"prefix": "his file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j E Y г.\"\nTIME_FORMAT = \"G:i\"\nDATETIME_FORMAT = \"j E Y г. G:i\"\nYEAR_MONTH_FORMAT = \"F Y г.\"\nMONTH_DAY_FORMAT = \"j F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https", "suffix": "9'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '25.10.06 14:30:59.000200'\n \"%d.%m.%y %H:%M\", # '25.10.06 14:30'\n]", "middle": "://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:5", "meta": {"filepath": "django/conf/locale/ru/formats.py", "language": "python", "file_size": 1098, "cut_index": 515, "middle_length": 229}} +{"prefix": " file is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.p", "suffix": "ETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n]\n\n# Swiss number formatting can vary based on context (e.g. Fr. 23.50 vs 22,5", "middle": "ython.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n # \"%d. %B %Y\", # '25. October 2006'\n # \"%d. %b. %Y\", # '25. Oct. 2006'\n]\nDAT", "meta": {"filepath": "django/conf/locale/de_CH/formats.py", "language": "python", "file_size": 1187, "cut_index": 518, "middle_length": 229}} +{"prefix": "se as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-b", "suffix": "5.10.2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n]\nDECIMAL_SEPARATOR = \",\"\nTHOUSAND_SEPARATOR = \".\"\nNUMBER_GROU", "middle": "ehavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '2", "meta": {"filepath": "django/conf/locale/da/formats.py", "language": "python", "file_size": 876, "cut_index": 559, "middle_length": 52}} +{"prefix": "e.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j \\d\\e F \\d\\e Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = r\"j \\d\\e F \\d\\e Y \\a \\l\\a\\s H:i\"\nYEAR_MONTH_FORMAT = r\"F \\d\\e Y\"\nMONTH_DAY_FORMAT = r\"j \\d\\e F\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datet", "suffix": "TS = [\n \"%d/%m/%Y\", # '31/12/2009'\n \"%d/%m/%y\", # '31/12/09'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\",\n \"%d/%m/%Y %H:%M:%S.%f\",\n \"%d/%m/%Y %H:%M\",\n \"%d/%m/%y %H:%M:%S\",\n \"%d/%m/%y %H:%M:%S.%f\",\n \"%d/%m/%y %H:%M\",\n]\nDECIMA", "middle": "ime.html#strftime-strptime-behavior\nDATE_INPUT_FORMA", "meta": {"filepath": "django/conf/locale/es/formats.py", "language": "python", "file_size": 978, "cut_index": 582, "middle_length": 52}} +{"prefix": " \"MultipleChoiceField\",\n \"ComboField\",\n \"MultiValueField\",\n \"FloatField\",\n \"DecimalField\",\n \"SplitDateTimeField\",\n \"GenericIPAddressField\",\n \"FilePathField\",\n \"JSONField\",\n \"SlugField\",\n \"TypedChoiceField\",\n \"TypedMultipleChoiceField\",\n \"UUIDField\",\n)\n\n\nclass Field:\n widget = TextInput # Default widget to use when rendering this type of Field.\n hidden_widget = (\n HiddenInput # Default widget to use when rendering this as \"hidden\".\n )\n default_validat", "suffix": "(\"This field is required.\"),\n }\n empty_values = list(validators.EMPTY_VALUES)\n bound_field_class = None\n\n def __init__(\n self,\n *,\n required=True,\n widget=None,\n label=None,\n initial=None,\n help_", "middle": "ors = [] # Default set of validators\n # Add an 'invalid' entry to default_error_message if you want a specific\n # field error message not raised by the field validators.\n default_error_messages = {\n \"required\": _", "meta": {"filepath": "django/forms/fields.py", "language": "python", "file_size": 48981, "cut_index": 2151, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j M Y\" # '25 Oct 2006'\nTIME_FORMAT = \"P\" # '2:30 p.m.'\nDATETIME_FORMAT = \"j M Y, P\" # '25 Oct 2006, 2:30 p.m.'\nYEAR_MONTH_FORMAT = \"F Y\" # 'October 2006'\nMONTH_DAY_FORMAT = \"j F\" # '25 October'\nSHORT_DATE_FORMAT = \"d/m/Y\" # '25/10/2006'\nSHORT_DATETIME_FORMAT = \"d/m/Y P\" # '25/10/2006 2:30 p.m.'\nFIRST_DAY_OF_", "suffix": "d/%m/%y\", # '25/10/06'\n # \"%b %d %Y\", # 'Oct 25 2006'\n # \"%b %d, %Y\", # 'Oct 25, 2006'\n # \"%d %b %Y\", # '25 Oct 2006'\n # \"%d %b, %Y\", # '25 Oct, 2006'\n # \"%B %d %Y\", # 'October 25 2006'\n # \"%B %d, %Y\", # 'October 25, 2006'\n # \"%", "middle": "WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%", "meta": {"filepath": "django/conf/locale/en_AU/formats.py", "language": "python", "file_size": 1650, "cut_index": 537, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"Y. \\g\\a\\d\\a j. F\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = r\"Y. \\g\\a\\d\\a j. F, H:i\"\nYEAR_MONTH_FORMAT = r\"Y. \\g. F\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = r\"j.m.Y\"\nSHORT_DATETIME_FORMAT = \"j.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see htt", "suffix": "10.06'\n]\nTIME_INPUT_FORMATS = [\n \"%H:%M:%S\", # '14:30:59'\n \"%H:%M:%S.%f\", # '14:30:59.000200'\n \"%H:%M\", # '14:30'\n \"%H.%M.%S\", # '14.30.59'\n \"%H.%M.%S.%f\", # '14.30.59.000200'\n \"%H.%M\", # '14.30'\n]\nDATETIME_INPUT_FORMATS = [\n \"%Y", "middle": "ps://docs.python.org/library/datetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n \"%Y-%m-%d\", # '2006-10-25'\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.", "meta": {"filepath": "django/conf/locale/lv/formats.py", "language": "python", "file_size": 1713, "cut_index": 537, "middle_length": 229}} +{"prefix": "is distributed under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = r\"j \\d\\e F \\d\\e Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = r\"j \\d\\e F \\d\\e Y à\\s H:i\"\nYEAR_MONTH_FORMAT = r\"F \\d\\e Y\"\nMONTH_DAY_FORMAT = r\"j \\d\\e F\"\nSHORT_DATE_FORMAT = \"d/m/Y\"\nSHORT_DATETIME_FORMAT = \"d/m/Y H:i\"\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format", "suffix": " de %b, %Y\", # '25 Out, 2006'\n # \"%d de %B de %Y\", # '25 de Outubro de 2006'\n # \"%d de %B, %Y\", # '25 de Outubro, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M:%S.%f\", # '25/10/2006 14:30", "middle": " syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d/%m/%Y\", # '25/10/2006'\n \"%d/%m/%y\", # '25/10/06'\n # \"%d de %b de %Y\", # '24 de Out de 2006'\n # \"%d", "meta": {"filepath": "django/conf/locale/pt_BR/formats.py", "language": "python", "file_size": 1285, "cut_index": 524, "middle_length": 229}} +{"prefix": " a formset\nDEFAULT_MIN_NUM = 0\n\n# default maximum number of forms in a formset, to prevent memory exhaustion\nDEFAULT_MAX_NUM = 1000\n\n\nclass ManagementForm(Form):\n \"\"\"\n Keep track of how many form instances are displayed on the page. If adding\n new forms via JavaScript, you should increment the count field of this form\n as well.\n \"\"\"\n\n TOTAL_FORMS = IntegerField(widget=HiddenInput)\n INITIAL_FORMS = IntegerField(widget=HiddenInput)\n # MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are outpu", "suffix": "nput)\n MAX_NUM_FORMS = IntegerField(required=False, widget=HiddenInput)\n\n def clean(self):\n cleaned_data = super().clean()\n # When the management form is invalid, we don't know how many forms\n # were submitted.\n cleaned_da", "middle": "t with the rest of the\n # management form, but only for the convenience of client-side code. The\n # POST value of them returned from the client is not checked.\n MIN_NUM_FORMS = IntegerField(required=False, widget=HiddenI", "meta": {"filepath": "django/forms/formsets.py", "language": "python", "file_size": 21324, "cut_index": 1331, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y.\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y. H:i\"\nYEAR_MONTH_FORMAT = \"F Y.\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j.m.Y.\"\nSHORT_DATETIME_FORMAT = \"j.m.Y. H:i\"\nFIRST_DAY_OF_WEEK = 1\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/dateti", "suffix": " 06.'\n # \"%d. %B %y.\", # '25. October 06.'\n # \"%d. %b '%y.\", # '25. Oct '06.'\n # \"%d. %B '%y.\", # '25. October '06.'\n # \"%d. %b %Y.\", # '25. Oct 2006.'\n # \"%d. %B %Y.\", # '25. October 2006.'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y. %", "middle": "me.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y.\", # '25.10.2006.'\n \"%d.%m.%y.\", # '25.10.06.'\n \"%d. %m. %Y.\", # '25. 10. 2006.'\n \"%d. %m. %y.\", # '25. 10. 06.'\n # \"%d. %b %y.\", # '25. Oct", "meta": {"filepath": "django/conf/locale/sr/formats.py", "language": "python", "file_size": 1729, "cut_index": 537, "middle_length": 229}} +{"prefix": "import timezone\nfrom django.utils.html import escape, format_html_join\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import gettext_lazy as _\n\n\ndef pretty_name(name):\n \"\"\"Convert 'first_name' to 'First name'.\"\"\"\n if not name:\n return \"\"\n return name.replace(\"_\", \" \").capitalize()\n\n\ndef flatatt(attrs):\n \"\"\"\n Convert a dictionary of attributes to a single string.\n The returned string will contain a leading space followed by key=\"value\",\n XML-style pair", "suffix": "sed through 'mark_safe' (by way of 'format_html_join').\n \"\"\"\n key_value_attrs = []\n boolean_attrs = []\n for attr, value in attrs.items():\n if isinstance(value, bool):\n if value:\n boolean_attrs.append((attr,))\n ", "middle": "s. In the case of a boolean value, the key will appear\n without a value. It is assumed that the keys do not need to be\n XML-escaped. If the passed dictionary is empty, then return an empty\n string.\n\n The result is pas", "meta": {"filepath": "django/forms/utils.py", "language": "python", "file_size": 7974, "cut_index": 716, "middle_length": 229}} +{"prefix": "alled_apps argument.\")\n\n # Mapping of app labels => model names => model classes. Every time a\n # model is imported, ModelBase.__new__ calls apps.register_model which\n # creates an entry in all_models. All imported models are registered,\n # regardless of whether they're defined in an installed application\n # and whether the registry has been populated. Since it isn't possible\n # to reimport a module safely (it could reexecute initialization code)\n # all_model", "suffix": "current state in\n # set_available_apps and set_installed_apps.\n self.stored_app_configs = []\n\n # Whether the registry is populated.\n self.apps_ready = self.models_ready = self.ready = False\n # For the autoreloader.\n ", "middle": "s is never overridden or reset.\n self.all_models = defaultdict(dict)\n\n # Mapping of labels to AppConfig instances for installed apps.\n self.app_configs = {}\n\n # Stack of app_configs. Used to store the ", "meta": {"filepath": "django/apps/registry.py", "language": "python", "file_size": 17707, "cut_index": 1331, "middle_length": 229}} +{"prefix": "d under the same license as the Django package.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"d. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y. H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"j. M. Y\"\nSHORT_DATETIME_FORMAT = \"j.n.Y. H:i\"\nFIRST_DAY_OF_WEEK = 0\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetim", "suffix": "IME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%m.%Y %H:%M\", # '25.10.2006 14:30'\n \"%d.%m.%y %H:%M:%S\", # '25.10.06 14:30:59'\n \"%d.%m.%y %H:%M:%S.%f\", # '", "middle": "e.html#strftime-strptime-behavior\nDATE_INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n \"%d.%m.%y\", # '25.10.06'\n \"%d-%m-%Y\", # '25-10-2006'\n \"%d. %m. %Y\", # '25. 10. 2006'\n \"%d. %m. %y\", # '25. 10. 06'\n]\n\nDATET", "meta": {"filepath": "django/conf/locale/sl/formats.py", "language": "python", "file_size": 1642, "cut_index": 537, "middle_length": 229}} +{"prefix": " cvar.set(cvalue)\n\n\nasync def _run_parallel(*coros):\n \"\"\"\n Execute multiple asynchronous coroutines in parallel,\n sharing the current context between them.\n \"\"\"\n context = contextvars.copy_context()\n\n if len(coros) == 0:\n return []\n\n async def run(i, coro):\n results[i] = await coro\n\n try:\n async with asyncio.TaskGroup() as tg:\n results = [None] * len(coros)\n for i, coro in enumerate(coros):\n tg.create_task(run(i, coro)", "suffix": "ore_context(context=context)\n\n\nclass Signal:\n \"\"\"\n Base class for all signals\n\n Internal attributes:\n\n receivers:\n [\n (\n (id(receiver), id(sender)),\n ref(receiver),\n ", "middle": ", context=context)\n return results\n except BaseExceptionGroup as exception_group:\n if len(exception_group.exceptions) == 1:\n raise exception_group.exceptions[0]\n raise\n finally:\n _rest", "meta": {"filepath": "django/dispatch/dispatcher.py", "language": "python", "file_size": 19563, "cut_index": 1331, "middle_length": 229}} +{"prefix": "t__(self, app_name, app_module):\n # Full Python path to the application e.g. 'django.contrib.admin'.\n self.name = app_name\n\n # Root module for the application e.g. .\n self.module = app_module\n\n # Reference to the Apps registry that holds this AppConfig. Set by the\n # registry when it registers the AppConfig instance.\n self.apps = None\n\n # The following attributes could be ", "suffix": " if not hasattr(self, \"label\"):\n self.label = app_name.rpartition(\".\")[2]\n if not self.label.isidentifier():\n raise ImproperlyConfigured(\n \"The app label '%s' is not a valid Python identifier.\" % self.label\n ", "middle": "defined at the class level in a\n # subclass, hence the test-and-set pattern.\n\n # Last component of the Python path to the application e.g. 'admin'.\n # This value must be unique across a Django project.\n ", "meta": {"filepath": "django/apps/config.py", "language": "python", "file_size": 11482, "cut_index": 921, "middle_length": 229}} +{"prefix": "e.\n#\n# The *_FORMAT strings use the Django date format syntax,\n# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = \"j. F Y\"\nTIME_FORMAT = \"H:i\"\nDATETIME_FORMAT = \"j. F Y H:i\"\nYEAR_MONTH_FORMAT = \"F Y\"\nMONTH_DAY_FORMAT = \"j. F\"\nSHORT_DATE_FORMAT = \"d.m.Y\"\nSHORT_DATETIME_FORMAT = \"d.m.Y H:i\"\nFIRST_DAY_OF_WEEK = 1 # Monday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior\nDATE_", "suffix": " \"%d.%m.%y\", # '25.10.06'\n # \"%d. %B %Y\", # '25. October 2006'\n # \"%d. %b. %Y\", # '25. Oct. 2006'\n]\nDATETIME_INPUT_FORMATS = [\n \"%d.%m.%Y %H:%M:%S\", # '25.10.2006 14:30:59'\n \"%d.%m.%Y %H:%M:%S.%f\", # '25.10.2006 14:30:59.000200'\n \"%d.%", "middle": "INPUT_FORMATS = [\n \"%d.%m.%Y\", # '25.10.2006'\n ", "meta": {"filepath": "django/conf/locale/de/formats.py", "language": "python", "file_size": 996, "cut_index": 582, "middle_length": 52}} +{"prefix": "r):\n # Compare path and attrs to ensure performant comparison\n # in Media.merge.\n return (\n self.__class__ is other.__class__\n and self._path == other._path\n and self.attributes == other.attributes\n ) or (isinstance(other, str) and self._path == other)\n\n def __hash__(self):\n # Compare path and attrs to ensure performant comparison\n # in Media.merge.\n if self.attributes:\n return hash(self._path) ^ hash(frozenset(s", "suffix": "e):\n if (\n attrs\n and self.attributes\n and (conflicts := attrs.keys() & self.attributes.keys())\n ):\n conflicts = \", \".join(sorted(conflicts))\n raise ValueError(\n f\"{self.__", "middle": "elf.attributes.items()))\n return hash(self._path)\n\n def __str__(self):\n return self.render()\n\n def __repr__(self):\n return f\"{type(self).__qualname__}({self._path!r})\"\n\n def render(self, *, attrs=Non", "meta": {"filepath": "django/forms/widgets.py", "language": "python", "file_size": 42431, "cut_index": 2151, "middle_length": 229}} +{"prefix": "rt Library, Node, TemplateSyntaxError\nfrom django.utils import formats\n\nregister = Library()\n\n\n@register.filter(is_safe=False)\ndef localize(value):\n \"\"\"\n Force a value to be rendered as a localized value.\n \"\"\"\n return str(formats.localize(value, use_l10n=True))\n\n\n@register.filter(is_safe=False)\ndef unlocalize(value):\n \"\"\"\n Force a value to be rendered as a non-localized value.\n \"\"\"\n return str(formats.localize(value, use_l10n=False))\n\n\nclass LocalizeNode(Node):\n def __init__(self,", "suffix": "0n\n context.use_l10n = self.use_l10n\n output = self.nodelist.render(context)\n context.use_l10n = old_setting\n return output\n\n\n@register.tag(\"localize\")\ndef localize_tag(parser, token):\n \"\"\"\n Force or prevents localization ", "middle": " nodelist, use_l10n):\n self.nodelist = nodelist\n self.use_l10n = use_l10n\n\n def __repr__(self):\n return \"<%s>\" % self.__class__.__name__\n\n def render(self, context):\n old_setting = context.use_l1", "meta": {"filepath": "django/templatetags/l10n.py", "language": "python", "file_size": 1563, "cut_index": 537, "middle_length": 229}} +{"prefix": " django.utils.encoding import iri_to_uri\nfrom django.utils.html import conditional_escape\n\nregister = template.Library()\n\n\nclass PrefixNode(template.Node):\n def __repr__(self):\n return \"\" % self.name\n\n def __init__(self, varname=None, name=None):\n if name is None:\n raise template.TemplateSyntaxError(\n \"Prefix nodes must be given a name to return.\"\n )\n self.varname = varname\n self.name = name\n\n @classmethod\n def h", "suffix": "variable as arguments.\n tokens = token.contents.split()\n if len(tokens) > 1 and tokens[1] != \"as\":\n raise template.TemplateSyntaxError(\n \"First argument in '%s' must be 'as'\" % tokens[0]\n )\n if len(", "middle": "andle_token(cls, parser, token, name):\n \"\"\"\n Class method to parse prefix node and return a Node.\n \"\"\"\n # token.split_contents() isn't useful here because tags using this\n # method don't accept ", "meta": {"filepath": "django/templatetags/static.py", "language": "python", "file_size": 4730, "cut_index": 614, "middle_length": 229}} +{"prefix": ", SafeString, mark_safe\nfrom django.utils.text import normalize_newlines\n\n# https://html.spec.whatwg.org/#void-elements\nVOID_ELEMENTS = frozenset(\n (\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n # Deprecated tags.\n \"frame\",\n \"spacer\",\n )\n)\n\nMAX_STRIP_TAGS_DEPTH = 50\n\n# HTML tag that opens but has no closi", "suffix": " for use in HTML.\n\n Always escape input, even if it's already escaped and marked as such.\n This may result in double-escaping. If this is a concern, use\n conditional_escape() instead.\n \"\"\"\n return SafeString(html.escape(str(text)))\n\n\n_js_", "middle": "ng \">\" after 1k+ chars.\nlong_open_tag_without_closing_re = _lazy_re_compile(r\"<[a-zA-Z][^>]{1000,}\")\n\n\n@keep_lazy(SafeString)\ndef escape(text):\n \"\"\"\n Return the given text with ampersands, quotes and angle brackets encoded\n", "meta": {"filepath": "django/utils/html.py", "language": "python", "file_size": 18534, "cut_index": 1331, "middle_length": 229}} +{"prefix": "n RFC 9110 Appendix A.\nETAG_MATCH = _lazy_re_compile(\n r\"\"\"\n \\A( # start of string and capture group\n (?:W/)? # optional weak indicator\n \" # opening quote\n [^\"]* # any sequence of non-quote characters\n \" # end quote\n )\\Z # end of string and capture group\n\"\"\",\n re.X,\n)\n\nMAX_HEADER_LENGTH = 10_000\nMONTHS = \"jan feb mar apr may jun jul aug sep oct nov dec\".split()\n__D = r\"(?P[0-9]{2})\"\n__D2 = r\"(?P[ 0-9][0-9])\"\n__M = r\"(?P\\w{3})\"\n__Y = r\"(?P[0-9]{4})\"\n__Y2 = r\"(?P[0-9]{2})\"\n__T = r\"(?P[0-9]{2}):(?P[0-9]{2}):(?P[0-9]{2})\"\nRFC1123_DATE = _lazy_re_compile(r\"^\\w{3}, %s %s %s %s GMT$\" % (__D, __M, __Y, __T))\nRFC850_DATE = _lazy_re_compile(r\"^\\w{6", "meta": {"filepath": "django/utils/http.py", "language": "python", "file_size": 14184, "cut_index": 921, "middle_length": 229}} +{"prefix": "ils.version import PY314, PY315\n\nif PY314:\n import annotationlib\n\n if not PY315:\n lock = threading.Lock()\n safe_signature_from_callable = functools.partial(\n inspect._signature_from_callable,\n annotation_format=annotationlib.Format.FORWARDREF,\n )\n\n\n@functools.lru_cache(maxsize=512)\ndef _get_func_parameters(func, remove_first):\n parameters = tuple(signature(func).parameters.values())\n if remove_first:\n parameters = parameters[1:]\n return parame", "suffix": "_KINDS = frozenset(\n {\n inspect.Parameter.POSITIONAL_ONLY,\n inspect.Parameter.KEYWORD_ONLY,\n inspect.Parameter.POSITIONAL_OR_KEYWORD,\n }\n)\n\n\ndef get_func_args(func):\n params = _get_callable_parameters(func)\n return [param.n", "middle": "ters\n\n\ndef _get_callable_parameters(meth_or_func):\n is_method = inspect.ismethod(meth_or_func)\n func = meth_or_func.__func__ if is_method else meth_or_func\n return _get_func_parameters(func, remove_first=is_method)\n\n\nARG", "meta": {"filepath": "django/utils/inspect.py", "language": "python", "file_size": 4522, "cut_index": 614, "middle_length": 229}} +{"prefix": "ango.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\nMAX_IPV6_ADDRESS_LENGTH = 39\n\n\ndef _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH):\n if len(ip_str) > max_length:\n raise ValueError(\n f\"Unable to convert {ip_str} to an IPv6 address (value too long).\"\n )\n return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))\n\n\ndef clean_ipv6_address(\n ip_str,\n unpack_ipv4=False,\n error_message=_(\"This is no", "suffix": "move leading\n zeroes, and make sure all hextets are lowercase.\n\n Args:\n ip_str: A valid IPv6 address.\n unpack_ipv4: if an IPv4-mapped address is found,\n return the plain IPv4 address (default=False).\n error_message: An err", "middle": "t a valid IPv6 address.\"),\n max_length=MAX_IPV6_ADDRESS_LENGTH,\n):\n \"\"\"\n Clean an IPv6 address string.\n\n Raise ValidationError if the address is invalid.\n\n Replace the longest continuous zero-sequence with \"::\", re", "meta": {"filepath": "django/utils/ipv6.py", "language": "python", "file_size": 1823, "cut_index": 537, "middle_length": 229}} +{"prefix": "ils.module_loading import import_string\n\nrequest_logger = logging.getLogger(\"django.request\")\n\n# Default logging for Django. This sends an email to the site admins on every\n# HTTP 500 error. Depending on DEBUG, all other log records are either sent to\n# the console (DEBUG=True) or discarded (DEBUG=False) by means of the\n# require_debug_true filter. This configuration is quoted in\n# docs/ref/logging.txt; please amend it there if edited here.\nDEFAULT_LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers", "suffix": "},\n \"formatters\": {\n \"django.server\": {\n \"()\": \"django.utils.log.ServerFormatter\",\n \"format\": \"[{server_time}] {message}\",\n \"style\": \"{\",\n }\n },\n \"handlers\": {\n \"console\": {\n \"level\"", "middle": "\": False,\n \"filters\": {\n \"require_debug_false\": {\n \"()\": \"django.utils.log.RequireDebugFalse\",\n },\n \"require_debug_true\": {\n \"()\": \"django.utils.log.RequireDebugTrue\",\n },\n ", "meta": {"filepath": "django/utils/log.py", "language": "python", "file_size": 10252, "cut_index": 921, "middle_length": 229}} +{"prefix": "bore et dolore magna aliqua. Ut enim ad minim \"\n \"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \"\n \"commodo consequat. Duis aute irure dolor in reprehenderit in voluptate \"\n \"velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint \"\n \"occaecat cupidatat non proident, sunt in culpa qui officia deserunt \"\n \"mollit anim id est laborum.\"\n)\n\nWORDS = (\n \"exercitationem\",\n \"perferendis\",\n \"perspiciatis\",\n \"laborum\",\n \"eveniet\",\n \"sunt\",\n \"iure", "suffix": "\",\n \"quaerat\",\n \"dignissimos\",\n \"facilis\",\n \"neque\",\n \"nihil\",\n \"expedita\",\n \"vitae\",\n \"vero\",\n \"ipsum\",\n \"nisi\",\n \"animi\",\n \"cumque\",\n \"pariatur\",\n \"velit\",\n \"modi\",\n \"natus\",\n \"iusto\",\n \"eaque\",\n \"", "middle": "\",\n \"nam\",\n \"nobis\",\n \"eum\",\n \"cum\",\n \"officiis\",\n \"excepturi\",\n \"odio\",\n \"consectetur\",\n \"quasi\",\n \"aut\",\n \"quisquam\",\n \"vel\",\n \"eligendi\",\n \"itaque\",\n \"non\",\n \"odit\",\n \"tempore", "meta": {"filepath": "django/utils/lorem_ipsum.py", "language": "python", "file_size": 5473, "cut_index": 716, "middle_length": 229}} +{"prefix": "pec as importlib_find\n\n\ndef cached_import(module_path, class_name):\n # Check whether module is loaded and fully initialized.\n if not (\n (module := sys.modules.get(module_path))\n and (spec := getattr(module, \"__spec__\", None))\n and getattr(spec, \"_initializing\", False) is False\n ):\n module = import_module(module_path)\n return getattr(module, class_name)\n\n\ndef import_string(dotted_path):\n \"\"\"\n Import a dotted module path and return the attribute/class designated b", "suffix": "a module path\" % dotted_path) from err\n\n try:\n return cached_import(module_path, class_name)\n except AttributeError as err:\n raise ImportError(\n 'Module \"%s\" does not define a \"%s\" attribute/class'\n % (module_path,", "middle": "y\n the last name in the path. Raise ImportError if the import failed.\n \"\"\"\n try:\n module_path, class_name = dotted_path.rsplit(\".\", 1)\n except ValueError as err:\n raise ImportError(\"%s doesn't look like ", "meta": {"filepath": "django/utils/module_loading.py", "language": "python", "file_size": 3820, "cut_index": 614, "middle_length": 229}} +{"prefix": "_safe\n\n\ndef format(\n number,\n decimal_sep,\n decimal_pos=None,\n grouping=0,\n thousand_sep=\"\",\n force_grouping=False,\n use_l10n=None,\n):\n \"\"\"\n Get a number (as a number or string), and return it as a string,\n using formats defined as arguments:\n\n * decimal_sep: Decimal separator symbol (for example \".\")\n * decimal_pos: Number of decimal positions\n * grouping: Number of digits in every group limited by thousand separator.\n For non-uniform digit grouping, it can be ", "suffix": " example \",\")\n \"\"\"\n if number is None or number == \"\":\n return mark_safe(number)\n if use_l10n is None:\n use_l10n = True\n use_grouping = use_l10n and settings.USE_THOUSAND_SEPARATOR\n use_grouping = use_grouping or force_grouping", "middle": "a sequence with the number\n of digit group sizes following the format used by the Python locale\n module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).\n * thousand_sep: Thousand separator symbol (for", "meta": {"filepath": "django/utils/numberformat.py", "language": "python", "file_size": 3867, "cut_index": 614, "middle_length": 229}} +{"prefix": "ass. So, e.g.,\n# \"\\w\" is replaced by \"x\" in a reverse URL. A value of None means to ignore\n# this sequence. Any missing key is mapped to itself.\nESCAPE_MAPPINGS = {\n \"A\": None,\n \"b\": None,\n \"B\": None,\n \"d\": \"0\",\n \"D\": \"x\",\n \"s\": \" \",\n \"S\": \"x\",\n \"w\": \"x\",\n \"W\": \"!\",\n \"Z\": None,\n}\n\n\nclass Choice(list):\n \"\"\"Represent multiple possibilities at this point in a pattern string.\"\"\"\n\n\nclass Group(list):\n \"\"\"Represent a capturing group in the pattern string.\"\"\"\n\n\nclass NonCapture(", "suffix": "lowing:\n\n (1) For any repeating sections, keeps the minimum number of occurrences\n permitted (this means zero for optional groups).\n (2) If an optional group includes parameters, include one occurrence of\n that group (along with the zer", "middle": "list):\n \"\"\"Represent a non-capturing group in the pattern string.\"\"\"\n\n\ndef normalize(pattern):\n r\"\"\"\n Given a reg-exp pattern, normalize it to an iterable of forms that\n suffice for reverse matching. This does the fol", "meta": {"filepath": "django/utils/regex_helper.py", "language": "python", "file_size": 12772, "cut_index": 921, "middle_length": 229}} +{"prefix": "ngs that can be displayed safely\nwithout further escaping in HTML. Marking something as a \"safe string\" means\nthat the producer of the string has already turned characters that should not\nbe interpreted by the HTML engine (e.g. '<') into the appropriate entities.\n\"\"\"\n\nfrom functools import wraps\n\nfrom django.utils.functional import keep_lazy\n\n\nclass SafeData:\n __slots__ = ()\n\n def __html__(self):\n \"\"\"\n Return the html representation of a string for interoperability.\n\n This allows ", "suffix": "\"\"\n\n __slots__ = ()\n\n def __add__(self, rhs):\n \"\"\"\n Concatenating a safe string with another safe bytestring or\n safe string is safe. Otherwise, the result is no longer safe.\n \"\"\"\n if isinstance(rhs, str):\n ", "middle": "other template engines to understand Django's SafeData.\n \"\"\"\n return self\n\n\nclass SafeString(str, SafeData):\n \"\"\"\n A str subclass that has been specifically marked as \"safe\" for HTML output\n purposes.\n \"", "meta": {"filepath": "django/utils/safestring.py", "language": "python", "file_size": 2178, "cut_index": 563, "middle_length": 229}} +{"prefix": "% x for x in range(8)}\n\nRESET = \"0\"\nopt_dict = {\n \"bold\": \"1\",\n \"underscore\": \"4\",\n \"blink\": \"5\",\n \"reverse\": \"7\",\n \"conceal\": \"8\",\n}\n\n\ndef colorize(text=\"\", opts=(), **kwargs):\n \"\"\"\n Return your text, enclosed in ANSI graphics codes.\n\n Depends on the keyword arguments 'fg' and 'bg', and the contents of\n the opts tuple/list.\n\n Return the RESET code if no parameters are given.\n\n Valid colors:\n 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'\n\n V", "suffix": "g='blue', opts=('blink',))\n colorize()\n colorize('goodbye', opts=('underscore',))\n print(colorize('first line', fg='red', opts=('noreset',)))\n print('this should be red too')\n print(colorize('and so should this'))\n ", "middle": "alid options:\n 'bold'\n 'underscore'\n 'blink'\n 'reverse'\n 'conceal'\n 'noreset' - string will not be auto-terminated with the RESET code\n\n Examples:\n colorize('hello', fg='red', b", "meta": {"filepath": "django/utils/termcolors.py", "language": "python", "file_size": 7386, "cut_index": 716, "middle_length": 229}} +{"prefix": "ext,\n lazy,\n)\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_lazy, pgettext\n\n\n@keep_lazy_text\ndef capfirst(x):\n \"\"\"Capitalize the first letter of a string.\"\"\"\n if not x:\n return x\n if not isinstance(x, str):\n x = str(x)\n return x[0].upper() + x[1:]\n\n\n# Set up regular expressions\nre_newlines = _lazy_re_compile(r\"\\r\\n|\\r\") # Used in normalize_newlines\nre_camel_case = _lazy_re_co", "suffix": "ve all white space except added line breaks consume the space on\n which they break the line.\n\n Don't wrap long words, thus the output text may have lines longer than\n ``width``.\n \"\"\"\n\n wrapper = textwrap.TextWrapper(\n width=width,\n ", "middle": "mpile(r\"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))\")\n\n\n@keep_lazy_text\ndef wrap(text, width):\n \"\"\"\n A word-wrap function that preserves existing line breaks. Expects that\n existing line breaks are posix newlines.\n\n Preser", "meta": {"filepath": "django/utils/text.py", "language": "python", "file_size": 15163, "cut_index": 921, "middle_length": 229}} +{"prefix": "re\nfrom django.utils.translation import gettext, ngettext_lazy\n\nTIME_STRINGS = {\n \"year\": ngettext_lazy(\"%(num)d year\", \"%(num)d years\", \"num\"),\n \"month\": ngettext_lazy(\"%(num)d month\", \"%(num)d months\", \"num\"),\n \"week\": ngettext_lazy(\"%(num)d week\", \"%(num)d weeks\", \"num\"),\n \"day\": ngettext_lazy(\"%(num)d day\", \"%(num)d days\", \"num\"),\n \"hour\": ngettext_lazy(\"%(num)d hour\", \"%(num)d hours\", \"num\"),\n \"minute\": ngettext_lazy(\"%(num)d minute\", \"%(num)d minutes\", \"num\"),\n}\n\nTIME_STRINGS_KEYS = ", "suffix": "e, reversed=False, time_strings=None, depth=2):\n \"\"\"\n Take two datetime objects and return the time between d and now as a nicely\n formatted string, e.g. \"10 minutes\". If d occurs after now, return\n \"0 minutes\".\n\n Units used are years, month", "middle": "list(TIME_STRINGS.keys())\n\nTIME_CHUNKS = [\n 60 * 60 * 24 * 7, # week\n 60 * 60 * 24, # day\n 60 * 60, # hour\n 60, # minute\n]\n\nMONTHS_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n\n\ndef timesince(d, now=Non", "meta": {"filepath": "django/utils/timesince.py", "language": "python", "file_size": 4917, "cut_index": 614, "middle_length": 229}} +{"prefix": "l import Local\n\nfrom django.conf import settings\n\n__all__ = [\n \"get_fixed_timezone\",\n \"get_default_timezone\",\n \"get_default_timezone_name\",\n \"get_current_timezone\",\n \"get_current_timezone_name\",\n \"activate\",\n \"deactivate\",\n \"override\",\n \"localtime\",\n \"localdate\",\n \"now\",\n \"is_aware\",\n \"is_naive\",\n \"make_aware\",\n \"make_naive\",\n]\n\n\ndef get_fixed_timezone(offset):\n \"\"\"Return a tzinfo instance with a fixed offset from UTC.\"\"\"\n if isinstance(offset, timedelta):\n", "suffix": " accessing settings at compile time,\n# wrap the logic in a function and cache the result.\n@functools.lru_cache\ndef get_default_timezone():\n \"\"\"\n Return the default time zone as a tzinfo instance.\n\n This is the time zone defined by settings.TIME_ZO", "middle": " offset = offset.total_seconds() // 60\n sign = \"-\" if offset < 0 else \"+\"\n hhmm = \"%02d%02d\" % divmod(abs(offset), 60)\n name = sign + hhmm\n return timezone(timedelta(minutes=offset), name)\n\n\n# In order to avoid", "meta": {"filepath": "django/utils/timezone.py", "language": "python", "file_size": 7291, "cut_index": 716, "middle_length": 229}} +{"prefix": "y\n\nfrom django.utils.hashable import make_hashable\n\n\nclass Node:\n \"\"\"\n A single internal node in the tree graph. A Node should be viewed as a\n connection (the root) with the children being either leaf nodes or other\n Node instances.\n \"\"\"\n\n # Standard connector type. Clients usually won't use this at all and\n # subclasses will usually override the value.\n default = \"DEFAULT\"\n\n def __init__(self, children=None, connector=None, negated=False):\n \"\"\"Construct a new Node. If no c", "suffix": " connector=None, negated=False):\n \"\"\"\n Create a new instance using Node() instead of __init__() as some\n subclasses, e.g. django.db.models.query_utils.Q, may implement a custom\n __init__() with a signature that conflicts with th", "middle": "onnector is given, use the default.\"\"\"\n self.children = children[:] if children else []\n self.connector = connector or self.default\n self.negated = negated\n\n @classmethod\n def create(cls, children=None,", "meta": {"filepath": "django/utils/tree.py", "language": "python", "file_size": 4394, "cut_index": 614, "middle_length": 229}} +{"prefix": "r import _lazy_re_compile\n\n# Private, stable API for detecting the Python implementation.\nPYPY = sys.implementation.name == \"pypy\"\n\n# Private, stable API for detecting the Python version. PYXY means \"Python X.Y\n# or later\". So that third-party apps can use these values, each constant\n# should remain as long as the oldest supported Django version supports that\n# Python version.\nPY310 = sys.version_info >= (3, 10)\nPY311 = sys.version_info >= (3, 11)\nPY312 = sys.version_info >= (3, 12)\nPY313 = sys.version_info", "suffix": " # Now build the two parts of the version number:\n # main = X.Y[.Z]\n # sub = .devN - for pre-alpha releases\n # | {a|b|rc}N - for alpha, beta, and rc releases\n\n main = get_main_version(version)\n\n sub = \"\"\n if version[3] == \"alpha\" an", "middle": " >= (3, 13)\nPY314 = sys.version_info >= (3, 14)\nPY315 = sys.version_info >= (3, 15)\n\n\ndef get_version(version=None):\n \"\"\"Return a PEP 440-compliant version number from VERSION.\"\"\"\n version = get_complete_version(version)\n\n ", "meta": {"filepath": "django/utils/version.py", "language": "python", "file_size": 3696, "cut_index": 614, "middle_length": 229}} +{"prefix": "ilities for XML generation/parsing.\n\"\"\"\n\nimport re\nfrom xml.sax.saxutils import XMLGenerator\n\n\nclass UnserializableContentError(ValueError):\n pass\n\n\nclass SimplerXMLGenerator(XMLGenerator):\n def addQuickElement(self, name, contents=None, attrs=None):\n \"Convenience method for adding an element with no children\"\n if attrs is None:\n attrs = {}\n self.startElement(name, attrs)\n if contents is not None:\n self.characters(contents)\n self.endElement(name", "suffix": ".org/International/questions/qa-controls\n raise UnserializableContentError(\n \"Control characters are not supported in XML 1.0\"\n )\n XMLGenerator.characters(self, content)\n\n def startElement(self, name, attrs):\n", "middle": ")\n\n def characters(self, content):\n if content and re.search(r\"[\\x00-\\x08\\x0B-\\x0C\\x0E-\\x1F]\", content):\n # Fail loudly when content has control chars (unsupported in XML\n # 1.0) See https://www.w3", "meta": {"filepath": "django/utils/xmlutils.py", "language": "python", "file_size": 1172, "cut_index": 518, "middle_length": 229}} +{"prefix": ".functional import lazy\nfrom django.utils.regex_helper import _lazy_re_compile\n\n__all__ = [\n \"activate\",\n \"deactivate\",\n \"override\",\n \"deactivate_all\",\n \"get_language\",\n \"get_language_from_request\",\n \"get_language_info\",\n \"get_language_bidi\",\n \"check_for_language\",\n \"to_language\",\n \"to_locale\",\n \"templatize\",\n \"gettext\",\n \"gettext_lazy\",\n \"gettext_noop\",\n \"ngettext\",\n \"ngettext_lazy\",\n \"pgettext\",\n \"pgettext_lazy\",\n \"npgettext\",\n \"npgettext_lazy", "suffix": " late as possible, so that modules can be imported\n# without having to first configure Django, and (2) if some other code creates\n# a reference to one of these functions, don't break that reference when we\n# replace the functions with their real counterpar", "middle": "\",\n]\n\n\nclass TranslatorCommentWarning(SyntaxWarning):\n pass\n\n\n# Here be dragons, so a short explanation of the logic won't hurt:\n# We are trying to solve two problems: (1) access settings, in particular\n# settings.USE_I18N, as", "meta": {"filepath": "django/utils/translation/__init__.py", "language": "python", "file_size": 8878, "cut_index": 716, "middle_length": 229}} +{"prefix": "m pathlib import Path\n\nfrom asgiref.local import Local\n\nfrom django.apps import apps\nfrom django.utils.autoreload import is_django_module\n\n\ndef watch_for_translation_changes(sender, **kwargs):\n \"\"\"Register file watchers for .mo files in potential locale paths.\"\"\"\n from django.conf import settings\n\n if settings.USE_I18N:\n directories = [Path(\"locale\")]\n directories.extend(\n Path(config.path) / \"locale\"\n for config in apps.get_app_configs()\n if not is_dj", "suffix": "th, **kwargs):\n \"\"\"Clear the internal translations cache if a .mo file is modified.\"\"\"\n if file_path.suffix == \".mo\":\n import gettext\n\n from django.utils.translation import trans_real\n\n gettext._translations = {}\n trans_re", "middle": "ango_module(config.module)\n )\n directories.extend(Path(p) for p in settings.LOCALE_PATHS)\n for path in directories:\n sender.watch_dir(path, \"**/*.mo\")\n\n\ndef translation_file_changed(sender, file_pa", "meta": {"filepath": "django/utils/translation/reloader.py", "language": "python", "file_size": 1114, "cut_index": 515, "middle_length": 229}} +{"prefix": ".\n \"\"\"\n return dot_re.sub(char, src)\n\n\ncontext_re = _lazy_re_compile(r\"\"\"^\\s+.*context\\s+((?:\"[^\"]*?\")|(?:'[^']*?'))\\s*\"\"\")\ninline_re = _lazy_re_compile(\n # Match the trans/translate 'some text' part.\n r\"\"\"^\\s*trans(?:late)?\\s+((?:\"[^\"]*?\")|(?:'[^']*?'))\"\"\"\n # Match and ignore optional filters\n r\"\"\"(?:\\s*\\|\\s*[^\\s:]+(?::(?:[^\\s'\":]+|(?:\"[^\"]*?\")|(?:'[^']*?')))?)*\"\"\"\n # Match the optional context part\n r\"\"\"(\\s+.*context\\s+((?:\"[^\"]*?\")|(?:'[^']*?')))?\\s*\"\"\"\n)\nblock_re = _lazy_re_compi", "suffix": "y_re_compile(r\"\"\"_\\(((?:\".*?\")|(?:'.*?'))\\)\"\"\")\n\n\ndef templatize(src, origin=None):\n \"\"\"\n Turn a Django template into something that is understood by xgettext. It\n does so by translating the Django translation tags into standard gettext\n functi", "middle": "le(\n r\"\"\"^\\s*blocktrans(?:late)?(\\s+.*context\\s+((?:\"[^\"]*?\")|(?:'[^']*?')))?(?:\\s+|$)\"\"\"\n)\nendblock_re = _lazy_re_compile(r\"\"\"^\\s*endblocktrans(?:late)?$\"\"\")\nplural_re = _lazy_re_compile(r\"\"\"^\\s*plural$\"\"\")\nconstant_re = _laz", "meta": {"filepath": "django/utils/translation/template.py", "language": "python", "file_size": 10549, "cut_index": 921, "middle_length": 229}} +{"prefix": "versions of the functions in django.utils.translation.trans_real\n# that don't actually do anything. This is purely for performance, so that\n# settings.USE_I18N = False can use this module rather than trans_real.py.\n\nfrom django.conf import settings\n\n\ndef gettext(message):\n return message\n\n\ngettext_noop = gettext_lazy = _ = gettext\n\n\ndef ngettext(singular, plural, number):\n if number == 1:\n return singular\n return plural\n\n\nngettext_lazy = ngettext\n\n\ndef pgettext(context, message):\n return ", "suffix": "guage():\n return settings.LANGUAGE_CODE\n\n\ndef get_language_bidi():\n return settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI\n\n\ndef check_for_language(x):\n return True\n\n\ndef get_language_from_request(request, check_path=False):\n return settings.", "middle": "gettext(message)\n\n\ndef npgettext(context, singular, plural, number):\n return ngettext(singular, plural, number)\n\n\ndef activate(x):\n return None\n\n\ndef deactivate():\n return None\n\n\ndeactivate_all = deactivate\n\n\ndef get_lan", "meta": {"filepath": "django/utils/translation/trans_null.py", "language": "python", "file_size": 1287, "cut_index": 524, "middle_length": 229}} +{"prefix": "gettext number to separate context from message\nCONTEXT_SEPARATOR = \"\\x04\"\n\n# Maximum number of characters that will be parsed from the Accept-Language\n# header or cookie to prevent possible denial of service or memory exhaustion\n# attacks. About 10x longer than the longest value shown on MDN’s\n# Accept-Language page.\nLANGUAGE_CODE_MAX_LENGTH = 500\n\n# Format of Accept-Language header values. From RFC 9110 Sections 12.4.2 and\n# 12.5.4, and RFC 5646 Section 2.1.\naccept_language_re = _lazy_re_compile(\n r\"\"\"", "suffix": "\n (?:\\s*,\\s*|$)\n \"\"\",\n re.VERBOSE,\n)\n\nlanguage_code_re = _lazy_re_compile(\n r\"^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$\", re.IGNORECASE\n)\n\nlanguage_code_prefix_re = _lazy_re_compile(r\"^/(\\w+([@-]\\w+){0,2})(/|$)\")\n\n\n@receiver(setti", "middle": "\n # \"en\", \"en-au\", \"x-y-z\", \"es-419\", \"*\"\n ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\\*)\n # Optional \"q=1.00\", \"q=0.8\"\n (?:\\s*;\\s*q=(0(?:\\.[0-9]{,3})?|1(?:\\.0{,3})?))?\n # Multiple accepts per header.", "meta": {"filepath": "django/utils/translation/trans_real.py", "language": "python", "file_size": 22339, "cut_index": 1331, "middle_length": 229}} +{"prefix": "jango.http.cookie import SimpleCookie, parse_cookie\nfrom django.http.request import (\n HttpHeaders,\n HttpRequest,\n QueryDict,\n RawPostDataException,\n UnreadablePostError,\n)\nfrom django.http.response import (\n BadHeaderError,\n FileResponse,\n Http404,\n HttpResponse,\n HttpResponseBadRequest,\n HttpResponseBase,\n HttpResponseForbidden,\n HttpResponseGone,\n HttpResponseNotAllowed,\n HttpResponseNotFound,\n HttpResponseNotModified,\n HttpResponsePermanentRedirect,\n ", "suffix": "ion\",\n \"UnreadablePostError\",\n \"HttpResponse\",\n \"HttpResponseBase\",\n \"StreamingHttpResponse\",\n \"HttpResponseRedirect\",\n \"HttpResponsePermanentRedirect\",\n \"HttpResponseNotModified\",\n \"HttpResponseBadRequest\",\n \"HttpResponseForbidd", "middle": " HttpResponseRedirect,\n HttpResponseServerError,\n JsonResponse,\n StreamingHttpResponse,\n)\n\n__all__ = [\n \"SimpleCookie\",\n \"parse_cookie\",\n \"HttpHeaders\",\n \"HttpRequest\",\n \"QueryDict\",\n \"RawPostDataExcept", "meta": {"filepath": "django/http/__init__.py", "language": "python", "file_size": 1200, "cut_index": 518, "middle_length": 229}} +{"prefix": "lass InputStreamExhausted(Exception):\n \"\"\"\n No more reads are allowed from this device.\n \"\"\"\n\n pass\n\n\nRAW = \"raw\"\nFILE = \"file\"\nFIELD = \"field\"\nFIELD_TYPES = frozenset([FIELD, RAW])\nMAX_TOTAL_HEADER_SIZE = 1024\n\n\nclass MultiPartParser:\n \"\"\"\n An RFC 7578 multipart/form-data parser.\n\n ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks\n and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``.\n \"\"\"\n\n boundary_re = _lazy_re_compile(r\"[ -~]{0,", "suffix": "cts.\n :input_data:\n The raw post data, as a file-like object.\n :upload_handlers:\n A list of UploadHandler instances that perform operations on the\n uploaded data.\n :encoding:\n The encoding wi", "middle": "200}[!-~]\")\n\n def __init__(self, META, input_data, upload_handlers, encoding=None):\n \"\"\"\n Initialize the MultiPartParser object.\n\n :META:\n The standard ``META`` dictionary in Django request obje", "meta": {"filepath": "django/http/multipartparser.py", "language": "python", "file_size": 28096, "cut_index": 1331, "middle_length": 229}} +{"prefix": "se_header_parameters\nfrom django.utils.regex_helper import _lazy_re_compile\n\nRAISE_ERROR = object()\nhost_validation_re = _lazy_re_compile(\n r\"^([a-z0-9.-]+|\\[[a-f0-9]*:[a-f0-9.:]+\\])(?::([0-9]+))?$\"\n)\n\n\nclass UnreadablePostError(OSError):\n pass\n\n\nclass RawPostDataException(Exception):\n \"\"\"\n You cannot access raw_post_data from a request that has\n multipart/* POST data if it has been accessed via POST,\n FILES, etc..\n \"\"\"\n\n pass\n\n\nclass HttpRequest:\n \"\"\"A basic HTTP request.\"\"\"\n\n ", "suffix": "bclass doesn't call `super`.\n # Any variable assignment made here should also happen in\n # `WSGIRequest.__init__()`.\n\n self.GET = QueryDict(mutable=True)\n self.POST = QueryDict(mutable=True)\n self.COOKIES = {}\n sel", "middle": " # The encoding used in GET/POST dicts. None means use default setting.\n _encoding = None\n _upload_handlers = []\n _multipart_parser_class = MultiPartParser\n\n def __init__(self):\n # WARNING: The `WSGIRequest` su", "meta": {"filepath": "django/http/request.py", "language": "python", "file_size": 30293, "cut_index": 1331, "middle_length": 229}} +{"prefix": "rt (\n MAX_URL_REDIRECT_LENGTH,\n content_disposition_header,\n http_date,\n)\nfrom django.utils.regex_helper import _lazy_re_compile\n\n_charset_from_content_type_re = _lazy_re_compile(\n r\";\\s*charset=(?P[^\\s;]+)\", re.I\n)\n_control_chars_re = _lazy_re_compile(r\"[\\x00-\\x1f\\x7f-\\x9f]\")\n\n\nclass ResponseHeaders(CaseInsensitiveMapping):\n def __init__(self, data):\n \"\"\"\n Populate the initial data using __setitem__ to ensure values are\n correctly encoded.\n \"\"\"\n se", "suffix": "aders key/value to ascii/latin-1 native strings.\n `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and\n `value` can't be represented in the given charset, apply MIME-encoding.\n \"\"\"\n try:\n if isinstance", "middle": "lf._store = {}\n if data:\n for header, value in self._unpack_items(data):\n self[header] = value\n\n def _convert_to_charset(self, value, charset, mime_encode=False):\n \"\"\"\n Convert he", "meta": {"filepath": "django/http/response.py", "language": "python", "file_size": 26970, "cut_index": 1331, "middle_length": 229}} +{"prefix": " that are commented out\n# serve to show the default.\n\nimport sys\nfrom os.path import abspath, dirname, join\n\nfrom sphinx import version_info as sphinx_version\n\n# Workaround for sphinx-build recursion limit overflow:\n# pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL)\n# RuntimeError: maximum recursion depth exceeded while pickling an object\n#\n# Python's default allowed recursion depth is 1000 but this isn't enough for\n# building docs/ref/settings.txt sometimes.\n# https://groups.google.com/g/sphinx-dev/c/MtRf", "suffix": "irectory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nsys.path.append(abspath(join(dirname(__file__), \"_ext\")))\n\n# Use the module to GitHub ur", "middle": "64eGtv4/discussion\nsys.setrecursionlimit(2000)\n\n# Make sure we get the version of this copy of Django\nsys.path.insert(1, dirname(dirname(abspath(__file__))))\n\n# If extensions (or modules to document with autodoc) are in another d", "meta": {"filepath": "docs/conf.py", "language": "python", "file_size": 14810, "cut_index": 921, "middle_length": 229}} +{"prefix": "xt,\n _is_very_long_string_literal,\n _starts_with_anonymous_hyperlink,\n _starts_with_directive_or_hyperlink,\n)\nfrom sphinxlint.checkers import checker as sphinxlint_checker\nfrom sphinxlint.rst import SIMPLENAME\nfrom sphinxlint.sphinxlint import check_text\nfrom sphinxlint.utils import PER_FILE_CACHES, hide_non_rst_blocks, paragraphs\n\n\ndef django_check_file(filename, checkers, options=None):\n try:\n for checker in checkers:\n # Django docs use \".txt\" for docs file extension.\n ", "suffix": " with open(filename, encoding=\"utf-8\") as f:\n text = f.read()\n except OSError as err:\n return [f\"{filename}: cannot open: {err}\"]\n except UnicodeDecodeError as err:\n return [f\"{filename}: cannot ", "middle": " if \".rst\" in checker.suffixes:\n checker.suffixes = (\".txt\",)\n ext = splitext(filename)[1]\n if not any(ext in checker.suffixes for checker in checkers):\n return Counter()\n try:\n ", "meta": {"filepath": "docs/lint.py", "language": "python", "file_size": 7095, "cut_index": 716, "middle_length": 229}} +{"prefix": "ption\nfrom sphinx.errors import ExtensionError\nfrom sphinx.util import logging\nfrom sphinx.util.console import bold\nfrom sphinx.writers.html import HTMLTranslator\n\nlogger = logging.getLogger(__name__)\n# RE for option descriptions without a '--' prefix\nsimple_option_desc_re = re.compile(r\"([-_a-zA-Z0-9]+)(\\s*.*?)(?=,\\s+(?:/|-|--)|$)\")\n\n\ndef setup(app):\n app.add_crossref_type(\n directivename=\"setting\",\n rolename=\"setting\",\n indextemplate=\"pair: %s; setting\",\n )\n app.add_crossref_", "suffix": "xtemplate=\"pair: %s; template filter\",\n )\n app.add_crossref_type(\n directivename=\"fieldlookup\",\n rolename=\"lookup\",\n indextemplate=\"pair: %s; field lookup type\",\n )\n app.add_object_type(\n directivename=\"django-admin\"", "middle": "type(\n directivename=\"templatetag\",\n rolename=\"ttag\",\n indextemplate=\"pair: %s; template tag\",\n )\n app.add_crossref_type(\n directivename=\"templatefilter\",\n rolename=\"tfilter\",\n inde", "meta": {"filepath": "docs/_ext/djangodocs.py", "language": "python", "file_size": 14448, "cut_index": 921, "middle_length": 229}} +{"prefix": "\n def __init__(self):\n super().__init__()\n self.current_path = []\n self.node_line_numbers = {}\n self.import_locations = {}\n\n @classmethod\n def from_code(cls, code):\n tree = ast.parse(code)\n locator = cls()\n locator.visit(tree)\n return locator\n\n def visit_node(self, node):\n self.current_path.append(node.name)\n self.node_line_numbers[\".\".join(self.current_path)] = node.lineno\n self.generic_visit(node)\n self.current", "suffix": " if alias.asname:\n # Exclude linking aliases (`import x as y`) to avoid confusion\n # when clicking a source link to a differently named entity.\n continue\n if alias.name == \"*\":\n # Re", "middle": "_path.pop()\n\n def visit_FunctionDef(self, node):\n self.visit_node(node)\n\n def visit_ClassDef(self, node):\n self.visit_node(node)\n\n def visit_ImportFrom(self, node):\n for alias in node.names:\n ", "meta": {"filepath": "docs/_ext/github_links.py", "language": "python", "file_size": 4728, "cut_index": 614, "middle_length": 229}} +{"prefix": "imeKeeper, TimeKeeper, get_runner\n from django.utils.deprecation import (\n RemovedAfterNextVersionWarning,\n RemovedInNextVersionWarning,\n )\n from django.utils.functional import classproperty\n from django.utils.log import DEFAULT_LOGGING\n from django.utils.version import PYPY\n\n\ntry:\n import MySQLdb\nexcept ImportError:\n pass\nelse:\n # Ignore informational warnings from QuerySet.explain().\n warnings.filterwarnings(\"ignore\", r\"\\(1003, *\", category=MySQLdb.Warning)\n\n# Make", "suffix": "g errors to ensure no usage of error prone\n# patterns.\nwarnings.simplefilter(\"error\", ResourceWarning)\nwarnings.simplefilter(\"error\", RuntimeWarning)\n\n# Reduce garbage collection frequency to improve performance. Since CPython\n# uses refcounting, garbage c", "middle": " deprecation warnings errors to ensure no usage of deprecated features.\nwarnings.simplefilter(\"error\", RemovedInNextVersionWarning)\nwarnings.simplefilter(\"error\", RemovedAfterNextVersionWarning)\n# Make resource and runtime warnin", "meta": {"filepath": "tests/runtests.py", "language": "python", "file_size": 27785, "cut_index": 1331, "middle_length": 229}} +{"prefix": "# This is an example test settings file for use with the Django test suite.\n#\n# The 'sqlite3' backend requires only the ENGINE setting (an in-\n# memory database will be used). All other backends will require a\n# NAME and potentially authentication information. See the\n# following section in the docs for more information:\n#\n# https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/\n#\n# The different databases that Django supports behave differently in certain\n# situations, so it ", "suffix": "\"django.db.backends.sqlite3\",\n },\n \"other\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n },\n}\n\nSECRET_KEY = \"django_tests_secret_key\"\n\n# Use a fast hasher to speed up tests.\nPASSWORD_HASHERS = [\n \"django.contrib.auth.hashers.MD5PasswordHa", "middle": "is recommended to run the test suite against as many\n# database backends as possible. You may want to create a separate settings\n# file for each of the backends you test against.\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": ", "meta": {"filepath": "tests/test_sqlite.py", "language": "python", "file_size": 1022, "cut_index": 512, "middle_length": 229}} +{"prefix": "ces cannot be assigned new attributes. Define a subclass\n# in order to define new attributes in do_timezone().\nclass datetimeobject(datetime):\n pass\n\n\n# Template filters\n\n\n@register.filter\ndef localtime(value):\n \"\"\"\n Convert a datetime to local time in the active time zone.\n\n This only makes sense within a {% localtime off %} block.\n \"\"\"\n return do_timezone(value, timezone.get_current_timezone())\n\n\n@register.filter\ndef utc(value):\n \"\"\"\n Convert a datetime to UTC.\n \"\"\"\n return d", "suffix": "\n\n Naive datetimes are assumed to be in local time in the default time zone.\n \"\"\"\n if not isinstance(value, datetime):\n return \"\"\n\n # Obtain a timezone-aware datetime\n try:\n if timezone.is_naive(value):\n default_time", "middle": "o_timezone(value, UTC)\n\n\n@register.filter(\"timezone\")\ndef do_timezone(value, arg):\n \"\"\"\n Convert a datetime to local time in a given time zone.\n\n The argument must be an instance of a tzinfo subclass or a time zone name.", "meta": {"filepath": "django/templatetags/tz.py", "language": "python", "file_size": 5273, "cut_index": 716, "middle_length": 229}} +{"prefix": "y person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nT", "suffix": "S OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport os\nimport shu", "middle": "HE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHOR", "meta": {"filepath": "django/utils/archive.py", "language": "python", "file_size": 8301, "cut_index": 716, "middle_length": 229}} +{"prefix": "ught. Keep a list of these\n# file paths to allow watching them in the future.\n_error_files = []\n_exception = None\n# Exception raised while loading the URLConf.\n_url_module_exception = None\n\ntry:\n import termios\nexcept ImportError:\n termios = None\n\n\ntry:\n import pywatchman\nexcept ImportError:\n pywatchman = None\n\n\ndef is_django_module(module):\n \"\"\"Return True if the given module is nested under Django.\"\"\"\n return module.__name__.startswith(\"django.\")\n\n\ndef is_django_path(path):\n \"\"\"Return", "suffix": "\n fn(*args, **kwargs)\n except Exception as e:\n _exception = sys.exc_info()\n\n et, ev, tb = _exception\n\n if getattr(ev, \"filename\", None) is None:\n # get the filename from the last item in the", "middle": " True if the given file path is nested under Django.\"\"\"\n return Path(django.__file__).parent in Path(path).parents\n\n\ndef check_errors(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n global _exception\n try:", "meta": {"filepath": "django/utils/autoreload.py", "language": "python", "file_size": 25048, "cut_index": 1331, "middle_length": 229}} +{"prefix": "ip_longest\n\nfrom django.utils.functional import Promise\n\n__all__ = [\n \"BaseChoiceIterator\",\n \"BlankChoiceIterator\",\n \"CallableChoiceIterator\",\n \"flatten_choices\",\n \"normalize_choices\",\n]\n\n\nclass BaseChoiceIterator:\n \"\"\"Base class for lazy iterators for choices.\"\"\"\n\n def __eq__(self, other):\n if isinstance(other, Iterable):\n return all(a == b for a, b in zip_longest(self, other, fillvalue=object()))\n return super().__eq__(other)\n\n def __getitem__(self, index):", "suffix": "slice(self, index, index + 1))\n except StopIteration:\n raise IndexError(\"index out of range\") from None\n\n def __iter__(self):\n raise NotImplementedError(\n \"BaseChoiceIterator subclasses must implement __iter__().\"\n ", "middle": "\n if isinstance(index, slice) or index < 0:\n # Suboptimally consume whole iterator to handle slices and negative\n # indexes.\n return list(self)[index]\n try:\n return next(i", "meta": {"filepath": "django/utils/choices.py", "language": "python", "file_size": 4202, "cut_index": 614, "middle_length": 229}} +{"prefix": "mport warnings\n\nfrom django.conf import settings\nfrom django.utils.deprecation import RemovedInDjango70Warning, django_file_prefixes\nfrom django.utils.encoding import force_bytes\n\n\nclass InvalidAlgorithm(ValueError):\n \"\"\"Algorithm is not supported by hashlib.\"\"\"\n\n pass\n\n\n# RemovedInDjango70Warning: algorithm=\"sha256\"\ndef salted_hmac(key_salt, value, secret=None, *, algorithm=None):\n \"\"\"\n Return the HMAC of 'value', using a key generated from key_salt and a\n secret (which defaults to settings.", "suffix": "hm to silence the warning.\n\n A different key_salt should be passed in for every application of HMAC.\n \"\"\"\n if algorithm is None:\n warnings.warn(\n \"The default argument for algorithm in salted_hmac() will change \"\n \"fro", "middle": "SECRET_KEY). Default algorithm is SHA1,\n but any algorithm name supported by hashlib can be passed.\n\n Removed in Django70Warning: The default algorithm will change to SHA256\n in Django 7.0, so provide an explicit algorit", "meta": {"filepath": "django/utils/crypto.py", "language": "python", "file_size": 3347, "cut_index": 614, "middle_length": 229}} +{"prefix": "ove(item)\n except KeyError:\n pass\n\n def __iter__(self):\n return iter(self.dict)\n\n def __reversed__(self):\n return reversed(self.dict)\n\n def __contains__(self, item):\n return item in self.dict\n\n def __bool__(self):\n return bool(self.dict)\n\n def __len__(self):\n return len(self.dict)\n\n def __repr__(self):\n data = repr(list(self.dict)) if self.dict else \"\"\n return f\"{self.__class__.__qualname__}({data})\"\n\n\nclass MultiValueDictK", "suffix": "tion': ['Developer']}\n ... )\n >>> d['name']\n 'Simon'\n >>> d.getlist('name')\n ['Adrian', 'Simon']\n >>> d.getlist('doesnotexist')\n []\n >>> d.getlist('doesnotexist', ['Adrian', 'Simon'])\n ['Adrian', 'Simon']\n >>> d.get('lastname'", "middle": "eyError(KeyError):\n pass\n\n\nclass MultiValueDict(dict):\n \"\"\"\n A subclass of dictionary customized to handle multiple values for the\n same key.\n\n >>> d = MultiValueDict(\n ... {'name': ['Adrian', 'Simon'], 'posi", "meta": {"filepath": "django/utils/datastructures.py", "language": "python", "file_size": 10863, "cut_index": 921, "middle_length": 229}} +{"prefix": "The date/datetime/time constructors produce friendlier error messages.\n\nimport datetime\n\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.timezone import get_fixed_timezone\n\ndate_re = _lazy_re_compile(r\"(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})$\")\n\ntime_re = _lazy_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)\n\ndatetime_re = _lazy_re_compile(\n r\"(?P\\d{4})-(?P\\d{1,2})-(?P-?\\d+) (days?, )?)?\"\n r\"(?P-?)\"\n r\"((?:(?P\\d+):)(?=\\d+:\\d+))?\"\n r\"(?:(?P\\d+):)?\"\n r\"(?P\\d+)\"\n r\"(?:[.,](?P\\d{1,6})\\d{0,6})?\"\n r\"$\"\n)\n\n# Support the sections of ISO 8601 ", "middle": "y>\\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\"\\s*(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$\"\n)\n\nstandard_duration_re = _lazy_re_compile(\n ", "meta": {"filepath": "django/utils/dateparse.py", "language": "python", "file_size": 5414, "cut_index": 716, "middle_length": 229}} +{"prefix": "ils.version import get_docs_version\n\n\ndef deconstructible(*args, path=None):\n \"\"\"\n Class decorator that allows the decorated class to be serialized\n by the migrations subsystem.\n\n The `path` kwarg specifies the import path.\n \"\"\"\n\n def decorator(klass):\n def __new__(cls, *args, **kwargs):\n # We capture the arguments to make returning them trivial\n obj = super(klass, cls).__new__(cls)\n obj._constructor_args = (args, kwargs)\n return obj\n\n ", "suffix": ") is klass:\n module_name, _, name = path.rpartition(\".\")\n else:\n module_name = obj.__module__\n name = obj.__class__.__name__\n # Make sure it's actually there and not an inner class\n ", "middle": " def deconstruct(obj):\n \"\"\"\n Return a 3-tuple of class import path, positional arguments,\n and keyword arguments.\n \"\"\"\n # Fallback version\n if path and type(obj", "meta": {"filepath": "django/utils/deconstruct.py", "language": "python", "file_size": 2126, "cut_index": 563, "middle_length": 229}} +{"prefix": " cache, it is possible to avoid running get_format_modules\n# repeatedly.\n_format_cache = {}\n_format_modules_cache = {}\n\nISO_INPUT_FORMATS = {\n \"DATE_INPUT_FORMATS\": [\"%Y-%m-%d\"],\n \"TIME_INPUT_FORMATS\": [\"%H:%M:%S\", \"%H:%M:%S.%f\", \"%H:%M\"],\n \"DATETIME_INPUT_FORMATS\": [\n \"%Y-%m-%d %H:%M:%S\",\n \"%Y-%m-%d %H:%M:%S.%f\",\n \"%Y-%m-%d %H:%M\",\n \"%Y-%m-%d\",\n ],\n}\n\n\nFORMAT_SETTINGS = frozenset(\n [\n \"DECIMAL_SEPARATOR\",\n \"THOUSAND_SEPARATOR\",\n \"NUMBER_GROUPI", "suffix": " \"DATE_INPUT_FORMATS\",\n \"TIME_INPUT_FORMATS\",\n \"DATETIME_INPUT_FORMATS\",\n ]\n)\n\n\ndef reset_format_cache():\n \"\"\"Clear any cached formats.\n\n This method is provided primarily for testing purposes,\n so that the effects of cached f", "middle": "NG\",\n \"FIRST_DAY_OF_WEEK\",\n \"MONTH_DAY_FORMAT\",\n \"TIME_FORMAT\",\n \"DATE_FORMAT\",\n \"DATETIME_FORMAT\",\n \"SHORT_DATE_FORMAT\",\n \"SHORT_DATETIME_FORMAT\",\n \"YEAR_MONTH_FORMAT\",\n ", "meta": {"filepath": "django/utils/formats.py", "language": "python", "file_size": 10255, "cut_index": 921, "middle_length": 229}} +{"prefix": "method(classmethod):\n def __get__(self, instance, cls=None):\n if instance is not None:\n raise AttributeError(\n \"This method is available only on the class, not on instances.\"\n )\n return super().__get__(instance, cls)\n\n\ndef _update_method_wrapper(_wrapper, decorator):\n # _multi_decorate()'s bound_method isn't available in this scope. Cheat by\n # using it on a dummy function.\n @decorator\n def dummy(*args, **kwargs):\n pass\n\n update_wra", "suffix": "decorators, \"__iter__\"):\n # Apply a list/tuple of decorators if 'decorators' is one. Decorator\n # functions are applied so that the call order is the same as the\n # order in which they appear in the iterable.\n decorators = decor", "middle": "pper(_wrapper, dummy)\n\n\ndef _multi_decorate(decorators, method):\n \"\"\"\n Decorate `method` with one or more function decorators. `decorators` can be\n a single decorator or an iterable of decorators.\n \"\"\"\n if hasattr(", "meta": {"filepath": "django/utils/decorators.py", "language": "python", "file_size": 8322, "cut_index": 716, "middle_length": 229}} +{"prefix": " datetime\n\n\ndef _get_duration_components(duration):\n days = duration.days\n seconds = duration.seconds\n microseconds = duration.microseconds\n\n minutes = seconds // 60\n seconds %= 60\n\n hours = minutes // 60\n minutes %= 60\n\n return days, hours, minutes, seconds, microseconds\n\n\ndef duration_string(duration):\n \"\"\"Version of str(timedelta) which is not English specific.\"\"\"\n days, hours, minutes, seconds, microseconds = _get_duration_components(duration)\n\n string = \"{:02d}:{:02d}:{", "suffix": " duration < datetime.timedelta(0):\n sign = \"-\"\n duration *= -1\n else:\n sign = \"\"\n\n days, hours, minutes, seconds, microseconds = _get_duration_components(duration)\n ms = \".{:06d}\".format(microseconds) if microseconds else \"\"\n ", "middle": ":02d}\".format(hours, minutes, seconds)\n if days:\n string = \"{} \".format(days) + string\n if microseconds:\n string += \".{:06d}\".format(microseconds)\n\n return string\n\n\ndef duration_iso_string(duration):\n if", "meta": {"filepath": "django/utils/duration.py", "language": "python", "file_size": 1230, "cut_index": 518, "middle_length": 229}} +{"prefix": "m .base import (\n clear_script_prefix,\n clear_url_caches,\n get_script_prefix,\n get_urlconf,\n is_valid_path,\n resolve,\n reverse,\n reverse_lazy,\n set_script_prefix,\n set_urlconf,\n translate_url,\n)\nfrom .conf import include, path, re_path\nfrom .converters import register_converter\nfrom .exceptions import NoReverseMatch, Resolver404\nfrom .resolvers import (\n LocalePrefixPattern,\n ResolverMatch,\n URLPattern,\n URLResolver,\n get_ns_resolver,\n get_resolver,\n)\nfrom ", "suffix": ",\n \"get_callable\",\n \"get_mod_func\",\n \"get_ns_resolver\",\n \"get_resolver\",\n \"get_script_prefix\",\n \"get_urlconf\",\n \"include\",\n \"is_valid_path\",\n \"path\",\n \"re_path\",\n \"register_converter\",\n \"resolve\",\n \"reverse\",\n \"rev", "middle": ".utils import get_callable, get_mod_func\n\n__all__ = [\n \"LocalePrefixPattern\",\n \"NoReverseMatch\",\n \"URLPattern\",\n \"URLResolver\",\n \"Resolver404\",\n \"ResolverMatch\",\n \"clear_script_prefix\",\n \"clear_url_caches\"", "meta": {"filepath": "django/urls/__init__.py", "language": "python", "file_size": 1079, "cut_index": 515, "middle_length": 229}} +{"prefix": "le\n\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom .resolvers import (\n LocalePrefixPattern,\n RegexPattern,\n RoutePattern,\n URLPattern,\n URLResolver,\n)\n\n\ndef include(arg, namespace=None):\n app_name = None\n if isinstance(arg, tuple):\n # Callable returning a namespace hint.\n try:\n urlconf_module, app_name = arg\n except ValueError:\n if namespace:\n raise ImproperlyConfigured(\n \"Cannot override the na", "suffix": " \"2-tuple containing the list of patterns and app_name, and \"\n \"provide the namespace argument to include() instead.\" % len(arg)\n )\n else:\n # No namespace hint - use manually provided namespace.\n urlconf_module = ", "middle": "mespace for a dynamic module that \"\n \"provides a namespace.\"\n )\n raise ImproperlyConfigured(\n \"Passing a %d-tuple to include() is not supported. Pass a \"\n ", "meta": {"filepath": "django/urls/conf.py", "language": "python", "file_size": 3426, "cut_index": 614, "middle_length": 229}} +{"prefix": "django.utils.regex_helper import _lazy_re_compile, normalize\nfrom django.utils.translation import get_language\n\nfrom .converters import get_converters\nfrom .exceptions import NoReverseMatch, Resolver404\nfrom .utils import get_callable\n\n\nclass ResolverMatch:\n def __init__(\n self,\n func,\n args,\n kwargs,\n url_name=None,\n app_names=None,\n namespaces=None,\n route=None,\n tried=None,\n captured_kwargs=None,\n extra_kwargs=None,\n ):\n ", "suffix": "_kwargs = extra_kwargs\n\n # If a URLRegexResolver doesn't have a namespace or app_name, it passes\n # in an empty value.\n self.app_names = [x for x in app_names if x] if app_names else []\n self.app_name = \":\".join(self.app_names)\n", "middle": " self.func = func\n self.args = args\n self.kwargs = kwargs\n self.url_name = url_name\n self.route = route\n self.tried = tried\n self.captured_kwargs = captured_kwargs\n self.extra", "meta": {"filepath": "django/urls/resolvers.py", "language": "python", "file_size": 32056, "cut_index": 1331, "middle_length": 229}} +{"prefix": "e_template_fragment_key\nfrom django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist\n\nregister = Library()\n\n\nclass CacheNode(Node):\n def __init__(self, nodelist, expire_time_var, fragment_name, vary_on, cache_name):\n self.nodelist = nodelist\n self.expire_time_var = expire_time_var\n self.fragment_name = fragment_name\n self.vary_on = vary_on\n self.cache_name = cache_name\n\n def render(self, context):\n try:\n expire_time = self.ex", "suffix": "is not None:\n try:\n expire_time = int(expire_time)\n except (ValueError, TypeError):\n raise TemplateSyntaxError(\n '\"cache\" tag got a non-integer timeout value: %r' % expire_time\n ", "middle": "pire_time_var.resolve(context)\n except VariableDoesNotExist:\n raise TemplateSyntaxError(\n '\"cache\" tag got an unknown variable: %r' % self.expire_time_var.var\n )\n if expire_time ", "meta": {"filepath": "django/templatetags/cache.py", "language": "python", "file_size": 3550, "cut_index": 614, "middle_length": 229}} +{"prefix": "ib import Path\n\nfrom django.core.exceptions import SuspiciousFileOperation\n\n\n# Copied verbatim (minus `os.path` fixes) from:\n# https://github.com/python/cpython/pull/23901.\n# Python versions >= PY315 may include this fix, so periodic checks are needed\n# to remove this vendored copy of `makedirs` once solved upstream.\ndef makedirs(name, mode=0o777, exist_ok=False, *, parent_mode=None):\n \"\"\"makedirs(name [, mode=0o777][, exist_ok=False][, parent_mode=None])\n\n Super-mkdir; create a leaf directory and all", "suffix": "alse. Otherwise no exception is\n raised. If parent_mode is not None, it will be used as the mode for any\n newly-created, intermediate-level directories. Otherwise, intermediate\n directories are created with the default permissions (respecting uma", "middle": " intermediate ones. Works like\n mkdir, except that any intermediate path segment (not just the rightmost)\n will be created if it does not exist. If the target directory already\n exists, raise an OSError if exist_ok is F", "meta": {"filepath": "django/utils/_os.py", "language": "python", "file_size": 4853, "cut_index": 614, "middle_length": 229}} +{"prefix": "take\ninto account when building its cache key. Requests with the same path but\ndifferent header content for headers named in \"Vary\" need to get different\ncache keys to prevent delivery of wrong content.\n\nAn example: i18n middleware would need to distinguish caches by the\n\"Accept-language\" header.\n\"\"\"\n\nimport time\nfrom collections import defaultdict\nfrom hashlib import md5\n\nfrom django.conf import settings\nfrom django.core.cache import caches\nfrom django.http import HttpResponse, HttpResponseNotModified\nfrom", "suffix": "ezone_name\nfrom django.utils.translation import get_language\n\ncc_delim_re = _lazy_re_compile(r\"\\s*,\\s*\")\n\n\ndef patch_cache_control(response, **kwargs):\n \"\"\"\n Patch the Cache-Control header by adding all keyword arguments to it.\n The transformation", "middle": " django.utils.http import http_date, parse_etags, parse_http_date_safe, quote_etag\nfrom django.utils.log import log_response\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.timezone import get_current_tim", "meta": {"filepath": "django/utils/cache.py", "language": "python", "file_size": 16589, "cut_index": 921, "middle_length": 229}} +{"prefix": "rom django.utils.html import format_html\n\n# Template context key for the CSP nonce.\nCONTEXT_KEY = \"csp_nonce\"\n\n\nclass CSP(StrEnum):\n \"\"\"\n Content Security Policy constants for directive values and special tokens.\n\n These constants represent:\n 1. Standard quoted string values from the CSP spec (e.g., 'self',\n 'unsafe-inline')\n 2. Special placeholder tokens (NONCE) that get replaced by the middleware\n\n Using this enum instead of raw strings provides better type checking,\n autocomple", "suffix": "\n\n Example usage in Django settings:\n\n SECURE_CSP = {\n \"default-src\": [CSP.NONE],\n \"script-src\": [CSP.SELF, CSP.NONCE],\n }\n\n \"\"\"\n\n # HTTP Headers.\n HEADER_ENFORCE = \"Content-Security-Policy\"\n HEADER_REPORT", "middle": "tion, and protection against common mistakes like:\n\n - Typos (e.g., 'noone' instead of 'none')\n - Missing quotes (e.g., [\"self\"] instead of [\"'self'\"])\n - Inconsistent quote styles (e.g., [\"'self'\", \"\\\"unsafe-inline\\\"\"])", "meta": {"filepath": "django/utils/csp.py", "language": "python", "file_size": 3971, "cut_index": 614, "middle_length": 229}} +{"prefix": "translation import gettext_lazy as _\nfrom django.utils.translation import pgettext_lazy\n\nWEEKDAYS = {\n 0: _(\"Monday\"),\n 1: _(\"Tuesday\"),\n 2: _(\"Wednesday\"),\n 3: _(\"Thursday\"),\n 4: _(\"Friday\"),\n 5: _(\"Saturday\"),\n 6: _(\"Sunday\"),\n}\nWEEKDAYS_ABBR = {\n 0: _(\"Mon\"),\n 1: _(\"Tue\"),\n 2: _(\"Wed\"),\n 3: _(\"Thu\"),\n 4: _(\"Fri\"),\n 5: _(\"Sat\"),\n 6: _(\"Sun\"),\n}\nMONTHS = {\n 1: _(\"January\"),\n 2: _(\"February\"),\n 3: _(\"March\"),\n 4: _(\"April\"),\n 5: _(\"May\"),\n 6: _(\"Ju", "suffix": "ay\"),\n 6: _(\"jun\"),\n 7: _(\"jul\"),\n 8: _(\"aug\"),\n 9: _(\"sep\"),\n 10: _(\"oct\"),\n 11: _(\"nov\"),\n 12: _(\"dec\"),\n}\nMONTHS_AP = { # month names in Associated Press style\n 1: pgettext_lazy(\"abbrev. month\", \"Jan.\"),\n 2: pgettext_lazy(\"ab", "middle": "ne\"),\n 7: _(\"July\"),\n 8: _(\"August\"),\n 9: _(\"September\"),\n 10: _(\"October\"),\n 11: _(\"November\"),\n 12: _(\"December\"),\n}\nMONTHS_3 = {\n 1: _(\"jan\"),\n 2: _(\"feb\"),\n 3: _(\"mar\"),\n 4: _(\"apr\"),\n 5: _(\"m", "meta": {"filepath": "django/utils/dates.py", "language": "python", "file_size": 2179, "cut_index": 563, "middle_length": 229}} +{"prefix": "b.parse import urlparse\n\nfrom django.forms.utils import flatatt\nfrom django.utils.encoding import iri_to_uri\nfrom django.utils.xmlutils import SimplerXMLGenerator\n\n\ndef rfc2822_date(date):\n if not isinstance(date, datetime.datetime):\n date = datetime.datetime.combine(date, datetime.time())\n return email.utils.format_datetime(date)\n\n\ndef rfc3339_date(date):\n if not isinstance(date, datetime.datetime):\n date = datetime.datetime.combine(date, datetime.time())\n return date.isoformat() ", "suffix": "bits = urlparse(url)\n d = \"\"\n if date is not None:\n d = \",%s\" % date.strftime(\"%Y-%m-%d\")\n return \"tag:%s%s:%s/%s\" % (bits.hostname, d, bits.path, bits.fragment)\n\n\ndef _guess_stylesheet_mimetype(url):\n \"\"\"\n Return the given stylesheet", "middle": "+ (\"Z\" if date.utcoffset() is None else \"\")\n\n\ndef get_tag_uri(url, date):\n \"\"\"\n Create a TagURI.\n\n See\n https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id\n \"\"\"\n ", "meta": {"filepath": "django/utils/feedgenerator.py", "language": "python", "file_size": 18069, "cut_index": 1331, "middle_length": 229}} +{"prefix": "ror(UnicodeDecodeError):\n def __str__(self):\n return \"%s. You passed in %r (%s)\" % (\n super().__str__(),\n self.object,\n type(self.object),\n )\n\n\ndef smart_str(s, encoding=\"utf-8\", strings_only=False, errors=\"strict\"):\n \"\"\"\n Return a string representing 's'. Treat bytestrings using the 'encoding'\n codec.\n\n If strings_only is True, don't convert (some) non-string-like objects.\n \"\"\"\n if isinstance(s, Promise):\n # The input is the result ", "suffix": "\n)\n\n\ndef is_protected_type(obj):\n \"\"\"Determine if the object instance is of a protected type.\n\n Objects of protected types are preserved as-is when passed to\n force_str(strings_only=True).\n \"\"\"\n return isinstance(obj, _PROTECTED_TYPES)\n\n\ndef", "middle": "of a gettext_lazy() call.\n return s\n return force_str(s, encoding, strings_only, errors)\n\n\n_PROTECTED_TYPES = (\n NoneType,\n int,\n float,\n Decimal,\n datetime.datetime,\n datetime.date,\n datetime.time,", "meta": {"filepath": "django/utils/encoding.py", "language": "python", "file_size": 8793, "cut_index": 716, "middle_length": 229}} +{"prefix": " import override\n\nfrom .exceptions import NoReverseMatch, Resolver404\nfrom .resolvers import _get_cached_resolver, get_ns_resolver, get_resolver\nfrom .utils import get_callable\n\n# SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for\n# the current thread (which is the only one we ever access), it is assumed to\n# be empty.\n_prefixes = Local()\n\n# Overridden URLconfs for each thread are stored here.\n_urlconfs = Local()\n\n\ndef resolve(path, urlconf=None):\n if urlconf is None:\n u", "suffix": "f is None:\n urlconf = get_urlconf()\n resolver = get_resolver(urlconf)\n args = args or []\n kwargs = kwargs or {}\n\n prefix = get_script_prefix()\n\n if not isinstance(viewname, str):\n view = viewname\n else:\n *path, view =", "middle": "rlconf = get_urlconf()\n return get_resolver(urlconf).resolve(path)\n\n\ndef reverse(\n viewname,\n urlconf=None,\n args=None,\n kwargs=None,\n current_app=None,\n *,\n query=None,\n fragment=None,\n):\n if urlcon", "meta": {"filepath": "django/urls/base.py", "language": "python", "file_size": 6191, "cut_index": 716, "middle_length": 229}} +{"prefix": "ools\nimport uuid\n\n\nclass IntConverter:\n regex = \"[0-9]+\"\n\n def to_python(self, value):\n return int(value)\n\n def to_url(self, value):\n return str(value)\n\n\nclass StringConverter:\n regex = \"[^/]+\"\n\n def to_python(self, value):\n return value\n\n def to_url(self, value):\n return value\n\n\nclass UUIDConverter:\n regex = \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"\n\n def to_python(self, value):\n return uuid.UUID(value)\n\n def to_url(self, va", "suffix": "verter(),\n \"slug\": SlugConverter(),\n \"str\": StringConverter(),\n \"uuid\": UUIDConverter(),\n}\n\n\nREGISTERED_CONVERTERS = {}\n\n\ndef register_converter(converter, type_name):\n if type_name in REGISTERED_CONVERTERS or type_name in DEFAULT_CONVERTERS:\n ", "middle": "lue):\n return str(value)\n\n\nclass SlugConverter(StringConverter):\n regex = \"[-a-zA-Z0-9_]+\"\n\n\nclass PathConverter(StringConverter):\n regex = \".+\"\n\n\nDEFAULT_CONVERTERS = {\n \"int\": IntConverter(),\n \"path\": PathCon", "meta": {"filepath": "django/urls/converters.py", "language": "python", "file_size": 1358, "cut_index": 524, "middle_length": 229}} +{"prefix": " os\nfrom asyncio import get_running_loop\nfrom functools import wraps\n\nfrom django.core.exceptions import SynchronousOnlyOperation\n\n\ndef async_unsafe(message):\n \"\"\"\n Decorator to mark functions as async-unsafe. Someone trying to access\n the function while in an async context will get an error message.\n \"\"\"\n\n def decorator(func):\n @wraps(func)\n def inner(*args, **kwargs):\n # Detect a running event loop in this thread.\n try:\n get_running_loop()\n", "suffix": " return func(*args, **kwargs)\n\n return inner\n\n # If the message is actually a function, then be a no-arguments decorator.\n if callable(message):\n func = message\n message = (\n \"You cannot call this from an asyn", "middle": " except RuntimeError:\n pass\n else:\n if not os.environ.get(\"DJANGO_ALLOW_ASYNC_UNSAFE\"):\n raise SynchronousOnlyOperation(message)\n # Pass onward.\n ", "meta": {"filepath": "django/utils/asyncio.py", "language": "python", "file_size": 1138, "cut_index": 518, "middle_length": 229}} +{"prefix": "mport settings as django_settings\nfrom django.utils.functional import cached_property\n\n\nclass ConnectionProxy:\n \"\"\"Proxy for accessing a connection object's attributes.\"\"\"\n\n def __init__(self, connections, alias):\n self.__dict__[\"_connections\"] = connections\n self.__dict__[\"_alias\"] = alias\n\n def __getattr__(self, item):\n return getattr(self._connections[self._alias], item)\n\n def __setattr__(self, name, value):\n return setattr(self._connections[self._alias], name, val", "suffix": "n self._connections[self._alias] == other\n\n\nclass ConnectionDoesNotExist(Exception):\n pass\n\n\nclass BaseConnectionHandler:\n settings_name = None\n exception_class = ConnectionDoesNotExist\n thread_critical = False\n\n def __init__(self, settings=", "middle": "ue)\n\n def __delattr__(self, name):\n return delattr(self._connections[self._alias], name)\n\n def __contains__(self, key):\n return key in self._connections[self._alias]\n\n def __eq__(self, other):\n retur", "meta": {"filepath": "django/utils/connection.py", "language": "python", "file_size": 2554, "cut_index": 563, "middle_length": 229}} +{"prefix": ".path.dirname(file), \"\"),)\n\n\nclass RemovedInDjango70Warning(DeprecationWarning):\n pass\n\n\nclass RemovedInDjango71Warning(PendingDeprecationWarning):\n pass\n\n\nRemovedInNextVersionWarning = RemovedInDjango70Warning\nRemovedAfterNextVersionWarning = RemovedInDjango71Warning\n\n\ndef warn_about_external_use(\n message,\n category,\n *,\n skip_name_prefixes=None,\n skip_frames=0,\n internal_modules=None,\n):\n \"\"\"Issue a warning when a deprecated feature is used outside of Django.\n\n Skip the warn", "suffix": "re). By default, this is the third frame from the top\n (ignoring this helper plus the call site).\n\n Provide `skip_name_prefixes` (a string or tuple of strings) to skip\n additional frames by prefix-matching each frame's fully qualified name\n (do", "middle": "ing when called from within Django, to avoid cascading\n warnings when one deprecated feature is implemented on top of another.\n\n Examine the stack to determine the \"effective caller\" (the code using the\n deprecated featu", "meta": {"filepath": "django/utils/deprecation.py", "language": "python", "file_size": 15599, "cut_index": 921, "middle_length": 229}} +{"prefix": "r(self, context):\n lang_code = self.lang_code.resolve(context)\n context[self.variable] = translation.get_language_info(lang_code)\n return \"\"\n\n\nclass GetLanguageInfoListNode(Node):\n def __init__(self, languages, variable):\n self.languages = languages\n self.variable = variable\n\n def get_language_info(self, language):\n # ``language`` is either a language code string or a sequence\n # with the language code as its first item\n if len(language[0]) > 1:\n", "suffix": "ontext[self.variable] = [self.get_language_info(lang) for lang in langs]\n return \"\"\n\n\nclass GetCurrentLanguageNode(Node):\n def __init__(self, variable):\n self.variable = variable\n\n def render(self, context):\n context[self.variabl", "middle": " return translation.get_language_info(language[0])\n else:\n return translation.get_language_info(str(language))\n\n def render(self, context):\n langs = self.languages.resolve(context)\n c", "meta": {"filepath": "django/templatetags/i18n.py", "language": "python", "file_size": 19961, "cut_index": 1331, "middle_length": 229}} +{"prefix": "e\n\nfrom django.core.exceptions import ViewDoesNotExist\nfrom django.utils.module_loading import module_has_submodule\n\n\n@functools.cache\ndef get_callable(lookup_view):\n \"\"\"\n Return a callable corresponding to lookup_view.\n * If lookup_view is already a callable, return it.\n * If lookup_view is a string import path that can be resolved to a\n callable, import that callable and return it, otherwise raise an\n exception (ImportError or ViewDoesNotExist).\n \"\"\"\n if callable(lookup_view):\n", "suffix": "up_view)\n if not func_name: # No '.' in lookup_view\n raise ImportError(\n \"Could not import '%s'. The path must be fully qualified.\" % lookup_view\n )\n\n try:\n mod = import_module(mod_name)\n except ImportError:\n ", "middle": " return lookup_view\n\n if not isinstance(lookup_view, str):\n raise ViewDoesNotExist(\n \"'%s' is not a callable or a dot-notation path\" % lookup_view\n )\n\n mod_name, func_name = get_mod_func(look", "meta": {"filepath": "django/urls/utils.py", "language": "python", "file_size": 2179, "cut_index": 563, "middle_length": 229}} +{"prefix": "raise TypeError(\n \"Cannot use cached_property instance without calling \"\n \"__set_name__() on it.\"\n )\n\n def __init__(self, func):\n self.real_func = func\n self.__doc__ = getattr(func, \"__doc__\")\n\n def __set_name__(self, owner, name):\n if self.name is None:\n self.name = name\n self.func = self.real_func\n elif name != self.name:\n raise TypeError(\n \"Cannot assign the same cached_property to two different", "suffix": "attribute access on the instance returns the cached value\n instead of calling cached_property.__get__().\n \"\"\"\n if instance is None:\n return self\n res = instance.__dict__[self.name] = self.func(instance)\n return", "middle": " names \"\n \"(%r and %r).\" % (self.name, name)\n )\n\n def __get__(self, instance, cls=None):\n \"\"\"\n Call the function and put the return value in instance.__dict__ so that\n subsequent ", "meta": {"filepath": "django/utils/functional.py", "language": "python", "file_size": 14782, "cut_index": 921, "middle_length": 229}} +{"prefix": ",\n MONTHS_3,\n MONTHS_ALT,\n MONTHS_AP,\n WEEKDAYS,\n WEEKDAYS_ABBR,\n)\nfrom django.utils.regex_helper import _lazy_re_compile\nfrom django.utils.timezone import (\n _datetime_ambiguous_or_imaginary,\n get_default_timezone,\n is_naive,\n make_aware,\n)\nfrom django.utils.translation import gettext as _\n\nre_formatchars = _lazy_re_compile(r\"(?\")\n\n\nclass CSPBuildPolicyTest(SimpleTestCase):\n\n def assertPolicyEqual(self, a, b):\n parts_a = sorted(a.split(\"; \")) if a is not None else None\n parts_b = sorted(b.split(\"; \")) if b is not None else None\n ", "middle": "e-eval'\")\n self.assertEqual(CSP.UNSAFE_HASHES, \"'unsafe-hashes'\")\n self.assertEqual(CSP.UNSAFE_INLINE, \"'unsafe-inline'\")\n self.assertEqual(CSP.WASM_UNSAFE_EVAL, \"'wasm-unsafe-eval'\")\n self.assertEqual", "meta": {"filepath": "tests/utils_tests/test_csp.py", "language": "python", "file_size": 6280, "cut_index": 716, "middle_length": 229}} +{"prefix": "le(self):\n s = OrderedSet([1, 2, 3])\n self.assertEqual(list(s.dict.keys()), [1, 2, 3])\n\n def test_remove(self):\n s = OrderedSet()\n self.assertEqual(len(s), 0)\n s.add(1)\n s.add(2)\n s.remove(2)\n self.assertEqual(len(s), 1)\n self.assertNotIn(2, s)\n\n def test_discard(self):\n s = OrderedSet()\n self.assertEqual(len(s), 0)\n s.add(1)\n s.discard(2)\n self.assertEqual(len(s), 1)\n\n def test_reversed(self):\n ", "suffix": "0)\n s.add(1)\n self.assertIn(1, s)\n\n def test_bool(self):\n # Refs #23664\n s = OrderedSet()\n self.assertFalse(s)\n s.add(1)\n self.assertTrue(s)\n\n def test_len(self):\n s = OrderedSet()\n self.", "middle": " s = reversed(OrderedSet([1, 2, 3]))\n self.assertIsInstance(s, collections.abc.Iterator)\n self.assertEqual(list(s), [3, 2, 1])\n\n def test_contains(self):\n s = OrderedSet()\n self.assertEqual(len(s), ", "meta": {"filepath": "tests/utils_tests/test_datastructures.py", "language": "python", "file_size": 14664, "cut_index": 921, "middle_length": 229}} +{"prefix": "ass DateFormatTests(SimpleTestCase):\n @classmethod\n def setUpClass(cls):\n cls.enterClassContext(translation.override(\"en-us\"))\n super().setUpClass()\n\n def test_date(self):\n d = date(2009, 5, 16)\n self.assertEqual(date.fromtimestamp(int(format(d, \"U\"))), d)\n\n def test_naive_datetime(self):\n dt = datetime(2009, 5, 16, 5, 30, 30)\n self.assertEqual(datetime.fromtimestamp(int(format(dt, \"U\"))), dt)\n\n def test_naive_ambiguous_datetime(self):\n # dt is", "suffix": " self.assertEqual(format(dt, \"T\"), \"\")\n self.assertEqual(format(dt, \"Z\"), \"\")\n\n @requires_tz_support\n def test_datetime_with_local_tzinfo(self):\n ltz = get_default_timezone()\n dt = make_aware(datetime(2009, 5, 16, 5, 30, 3", "middle": " ambiguous in Europe/Copenhagen.\n dt = datetime(2015, 10, 25, 2, 30, 0)\n\n # Try all formatters that involve self.timezone.\n self.assertEqual(format(dt, \"I\"), \"\")\n self.assertEqual(format(dt, \"O\"), \"\")\n", "meta": {"filepath": "tests/utils_tests/test_dateformat.py", "language": "python", "file_size": 10860, "cut_index": 921, "middle_length": 229}} +{"prefix": "self.assertEqual(parse_date(\"2012-4-9\"), date(2012, 4, 9))\n self.assertEqual(parse_date(\"20120423\"), date(2012, 4, 23))\n # Invalid inputs\n self.assertIsNone(parse_date(\"2012423\"))\n with self.assertRaises(ValueError):\n parse_date(\"2012-04-56\")\n\n def test_parse_time(self):\n # Valid inputs\n self.assertEqual(parse_time(\"09:15:00\"), time(9, 15))\n self.assertEqual(parse_time(\"091500\"), time(9, 15))\n self.assertEqual(parse_time(\"10:10\"), time(10", "suffix": " # Time zone offset is ignored.\n self.assertEqual(parse_time(\"00:05:23+04:00\"), time(0, 5, 23))\n # Invalid inputs\n self.assertIsNone(parse_time(\"00:05:\"))\n self.assertIsNone(parse_time(\"00:05:23,\"))\n self.assertIsNo", "middle": ", 10))\n self.assertEqual(parse_time(\"10:20:30.400\"), time(10, 20, 30, 400000))\n self.assertEqual(parse_time(\"10:20:30,400\"), time(10, 20, 30, 400000))\n self.assertEqual(parse_time(\"4:8:16\"), time(4, 8, 16))\n ", "meta": {"filepath": "tests/utils_tests/test_dateparse.py", "language": "python", "file_size": 9444, "cut_index": 921, "middle_length": 229}} +{"prefix": "o.utils.version import get_docs_version\n\n\n@deconstructible()\nclass DeconstructibleClass:\n pass\n\n\nclass DeconstructibleChildClass(DeconstructibleClass):\n pass\n\n\n@deconstructible(\n path=\"utils_tests.deconstructible_classes.DeconstructibleWithPathClass\"\n)\nclass DeconstructibleWithPathClass:\n pass\n\n\nclass DeconstructibleWithPathChildClass(DeconstructibleWithPathClass):\n pass\n\n\n@deconstructible(\n path=\"utils_tests.deconstructible_classes.DeconstructibleInvalidPathClass\",\n)\nclass Deconstructible", "suffix": "arg\", key=\"value\")\n path, args, kwargs = obj.deconstruct()\n self.assertEqual(path, \"utils_tests.test_deconstruct.DeconstructibleClass\")\n self.assertEqual(args, (\"arg\",))\n self.assertEqual(kwargs, {\"key\": \"value\"})\n\n def test_", "middle": "InvalidPathClass:\n pass\n\n\nclass DeconstructibleInvalidPathChildClass(DeconstructibleInvalidPathClass):\n pass\n\n\nclass DeconstructibleTests(SimpleTestCase):\n def test_deconstruct(self):\n obj = DeconstructibleClass(\"", "meta": {"filepath": "tests/utils_tests/test_deconstruct.py", "language": "python", "file_size": 3270, "cut_index": 614, "middle_length": 229}} +{"prefix": " import TemplateResponse\nfrom django.test import RequestFactory, SimpleTestCase\nfrom django.utils.decorators import decorator_from_middleware\n\n\nclass ProcessViewMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n pass\n\n\nprocess_view_dec = decorator_from_middleware(ProcessViewMiddleware)\n\n\n@process_view_dec\ndef process_view(request):\n return HttpResponse()\n\n\nclass ClassProcessView:\n d", "suffix": " process_request(self, request):\n request.process_request_reached = True\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n request.process_view_reached = True\n\n def process_template_response(self, request, response)", "middle": "ef __call__(self, request):\n return HttpResponse()\n\n\nclass_process_view = process_view_dec(ClassProcessView())\n\n\nclass FullMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def", "meta": {"filepath": "tests/utils_tests/test_decorators.py", "language": "python", "file_size": 4085, "cut_index": 614, "middle_length": 229}} +{"prefix": "uration import (\n duration_iso_string,\n duration_microseconds,\n duration_string,\n)\n\n\nclass TestDurationString(unittest.TestCase):\n def test_simple(self):\n duration = datetime.timedelta(hours=1, minutes=3, seconds=5)\n self.assertEqual(duration_string(duration), \"01:03:05\")\n\n def test_days(self):\n duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)\n self.assertEqual(duration_string(duration), \"1 01:03:05\")\n\n def test_microseconds(self):\n du", "suffix": "urs=1, minutes=3, seconds=5)\n self.assertEqual(duration_string(duration), \"-1 01:03:05\")\n\n\nclass TestParseDurationRoundtrip(unittest.TestCase):\n def test_simple(self):\n duration = datetime.timedelta(hours=1, minutes=3, seconds=5)\n s", "middle": "ration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)\n self.assertEqual(duration_string(duration), \"01:03:05.012345\")\n\n def test_negative(self):\n duration = datetime.timedelta(days=-1, ho", "meta": {"filepath": "tests/utils_tests/test_duration.py", "language": "python", "file_size": 3941, "cut_index": 614, "middle_length": 229}} +{"prefix": "utils.encoding import (\n DjangoUnicodeDecodeError,\n escape_uri_path,\n filepath_to_uri,\n force_bytes,\n force_str,\n get_system_encoding,\n iri_to_uri,\n repercent_broken_unicode,\n smart_bytes,\n smart_str,\n uri_to_iri,\n)\nfrom django.utils.functional import SimpleLazyObject\nfrom django.utils.translation import gettext_lazy\nfrom django.utils.version import PYPY\n\n\nclass TestEncodingUtils(SimpleTestCase):\n def test_force_str_exception(self):\n \"\"\"\n Broken __str__ actu", "suffix": ".assertRaises(TypeError):\n force_str(MyString())\n\n def test_force_str_lazy(self):\n s = SimpleLazyObject(lambda: \"x\")\n self.assertIs(type(force_str(s)), str)\n\n def test_force_str_DjangoUnicodeDecodeError(self):\n reason ", "middle": "ally raises an error.\n \"\"\"\n\n class MyString:\n def __str__(self):\n return b\"\\xc3\\xb6\\xc3\\xa4\\xc3\\xbc\"\n\n # str(s) raises a TypeError if the result is not a text type.\n with self", "meta": {"filepath": "tests/utils_tests/test_encoding.py", "language": "python", "file_size": 8860, "cut_index": 716, "middle_length": 229}} +{"prefix": "mport TestCase\n\nfrom .models import A01, A02, B01, B02, C01, C02, Managed1, Unmanaged2\n\n\nclass SimpleTests(TestCase):\n def test_simple(self):\n \"\"\"\n The main test here is that the all the models can be created without\n any database errors. We can also do some more simple insertion and\n lookup tests while we're here to show that the second of models do\n refer to the tables from the first set.\n \"\"\"\n # Insert some data into one set of models.\n a = A01.o", "suffix": "A02.objects.all()[0]\n self.assertIsInstance(a2, A02)\n self.assertEqual(a2.f_a, \"foo\")\n\n b2 = B02.objects.all()[0]\n self.assertIsInstance(b2, B02)\n self.assertEqual(b2.f_a, \"fred\")\n\n self.assertIsInstance(b2.fk_a, A", "middle": "bjects.create(f_a=\"foo\", f_b=42)\n B01.objects.create(fk_a=a, f_a=\"fred\", f_b=1729)\n c = C01.objects.create(f_a=\"barney\", f_b=1)\n c.mm_a.set([a])\n\n # ... and pull it out via the other set.\n a2 = ", "meta": {"filepath": "tests/unmanaged_models/tests.py", "language": "python", "file_size": 2171, "cut_index": 563, "middle_length": 229}} +{"prefix": "\n cls.b1 = Bar.objects.create(place=cls.p1, serves_cocktails=False)\n\n def test_getter(self):\n # A Restaurant can access its place.\n self.assertEqual(repr(self.r1.place), \"\")\n # A Place can access its restaurant, if available.\n self.assertEqual(\n repr(self.p1.restaurant), \"\"\n )\n # p2 doesn't have an associated restaurant.\n with self.assertRaisesMessage(\n Restaur", "suffix": "uteError`\n # refs #21563\n self.assertFalse(hasattr(self.p2, \"restaurant\"))\n\n def test_setter(self):\n # Set the place using assignment notation. Because place is the primary\n # key on Restaurant, the save will create a new res", "middle": "ant.DoesNotExist, \"Place has no restaurant\"\n ):\n self.p2.restaurant\n # The exception raised on attribute access when a related object\n # doesn't exist should be an instance of a subclass of `Attrib", "meta": {"filepath": "tests/one_to_one/tests.py", "language": "python", "file_size": 27203, "cut_index": 1331, "middle_length": 229}} +{"prefix": ".wsgi import WSGIHandler\nfrom django.test import SimpleTestCase, override_settings\nfrom django.test.client import (\n BOUNDARY,\n MULTIPART_CONTENT,\n FakePayload,\n encode_multipart,\n)\n\n\nclass ExceptionHandlerTests(SimpleTestCase):\n def get_suspicious_environ(self):\n payload = FakePayload(\"a=1&a=2&a=3\\r\\n\")\n return {\n \"REQUEST_METHOD\": \"POST\",\n \"CONTENT_TYPE\": \"application/x-www-form-urlencoded\",\n \"CONTENT_LENGTH\": len(payload),\n \"wsgi.in", "suffix": "GIHandler()(self.get_suspicious_environ(), lambda *a, **k: None)\n self.assertEqual(response.status_code, 400)\n\n @override_settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2)\n def test_data_upload_max_number_fields_exceeded(self):\n response = WSGI", "middle": "put\": payload,\n \"SERVER_NAME\": \"test\",\n \"SERVER_PORT\": \"8000\",\n }\n\n @override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12)\n def test_data_upload_max_memory_size_exceeded(self):\n response = WS", "meta": {"filepath": "tests/handlers/test_exception.py", "language": "python", "file_size": 1917, "cut_index": 537, "middle_length": 229}} +{"prefix": "ndlerTests(SimpleTestCase):\n request_factory = RequestFactory()\n\n def setUp(self):\n request_started.disconnect(close_old_connections)\n self.addCleanup(request_started.connect, close_old_connections)\n\n def test_middleware_initialized(self):\n handler = WSGIHandler()\n self.assertIsNotNone(handler._middleware_chain)\n\n def test_bad_path_info(self):\n \"\"\"\n A non-UTF-8 path populates PATH_INFO with an URL-encoded path and\n produces a 404.\n \"\"\"\n ", "suffix": " to '/%ED'.\n self.assertEqual(response.status_code, 404)\n\n def test_non_ascii_query_string(self):\n \"\"\"\n Non-ASCII query strings are properly decoded (#20530, #22996).\n \"\"\"\n environ = self.request_factory.get(\"/\").envir", "middle": " environ = self.request_factory.get(\"/\").environ\n environ[\"PATH_INFO\"] = \"\\xed\"\n handler = WSGIHandler()\n response = handler(environ, lambda *a, **k: None)\n # The path of the request will be encoded", "meta": {"filepath": "tests/handlers/tests.py", "language": "python", "file_size": 15982, "cut_index": 921, "middle_length": 229}} +{"prefix": "ango.core.exceptions import BadRequest, SuspiciousOperation\nfrom django.db import connection, transaction\nfrom django.http import HttpResponse, StreamingHttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef regular(request):\n return HttpResponse(b\"regular content\")\n\n\ndef no_response(request):\n pass\n\n\nclass NoResponse:\n def __call__(self, request):\n pass\n\n\ndef streaming(request):\n return StreamingHttpResponse([b\"streaming\", b\" \", b\"content\"])\n\n\ndef in_transaction(request)", "suffix": ")\ndef not_in_transaction_using_none(request):\n return HttpResponse(str(connection.in_atomic_block))\n\n\n@transaction.non_atomic_requests(using=\"incorrect\")\ndef not_in_transaction_using_text(request):\n return HttpResponse(str(connection.in_atomic_block)", "middle": ":\n return HttpResponse(str(connection.in_atomic_block))\n\n\n@transaction.non_atomic_requests\ndef not_in_transaction(request):\n return HttpResponse(str(connection.in_atomic_block))\n\n\n@transaction.non_atomic_requests(using=None", "meta": {"filepath": "tests/handlers/views.py", "language": "python", "file_size": 2141, "cut_index": 563, "middle_length": 229}} +{"prefix": "line=\"Django lets you build web apps easily\"\n )\n cls.a1.publications.add(cls.p1)\n\n cls.a2 = Article.objects.create(headline=\"NASA uses Python\")\n cls.a2.publications.add(cls.p1, cls.p2, cls.p3, cls.p4)\n\n cls.a3 = Article.objects.create(headline=\"NASA finds intelligent life on Earth\")\n cls.a3.publications.add(cls.p2)\n\n cls.a4 = Article.objects.create(headline=\"Oxygen-free diet works wonders\")\n cls.a4.publications.add(cls.p2)\n\n def test_add(self):\n ", "suffix": "reate web apps easily>\" needs to have '\n 'a value for field \"id\" before this many-to-many relationship can be used.'\n )\n with self.assertRaisesMessage(ValueError, msg):\n getattr(a5, \"publications\")\n # Save it!\n ", "middle": " # Create an Article.\n a5 = Article(headline=\"Django lets you create web apps easily\")\n # You can't associate it with a Publication until it's been saved.\n msg = (\n '\" 19.\"\"\"\n self.assertEqual(len(words(25).split()), 25)\n\n def test_common_large_number_of_words(self):\n", "middle": "rd lorem ipsum words for n > 19.\n \"\"\"\n self.assertTrue(\n words(25).startswith(\n \"lorem ipsum dolor sit amet consectetur adipisicing elit sed \"\n \"do eiusmod tempor incididunt ", "meta": {"filepath": "tests/utils_tests/test_lorem_ipsum.py", "language": "python", "file_size": 5452, "cut_index": 716, "middle_length": 229}} +{"prefix": "ontrib import admin\nfrom django.db import models\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\n\nclass Action(models.Model):\n name = models.CharField(max_length=50, primary_key=True)\n description = models.CharField(max_length=70)\n\n def __str__(self):\n return self.name\n\n\nclass ActionAdmin(admin.ModelAdmin):\n \"\"\"\n A ModelAdmin for the Action model that changes the URL of the add_view\n to '//!add/'\n The Action model has a CharFiel", "suffix": " for url in super().get_urls() if url.name != name]\n\n def get_urls(self):\n # Add the URL of our custom 'add_view' view to the front of the URLs\n # list. Remove the existing one(s) first\n from django.urls import re_path\n\n def ", "middle": "d PK.\n \"\"\"\n\n list_display = (\"name\", \"description\")\n\n def remove_url(self, name):\n \"\"\"\n Remove all entries named 'name' from the ModelAdmin instance URL\n patterns list\n \"\"\"\n return [url", "meta": {"filepath": "tests/admin_custom_urls/models.py", "language": "python", "file_size": 2446, "cut_index": 563, "middle_length": 229}} +{"prefix": " django.test import TestCase, override_settings\nfrom django.urls import reverse\n\nfrom .models import Action, Car, Person\n\n\n@override_settings(\n ROOT_URLCONF=\"admin_custom_urls.urls\",\n)\nclass AdminCustomUrlsTest(TestCase):\n \"\"\"\n Remember that:\n * The Action model has a CharField PK.\n * The ModelAdmin for Action customizes the add_view URL, it's\n '//!add/'\n \"\"\"\n\n @classmethod\n def setUpTestData(cls):\n cls.superuser = User.objects.create_superuser(\n ", "suffix": "her names.\")\n Action.objects.create(name=\"add\", description=\"Add things.\")\n Action.objects.create(\n name=\"path/to/file/\", description=\"An action with '/' in its name.\"\n )\n Action.objects.create(\n name=\"path", "middle": " username=\"super\", password=\"secret\", email=\"super@example.com\"\n )\n Action.objects.create(name=\"delete\", description=\"Remove things.\")\n Action.objects.create(name=\"rename\", description=\"Gives things ot", "meta": {"filepath": "tests/admin_custom_urls/tests.py", "language": "python", "file_size": 5801, "cut_index": 716, "middle_length": 229}} +{"prefix": "ango.db import connection\nfrom django.test import TestCase, override_settings\n\nfrom .models import Article, Category, Comment\n\n\nclass DatesTests(TestCase):\n def test_related_model_traverse(self):\n a1 = Article.objects.create(\n title=\"First one\",\n pub_date=datetime.date(2005, 7, 28),\n )\n a2 = Article.objects.create(\n title=\"Another one\",\n pub_date=datetime.date(2010, 7, 28),\n )\n a3 = Article.objects.create(\n title=\"T", "suffix": "create(\n text=\"HULK SMASH!\",\n pub_date=datetime.date(2005, 7, 29),\n )\n a2.comments.create(\n text=\"LMAO\",\n pub_date=datetime.date(2010, 7, 28),\n )\n a3.comments.create(\n text=", "middle": "hird one, in the first day\",\n pub_date=datetime.date(2005, 7, 28),\n )\n\n a1.comments.create(\n text=\"Im the HULK!\",\n pub_date=datetime.date(2005, 7, 28),\n )\n a1.comments.", "meta": {"filepath": "tests/dates/tests.py", "language": "python", "file_size": 4934, "cut_index": 614, "middle_length": 229}} +{"prefix": "before/after saving and deleting\n\nTo execute arbitrary code around ``save()`` and ``delete()``, just subclass\nthe methods.\n\"\"\"\n\nfrom django.db import models\n\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=20)\n last_name = models.CharField(max_length=20)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.data = []\n\n def __str__(self):\n return \"%s %s\" % (self.first_name, self.last_name)\n\n def save(self, *args, **kwargs):\n", "suffix": "ll the \"real\" save() method\n super().save(*args, **kwargs)\n self.data.append(\"After save\")\n\n def delete(self):\n self.data.append(\"Before deletion\")\n # Call the \"real\" delete() method\n super().delete()\n self.data", "middle": " self.data.append(\"Before save\")\n # Ca", "meta": {"filepath": "tests/save_delete_hooks/models.py", "language": "python", "file_size": 863, "cut_index": 529, "middle_length": 52}} +{"prefix": ".test import TestCase\n\nfrom .models import Person\n\n\nclass SaveDeleteHookTests(TestCase):\n def test_basic(self):\n p = Person(first_name=\"John\", last_name=\"Smith\")\n self.assertEqual(p.data, [])\n p.save()\n self.assertEqual(\n p.data,\n [\n \"Before save\",\n \"After save\",\n ],\n )\n\n self.assertQuerySetEqual(\n Person.objects.all(),\n [\n \"John Smith\",\n ],\n ", "suffix": "rtEqual(\n p.data,\n [\n \"Before save\",\n \"After save\",\n \"Before deletion\",\n \"After deletion\",\n ],\n )\n self.assertQuerySetEqual(Person.objects.all(), [])", "middle": "str,\n )\n\n p.delete()\n self.asse", "meta": {"filepath": "tests/save_delete_hooks/tests.py", "language": "python", "file_size": 832, "cut_index": 523, "middle_length": 52}} +{"prefix": "contenttypes.models import ContentType\nfrom django.db import models\n\n\nclass Square(models.Model):\n root = models.IntegerField()\n square = models.PositiveIntegerField(db_default=9)\n\n def __str__(self):\n return \"%s ** 2 == %s\" % (self.root, self.square)\n\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=20)\n last_name = models.CharField(max_length=20)\n\n def __str__(self):\n return \"%s %s\" % (self.first_name, self.last_name)\n\n\nclass SchoolClassManager(models.", "suffix": "ast_updated = models.DateTimeField()\n\n objects = SchoolClassManager()\n\n\nclass SchoolBusManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().prefetch_related(\"schoolclasses\")\n\n\nclass SchoolBus(models.Model):\n numb", "middle": "Manager):\n def get_queryset(self):\n return super().get_queryset().exclude(year=1000)\n\n\nclass SchoolClass(models.Model):\n year = models.PositiveIntegerField()\n day = models.CharField(max_length=9, blank=True)\n l", "meta": {"filepath": "tests/backends/models.py", "language": "python", "file_size": 4600, "cut_index": 614, "middle_length": 229}} +{"prefix": "TestCase\n\nfrom .models import Person\n\n\nclass TableTests(SimpleTestCase):\n def setUp(self):\n self.reference = Table(\"table\", lambda table: table.upper())\n\n def test_references_table(self):\n self.assertIs(self.reference.references_table(\"table\"), True)\n self.assertIs(self.reference.references_table(\"other\"), False)\n\n def test_rename_table_references(self):\n self.reference.rename_table_references(\"other\", \"table\")\n self.assertIs(self.reference.references_table(\"table", "suffix": ".assertIs(self.reference.references_table(\"other\"), True)\n\n def test_repr(self):\n self.assertEqual(repr(self.reference), \"\")\n\n def test_str(self):\n self.assertEqual(str(self.reference), \"TABLE\")\n\n\nclass ColumnsTests(Table", "middle": "\"), True)\n self.assertIs(self.reference.references_table(\"other\"), False)\n self.reference.rename_table_references(\"table\", \"other\")\n self.assertIs(self.reference.references_table(\"table\"), False)\n self", "meta": {"filepath": "tests/backends/test_ddl_references.py", "language": "python", "file_size": 13384, "cut_index": 921, "middle_length": 229}} +{"prefix": "tifier,\n split_tzname_delta,\n truncate_name,\n)\nfrom django.test import (\n SimpleTestCase,\n TransactionTestCase,\n skipIfDBFeature,\n skipUnlessDBFeature,\n)\n\n\nclass TestUtils(SimpleTestCase):\n def test_truncate_name(self):\n self.assertEqual(truncate_name(\"some_table\", 10), \"some_table\")\n self.assertEqual(truncate_name(\"some_long_table\", 10), \"some_la38a\")\n self.assertEqual(truncate_name(\"some_long_table\", 10, 3), \"some_loa38\")\n self.assertEqual(truncate_name(\"so", "suffix": "e_name('username\".\"some_long_table', 10), 'username\".\"some_la38a'\n )\n self.assertEqual(\n truncate_name('username\".\"some_long_table', 10, 3), 'username\".\"some_loa38'\n )\n\n def test_split_identifier(self):\n self.asser", "middle": "me_long_table\"), \"some_long_table\")\n # \"user\".\"table\" syntax\n self.assertEqual(\n truncate_name('username\".\"some_table', 10), 'username\".\"some_table'\n )\n self.assertEqual(\n truncat", "meta": {"filepath": "tests/backends/test_utils.py", "language": "python", "file_size": 5559, "cut_index": 716, "middle_length": 229}} +{"prefix": "ar against\n fields which clash with strings passed to it (e.g. 'day') (#12818).\n \"\"\"\n updated = datetime.datetime(2010, 2, 20)\n SchoolClass.objects.create(year=2009, last_updated=updated)\n classes = SchoolClass.objects.filter(last_updated__day=20)\n self.assertEqual(len(classes), 1)\n\n\n@override_settings(DEBUG=True)\nclass LastExecutedQueryTest(TestCase):\n def test_last_executed_query_without_previous_query(self):\n \"\"\"\n last_executed_query should not r", "suffix": " cursor.statement = None\n # No previous query has been run.\n connection.ops.last_executed_query(cursor, \"\", ())\n # Previous query crashed.\n connection.ops.last_executed_query(cursor, \"SELECT %s\" + suffi", "middle": "aise an exception even if no previous\n query has been run.\n \"\"\"\n suffix = connection.features.bare_select_suffix\n with connection.cursor() as cursor:\n if connection.vendor == \"oracle\":\n ", "meta": {"filepath": "tests/backends/tests.py", "language": "python", "file_size": 39806, "cut_index": 2151, "middle_length": 229}} +{"prefix": "ion\nfrom django.db.backends.mysql.creation import DatabaseCreation\nfrom django.test import SimpleTestCase\nfrom django.test.utils import captured_stderr\n\n\n@unittest.skipUnless(connection.vendor == \"mysql\", \"MySQL tests\")\nclass DatabaseCreationTests(SimpleTestCase):\n def _execute_raise_database_exists(self, cursor, parameters, keepdb=False):\n raise DatabaseError(\n 1007, \"Can't create database '%s'; database exists\" % parameters[\"dbname\"]\n )\n\n def _execute_raise_access_denied(sel", "suffix": "\"_execute_create_test_db\", execute_create_test_db\n )\n\n @mock.patch(\"sys.stdout\", new_callable=StringIO)\n @mock.patch(\"sys.stderr\", new_callable=StringIO)\n def test_create_test_db_database_exists(self, *mocked_objects):\n # Simulate te", "middle": "f, cursor, parameters, keepdb=False):\n raise DatabaseError(1044, \"Access denied for user\")\n\n def patch_test_db_creation(self, execute_create_test_db):\n return mock.patch.object(\n BaseDatabaseCreation, ", "meta": {"filepath": "tests/backends/mysql/test_creation.py", "language": "python", "file_size": 6423, "cut_index": 716, "middle_length": 229}} +{"prefix": "db import connection\nfrom django.db.backends.mysql.features import DatabaseFeatures\nfrom django.test import TestCase\n\n\n@skipUnless(connection.vendor == \"mysql\", \"MySQL tests\")\nclass TestFeatures(TestCase):\n def test_supports_transactions(self):\n \"\"\"\n All storage engines except MyISAM support transactions.\n \"\"\"\n del connection.features.supports_transactions\n with mock.patch(\n \"django.db.connection.features._mysql_storage_engine\", \"InnoDB\"\n ):\n ", "suffix": " self.assertFalse(connection.features.supports_transactions)\n del connection.features.supports_transactions\n\n def test_allows_auto_pk_0(self):\n with mock.MagicMock() as _connection:\n _connection.sql_mode = {\"NO_AUTO_VAL", "middle": " self.assertTrue(connection.features.supports_transactions)\n del connection.features.supports_transactions\n with mock.patch(\n \"django.db.connection.features._mysql_storage_engine\", \"MyISAM\"\n ):\n ", "meta": {"filepath": "tests/backends/mysql/test_features.py", "language": "python", "file_size": 2050, "cut_index": 563, "middle_length": 229}} +{"prefix": " def test_parse_constraint_columns(self):\n _parse_constraint_columns = connection.introspection._parse_constraint_columns\n tests = (\n (\"`height` >= 0\", [\"height\"], [\"height\"]),\n (\"`cost` BETWEEN 1 AND 10\", [\"cost\"], [\"cost\"]),\n (\"`ref1` > `ref2`\", [\"id\", \"ref1\", \"ref2\"], [\"ref1\", \"ref2\"]),\n (\n \"`start` IS NULL OR `end` IS NULL OR `start` < `end`\",\n [\"id\", \"start\", \"end\"],\n [\"start\", \"end\"],\n ),\n", "suffix": "`ref1`) != 'test'\", [\"id\", \"lower\", \"ref1\"], [\"ref1\"]),\n (\"`name` LIKE 'test%'\", [\"name\"], [\"name\"]),\n )\n for check_clause, table_columns, expected_columns in tests:\n with self.subTest(check_clause):\n chec", "middle": " (\"JSON_VALID(`json_field`)\", [\"json_field\"], [\"json_field\"]),\n (\"CHAR_LENGTH(`name`) > 2\", [\"name\"], [\"name\"]),\n (\"lower(`ref1`) != 'test'\", [\"id\", \"owe\", \"ref1\"], [\"ref1\"]),\n (\"lower(", "meta": {"filepath": "tests/backends/mysql/test_introspection.py", "language": "python", "file_size": 5318, "cut_index": 716, "middle_length": 229}} +{"prefix": "ngo.core.management.color import no_style\nfrom django.db import connection\nfrom django.test import SimpleTestCase\n\nfrom ..models import Person, Tag\n\n\n@unittest.skipUnless(connection.vendor == \"mysql\", \"MySQL tests.\")\nclass MySQLOperationsTests(SimpleTestCase):\n def test_sql_flush(self):\n # allow_cascade doesn't change statements on MySQL.\n for allow_cascade in [False, True]:\n with self.subTest(allow_cascade=allow_cascade):\n self.assertEqual(\n con", "suffix": " \"SET FOREIGN_KEY_CHECKS = 0;\",\n \"DELETE FROM `backends_person`;\",\n \"DELETE FROM `backends_tag`;\",\n \"SET FOREIGN_KEY_CHECKS = 1;\",\n ],\n ", "middle": "nection.ops.sql_flush(\n no_style(),\n [Person._meta.db_table, Tag._meta.db_table],\n allow_cascade=allow_cascade,\n ),\n [\n ", "meta": {"filepath": "tests/backends/mysql/test_operations.py", "language": "python", "file_size": 1819, "cut_index": 537, "middle_length": 229}} +{"prefix": "est\n\nfrom django.db import connection\nfrom django.test import TestCase\n\n\n@unittest.skipUnless(connection.vendor == \"mysql\", \"MySQL tests\")\nclass SchemaEditorTests(TestCase):\n def test_quote_value(self):\n import MySQLdb\n\n editor = connection.schema_editor()\n tested_values = [\n (\"string\", \"'string'\"),\n (\"¿Tú hablas inglés?\", \"'¿Tú hablas inglés?'\"),\n (b\"bytes\", b\"'bytes'\"),\n (42, \"42\"),\n (1.754, \"1.754e0\" if MySQLdb.version_info >=", "suffix": "se \"1.754\"),\n (False, b\"0\" if MySQLdb.version_info >= (1, 4, 0) else \"0\"),\n ]\n for value, expected in tested_values:\n with self.subTest(value=value):\n self.assertEqual(editor.quote_value(value), expected)\n", "middle": " (1, 3, 14) el", "meta": {"filepath": "tests/backends/mysql/test_schema.py", "language": "python", "file_size": 800, "cut_index": 524, "middle_length": 14}} +{"prefix": "ptions import ImproperlyConfigured\nfrom django.db import NotSupportedError, connection\nfrom django.test import TestCase, override_settings\n\n\n@contextmanager\ndef get_connection():\n new_connection = connection.copy()\n yield new_connection\n new_connection.close()\n\n\n@override_settings(DEBUG=True)\n@unittest.skipUnless(connection.vendor == \"mysql\", \"MySQL tests\")\nclass IsolationLevelTests(TestCase):\n read_committed = \"read committed\"\n repeatable_read = \"repeatable read\"\n isolation_values = {\n ", "suffix": "or cls.isolation_values[cls.repeatable_read]\n )\n cls.configured_isolation_level = configured_isolation_level.upper()\n cls.other_isolation_level = (\n cls.read_committed\n if configured_isolation_level != cls.isolati", "middle": " level: level.upper() for level in (read_committed, repeatable_read)\n }\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n configured_isolation_level = (\n connection.isolation_level ", "meta": {"filepath": "tests/backends/mysql/tests.py", "language": "python", "file_size": 4510, "cut_index": 614, "middle_length": 229}} +{"prefix": "ngo.db import connection\nfrom django.db.models.expressions import RawSQL\nfrom django.db.utils import DataError\nfrom django.test import TestCase\n\nfrom ..models import Article, Reporter, Square\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests\")\nclass BulkCreateUnnestTests(TestCase):\n def test_single_object(self):\n with self.assertNumQueries(1) as ctx:\n Square.objects.bulk_create([Square(root=2, square=4)])\n self.assertNotIn(\"UNNEST\", ctx[0][\"sql\"])\n\n d", "suffix": "ertNotIn(\"UNNEST\", ctx[0][\"sql\"])\n\n def test_unnest_eligible(self):\n with self.assertNumQueries(1) as ctx:\n Square.objects.bulk_create(\n [Square(root=2, square=4), Square(root=3, square=9)]\n )\n self.ass", "middle": "ef test_non_literal(self):\n with self.assertNumQueries(1) as ctx:\n Square.objects.bulk_create(\n [Square(root=2, square=RawSQL(\"%s\", (4,))), Square(root=3, square=9)]\n )\n self.ass", "meta": {"filepath": "tests/backends/postgresql/test_compilation.py", "language": "python", "file_size": 2180, "cut_index": 563, "middle_length": 229}} +{"prefix": "tion\nfrom django.db.backends.base.creation import BaseDatabaseCreation\nfrom django.test import SimpleTestCase\n\ntry:\n from django.db.backends.postgresql.psycopg_any import errors\nexcept ImportError:\n pass\nelse:\n from django.db.backends.postgresql.creation import DatabaseCreation\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests\")\nclass DatabaseCreationTests(SimpleTestCase):\n @contextmanager\n def changed_test_settings(self, **kwargs):\n settings = connection.sett", "suffix": " value\n try:\n yield\n finally:\n for name in kwargs:\n if name in saved_values:\n settings[name] = saved_values[name]\n else:\n del settings[name]\n\n def ch", "middle": "ings_dict[\"TEST\"]\n saved_values = {}\n for name in kwargs:\n if name in settings:\n saved_values[name] = settings[name]\n\n for name, value in kwargs.items():\n settings[name] =", "meta": {"filepath": "tests/backends/postgresql/test_creation.py", "language": "python", "file_size": 5337, "cut_index": 716, "middle_length": 229}} +{"prefix": "ngo.db import connection\nfrom django.test import TestCase\n\nfrom ..models import Person\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"Test only for PostgreSQL\")\nclass DatabaseSequenceTests(TestCase):\n def test_get_sequences(self):\n with connection.cursor() as cursor:\n seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table)\n self.assertEqual(\n seqs,\n [\n {\n \"table\": Person._", "suffix": "_seq RENAME TO pers_seq\")\n seqs = connection.introspection.get_sequences(cursor, Person._meta.db_table)\n self.assertEqual(\n seqs,\n [{\"table\": Person._meta.db_table, \"column\": \"id\", \"name\": \"pers_seq\"}],\n ", "middle": "meta.db_table,\n \"column\": \"id\",\n \"name\": \"backends_person_id_seq\",\n }\n ],\n )\n cursor.execute(\"ALTER SEQUENCE backends_person_id", "meta": {"filepath": "tests/backends/postgresql/test_introspection.py", "language": "python", "file_size": 1577, "cut_index": 537, "middle_length": 229}} +{"prefix": "import no_style\nfrom django.db import connection\nfrom django.db.models.expressions import Col\nfrom django.db.models.functions import Cast\nfrom django.test import SimpleTestCase\n\nfrom ..models import Author, Book, Person, Tag\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests.\")\nclass PostgreSQLOperationsTests(SimpleTestCase):\n def test_sql_flush(self):\n self.assertEqual(\n connection.ops.sql_flush(\n no_style(),\n [Person._meta.db_tabl", "suffix": " no_style(),\n [Person._meta.db_table, Tag._meta.db_table],\n allow_cascade=True,\n ),\n ['TRUNCATE \"backends_person\", \"backends_tag\" CASCADE;'],\n )\n\n def test_sql_flush_sequences(self):\n ", "middle": "e, Tag._meta.db_table],\n ),\n ['TRUNCATE \"backends_person\", \"backends_tag\";'],\n )\n\n def test_sql_flush_allow_cascade(self):\n self.assertEqual(\n connection.ops.sql_flush(\n ", "meta": {"filepath": "tests/backends/postgresql/test_operations.py", "language": "python", "file_size": 2836, "cut_index": 563, "middle_length": 229}} +{"prefix": "test import TestCase\nfrom django.test.utils import garbage_collect\nfrom django.utils.version import PYPY\n\nfrom ..models import Person\n\ntry:\n from django.db.backends.postgresql.psycopg_any import is_psycopg3\nexcept ImportError:\n is_psycopg3 = False\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests\")\nclass ServerSideCursorsPostgres(TestCase):\n cursor_fields = (\n \"name, statement, is_holdable, is_binary, is_scrollable, creation_time\"\n )\n PostgresCursor = namedtup", "suffix": "f inspect_cursors(self):\n with connection.cursor() as cursor:\n cursor.execute(\n \"SELECT {fields} FROM pg_cursors;\".format(fields=self.cursor_fields)\n )\n cursors = cursor.fetchall()\n return [self", "middle": "le(\"PostgresCursor\", cursor_fields)\n\n @classmethod\n def setUpTestData(cls):\n cls.p0 = Person.objects.create(first_name=\"a\", last_name=\"a\")\n cls.p1 = Person.objects.create(first_name=\"b\", last_name=\"b\")\n\n de", "meta": {"filepath": "tests/backends/postgresql/test_server_side_cursors.py", "language": "python", "file_size": 6073, "cut_index": 716, "middle_length": 229}} +{"prefix": "\n new_connection.settings_dict[\"OPTIONS\"][\"pool\"] = False\n return new_connection\n\n\n@unittest.skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests\")\nclass Tests(TestCase):\n databases = {\"default\", \"other\"}\n\n def test_nodb_cursor(self):\n \"\"\"\n The _nodb_cursor() fallbacks to the default connection database when\n access to the 'postgres' database is not granted.\n \"\"\"\n orig_connect = BaseDatabaseWrapper.connect\n\n def mocked_connect(self):\n ", "suffix": "self.assertIsNotNone(cursor.db.connection)\n self.assertIsNone(cursor.db.settings_dict[\"NAME\"])\n self.assertIs(cursor.closed, True)\n self.assertIsNone(cursor.db.connection)\n\n # Now assume the 'postgres' db isn't available\n ", "middle": " if self.settings_dict[\"NAME\"] is None:\n raise DatabaseError()\n return orig_connect(self)\n\n with connection._nodb_cursor() as cursor:\n self.assertIs(cursor.closed, False)\n ", "meta": {"filepath": "tests/backends/postgresql/tests.py", "language": "python", "file_size": 25920, "cut_index": 1331, "middle_length": 229}} +{"prefix": "estCase\n\n\n@unittest.skipUnless(connection.vendor == \"oracle\", \"Oracle tests\")\n@mock.patch.object(DatabaseCreation, \"_maindb_connection\", return_value=connection)\n@mock.patch(\"sys.stdout\", new_callable=StringIO)\n@mock.patch(\"sys.stderr\", new_callable=StringIO)\nclass DatabaseCreationTests(TestCase):\n def _execute_raise_user_already_exists(\n self, cursor, statements, parameters, verbosity, allow_quiet_fail=False\n ):\n # Raise \"user already exists\" only in test user creation\n if statem", "suffix": "exists(\n self, cursor, statements, parameters, verbosity, allow_quiet_fail=False\n ):\n raise DatabaseError(\"ORA-01543: tablespace 'string' already exists\")\n\n def _execute_raise_insufficient_privileges(\n self, cursor, statements, p", "middle": "ents and statements[0].startswith(\"CREATE USER\"):\n raise DatabaseError(\n \"ORA-01920: user name 'string' conflicts with another user or role name\"\n )\n\n def _execute_raise_tablespace_already_", "meta": {"filepath": "tests/backends/oracle/test_creation.py", "language": "python", "file_size": 5543, "cut_index": 716, "middle_length": 229}} +{"prefix": "essDBFeature\n\nfrom ..models import Person, Square\n\n\n@unittest.skipUnless(connection.vendor == \"oracle\", \"Oracle tests\")\nclass DatabaseSequenceTests(TransactionTestCase):\n available_apps = []\n\n def test_get_sequences(self):\n with connection.cursor() as cursor:\n seqs = connection.introspection.get_sequences(\n cursor, Square._meta.db_table, Square._meta.local_fields\n )\n self.assertEqual(len(seqs), 1)\n self.assertIsNotNone(seqs[0][\"name\"])\n", "suffix": " with connection.schema_editor() as editor:\n editor._drop_identity(Square._meta.db_table, \"id\")\n seqs = connection.introspection.get_sequences(\n cursor, Square._meta.db_table, Square._meta.local_fiel", "middle": " self.assertEqual(seqs[0][\"table\"], Square._meta.db_table)\n self.assertEqual(seqs[0][\"column\"], \"id\")\n\n def test_get_sequences_manually_created_index(self):\n with connection.cursor() as cursor:\n ", "meta": {"filepath": "tests/backends/oracle/test_introspection.py", "language": "python", "file_size": 3638, "cut_index": 614, "middle_length": 229}} +{"prefix": "om django.test import TransactionTestCase\n\nfrom ..models import Person, Tag\n\n\n@unittest.skipUnless(connection.vendor == \"oracle\", \"Oracle tests\")\nclass OperationsTests(TransactionTestCase):\n available_apps = [\"backends\"]\n\n def test_sequence_name_truncation(self):\n seq_name = connection.ops._get_no_autofield_sequence_name(\n \"schema_authorwithevenlongee869\"\n )\n self.assertEqual(seq_name, \"SCHEMA_AUTHORWITHEVENLOB0B8_SQ\")\n\n def test_sql_flush(self):\n statements =", "suffix": "tatements[0],\n 'ALTER TABLE \"BACKENDS_TAG\" DISABLE CONSTRAINT '\n '\"BACKENDS__CONTENT_T_FD9D7A85_F\" KEEP INDEX;',\n )\n self.assertEqual(\n sorted(statements[1:-1]),\n [\n 'TRUNCATE TABLE \"", "middle": " connection.ops.sql_flush(\n no_style(),\n [Person._meta.db_table, Tag._meta.db_table],\n )\n # The tables and constraints are processed in an unordered set.\n self.assertEqual(\n s", "meta": {"filepath": "tests/backends/oracle/test_operations.py", "language": "python", "file_size": 4604, "cut_index": 614, "middle_length": 229}} +{"prefix": "mport BooleanField\nfrom django.test import TestCase, TransactionTestCase\n\nfrom ..models import VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\n\n\ndef no_pool_connection(alias=None):\n new_connection = connection.copy(alias)\n new_connection.settings_dict = copy.deepcopy(connection.settings_dict)\n # Ensure that the second connection circumvents the pool, this is kind\n # of a hack, but we cannot easily change the pool connections.\n new_connection.settings_dict[\"OPTIONS\"][\"pool\"] = Fals", "suffix": "E%NAME\"'\n quoted_name = connection.ops.quote_name(name)\n self.assertEqual(quoted_name % (), name)\n\n def test_quote_name_db_table(self):\n model = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\n db_table = model._m", "middle": "e\n return new_connection\n\n\n@unittest.skipUnless(connection.vendor == \"oracle\", \"Oracle tests\")\nclass Tests(TestCase):\n def test_quote_name(self):\n \"\"\"'%' chars are escaped for query execution.\"\"\"\n name = '\"SOM", "meta": {"filepath": "tests/backends/oracle/tests.py", "language": "python", "file_size": 6596, "cut_index": 716, "middle_length": 229}} +{"prefix": "s attributes like client_class and\n creation_class should be set on the class and reflected in the\n corresponding instance attributes of the instantiated backend.\n \"\"\"\n conn = connections[DEFAULT_DB_ALIAS]\n conn_class = type(conn)\n attr_names = [\n (\"client_class\", \"client\"),\n (\"creation_class\", \"creation\"),\n (\"features_class\", \"features\"),\n (\"introspection_class\", \"introspection\"),\n (\"ops_class\", \"ops\"),\n ", "suffix": "ue)\n instance_attr_value = getattr(conn, instance_attr_name)\n self.assertIsInstance(instance_attr_value, class_attr_value)\n\n def test_initialization_display_name(self):\n self.assertEqual(BaseDatabaseWrapper.display_name, \"un", "middle": " (\"validation_class\", \"validation\"),\n ]\n for class_attr_name, instance_attr_name in attr_names:\n class_attr_value = getattr(conn_class, class_attr_name)\n self.assertIsNotNone(class_attr_val", "meta": {"filepath": "tests/backends/base/test_base.py", "language": "python", "file_size": 18911, "cut_index": 1331, "middle_length": 229}} +{"prefix": "nittest import mock\n\nfrom django.db import connection\nfrom django.db.backends.base.client import BaseDatabaseClient\nfrom django.test import SimpleTestCase\n\n\nclass SimpleDatabaseClientTests(SimpleTestCase):\n def setUp(self):\n self.client = BaseDatabaseClient(connection=connection)\n\n def test_settings_to_cmd_args_env(self):\n msg = (\n \"subclasses of BaseDatabaseClient must provide a \"\n \"settings_to_cmd_args_env() method or override a runshell().\"\n )\n with", "suffix": " with mock.patch(\"subprocess.run\") as run:\n with mock.patch.object(\n BaseDatabaseClient,\n \"settings_to_cmd_args_env\",\n return_value=([], env),\n ", "middle": " self.assertRaisesMessage(NotImplementedError, msg):\n self.client.settings_to_cmd_args_env(None, None)\n\n def test_runshell_use_environ(self):\n for env in [None, {}]:\n with self.subTest(env=env):\n ", "meta": {"filepath": "tests/backends/base/test_client.py", "language": "python", "file_size": 1139, "cut_index": 518, "middle_length": 229}} +{"prefix": "els import (\n CircularA,\n CircularB,\n Object,\n ObjectReference,\n ObjectSelfReference,\n SchoolBus,\n SchoolClass,\n)\n\n\ndef get_connection_copy():\n # Get a copy of the default connection. (Can't use django.db.connection\n # because it'll modify the default connection itself.)\n test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])\n test_connection.settings_dict = copy.deepcopy(\n connections[DEFAULT_DB_ALIAS].settings_dict\n )\n return test_connection\n\n\nclass TestDb", "suffix": "_name\n test_connection.settings_dict[\"TEST\"] = {\"NAME\": None}\n signature = BaseDatabaseCreation(test_connection).test_db_signature()\n self.assertEqual(signature[3], TEST_DATABASE_PREFIX + prod_name)\n\n def test_custom_test_name(self)", "middle": "SignatureTests(SimpleTestCase):\n def test_default_name(self):\n # A test db name isn't set.\n prod_name = \"hodor\"\n test_connection = get_connection_copy()\n test_connection.settings_dict[\"NAME\"] = prod", "meta": {"filepath": "tests/backends/base/test_creation.py", "language": "python", "file_size": 15378, "cut_index": 921, "middle_length": 229}} +{"prefix": "db import connection\nfrom django.db.backends.base.introspection import BaseDatabaseIntrospection\nfrom django.test import SimpleTestCase\n\n\nclass SimpleDatabaseIntrospectionTests(SimpleTestCase):\n may_require_msg = (\n \"subclasses of BaseDatabaseIntrospection may require a %s() method\"\n )\n\n def setUp(self):\n self.introspection = BaseDatabaseIntrospection(connection=connection)\n\n def test_get_table_list(self):\n msg = self.may_require_msg % \"get_table_list\"\n with self.asse", "suffix": "Message(NotImplementedError, msg):\n self.introspection.get_table_description(None, None)\n\n def test_get_sequences(self):\n msg = self.may_require_msg % \"get_sequences\"\n with self.assertRaisesMessage(NotImplementedError, msg):\n ", "middle": "rtRaisesMessage(NotImplementedError, msg):\n self.introspection.get_table_list(None)\n\n def test_get_table_description(self):\n msg = self.may_require_msg % \"get_table_description\"\n with self.assertRaises", "meta": {"filepath": "tests/backends/base/test_introspection.py", "language": "python", "file_size": 1489, "cut_index": 524, "middle_length": 229}} +{"prefix": "skipIfDBFeature,\n skipUnlessDBFeature,\n)\nfrom django.utils import timezone\n\nfrom ..models import Author, Book, Person\n\n\nclass SimpleDatabaseOperationTests(SimpleTestCase):\n may_require_msg = \"subclasses of BaseDatabaseOperations may require a %s() method\"\n\n def setUp(self):\n self.ops = BaseDatabaseOperations(connection=connection)\n\n def test_deferrable_sql(self):\n self.assertEqual(self.ops.deferrable_sql(), \"\")\n\n def test_end_transaction_rollback(self):\n self.assertEqual(", "suffix": "self.ops.no_limit_value()\n\n def test_quote_name(self):\n with self.assertRaisesMessage(\n NotImplementedError, self.may_require_msg % \"quote_name\"\n ):\n self.ops.quote_name(\"a\")\n\n def test_regex_lookup(self):\n ", "middle": "self.ops.end_transaction_sql(success=False), \"ROLLBACK;\")\n\n def test_no_limit_value(self):\n with self.assertRaisesMessage(\n NotImplementedError, self.may_require_msg % \"no_limit_value\"\n ):\n ", "meta": {"filepath": "tests/backends/base/test_operations.py", "language": "python", "file_size": 10796, "cut_index": 921, "middle_length": 229}} +{"prefix": "go.db import DEFAULT_DB_ALIAS, NotSupportedError, connection, connections\nfrom django.test import SimpleTestCase\n\n\n@unittest.skipUnless(connection.vendor == \"sqlite\", \"SQLite tests\")\nclass TestDbSignatureTests(SimpleTestCase):\n def test_custom_test_name(self):\n test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])\n test_connection.settings_dict = copy.deepcopy(\n connections[DEFAULT_DB_ALIAS].settings_dict\n )\n test_connection.settings_dict[\"NAME\"] = None\n ", "suffix": "test_get_test_db_clone_settings_name(self):\n test_connection = copy.copy(connections[DEFAULT_DB_ALIAS])\n test_connection.settings_dict = copy.deepcopy(\n connections[DEFAULT_DB_ALIAS].settings_dict,\n )\n tests = [\n ", "middle": " test_connection.settings_dict[\"TEST\"][\"NAME\"] = \"custom.sqlite.db\"\n signature = test_connection.creation_class(test_connection).test_db_signature()\n self.assertEqual(signature, (None, \"custom.sqlite.db\"))\n\n def ", "meta": {"filepath": "tests/backends/sqlite/test_creation.py", "language": "python", "file_size": 4515, "cut_index": 614, "middle_length": 229}} +{"prefix": "3\nfrom unittest import mock, skipUnless\n\nfrom django.db import OperationalError, connection\nfrom django.test import TestCase\n\n\n@skipUnless(connection.vendor == \"sqlite\", \"SQLite tests.\")\nclass FeaturesTests(TestCase):\n def test_supports_json_field_operational_error(self):\n if hasattr(connection.features, \"supports_json_field\"):\n del connection.features.supports_json_field\n msg = \"unable to open database file\"\n with mock.patch.object(\n connection,\n \"cu", "suffix": "riable_limit(self):\n limit_name = sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER\n current_limit = connection.features.max_query_params\n new_limit = min(42, current_limit)\n try:\n connection.connection.setlimit(limit_name, new_li", "middle": "rsor\",\n side_effect=OperationalError(msg),\n ):\n with self.assertRaisesMessage(OperationalError, msg):\n connection.features.supports_json_field\n\n def test_max_query_params_respects_va", "meta": {"filepath": "tests/backends/sqlite/test_features.py", "language": "python", "file_size": 1689, "cut_index": 537, "middle_length": 229}} +{"prefix": "ort TestCase\n\nfrom .models import Comment, Tenant, User\n\n\nclass CompositePKOrderByTests(TestCase):\n maxDiff = None\n\n @classmethod\n def setUpTestData(cls):\n cls.tenant_1 = Tenant.objects.create()\n cls.tenant_2 = Tenant.objects.create()\n cls.tenant_3 = Tenant.objects.create()\n cls.user_1 = User.objects.create(\n tenant=cls.tenant_1,\n id=1,\n email=\"user0001@example.com\",\n )\n cls.user_2 = User.objects.create(\n tenant=c", "suffix": " cls.comment_1 = Comment.objects.create(id=1, user=cls.user_1)\n cls.comment_2 = Comment.objects.create(id=2, user=cls.user_1)\n cls.comment_3 = Comment.objects.create(id=3, user=cls.user_2)\n cls.comment_4 = Comment.objects.create(", "middle": "ls.tenant_1,\n id=2,\n email=\"user0002@example.com\",\n )\n cls.user_3 = User.objects.create(\n tenant=cls.tenant_2,\n id=3,\n email=\"user0003@example.com\",\n )\n ", "meta": {"filepath": "tests/composite_pk/test_order_by.py", "language": "python", "file_size": 2372, "cut_index": 563, "middle_length": 229}} +{"prefix": "\n\nfrom django.test import SimpleTestCase\nfrom django.utils import regex_helper\n\n\nclass NormalizeTests(unittest.TestCase):\n def test_empty(self):\n pattern = r\"\"\n expected = [(\"\", [])]\n result = regex_helper.normalize(pattern)\n self.assertEqual(result, expected)\n\n def test_escape(self):\n pattern = r\"\\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)\\[\"\n expected = [(\"\\\\^$.|?*+()[\", [])]\n result = regex_helper.normalize(pattern)\n self.assertEqual(result, expected)\n\n def test_", "suffix": "ing(self):\n pattern = r\"(?:non-capturing)\"\n expected = [(\"non-capturing\", [])]\n result = regex_helper.normalize(pattern)\n self.assertEqual(result, expected)\n\n def test_group_named(self):\n pattern = r\"(?P\")\n self.assertEqual(repr(self.node2), \"\")\n\n def test_hash(self):\n node3 = Node(self.node1_children, negated=True)\n node4 = Node(self.node1_children, connector=\"OTHER\")\n node5 = Node(self.node1_children)\n node6 = Node([[\"a\", 1], [\"b", "meta": {"filepath": "tests/utils_tests/test_tree.py", "language": "python", "file_size": 4828, "cut_index": 614, "middle_length": 229}} +{"prefix": "o.db.backends.utils import truncate_name\nfrom django.test import TestCase\n\nfrom .models.article import Article, Site\nfrom .models.publication import Publication\n\n\nclass Advertisement(models.Model):\n customer = models.CharField(max_length=100)\n publications = models.ManyToManyField(\"model_package.Publication\", blank=True)\n\n\nclass ModelPackageTests(TestCase):\n def test_m2m_tables_in_subpackage_models(self):\n \"\"\"\n Regression for #12168: models split into subpackages still get M2M\n ", "suffix": " a.sites.add(site)\n\n a = Article.objects.get(id=a.pk)\n self.assertEqual(a.id, a.pk)\n self.assertEqual(a.sites.count(), 1)\n\n def test_models_in_the_test_package(self):\n \"\"\"\n Regression for #12245 - Models can exist i", "middle": " tables.\n \"\"\"\n p = Publication.objects.create(title=\"FooBar\")\n\n site = Site.objects.create(name=\"example.com\")\n\n a = Article.objects.create(headline=\"a foo headline\")\n a.publications.add(p)\n ", "meta": {"filepath": "tests/model_package/tests.py", "language": "python", "file_size": 2624, "cut_index": 563, "middle_length": 229}} +{"prefix": "sponse\nfrom django.middleware.csrf import (\n CSRF_TOKEN_LENGTH,\n CsrfViewMiddleware,\n _unmask_cipher_token,\n get_token,\n)\nfrom django.template import TemplateDoesNotExist, TemplateSyntaxError\nfrom django.template.backends.dummy import TemplateStrings\nfrom django.test import SimpleTestCase\n\n\nclass TemplateStringsTests(SimpleTestCase):\n engine_class = TemplateStrings\n backend_name = \"dummy\"\n options = {}\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n param", "suffix": " template = self.engine.from_string(\"Hello!\\n\")\n content = template.render()\n self.assertEqual(content, \"Hello!\\n\")\n\n def test_get_template(self):\n template = self.engine.get_template(\"template_backends/hello.html\")\n content", "middle": "s = {\n \"DIRS\": [],\n \"APP_DIRS\": True,\n \"NAME\": cls.backend_name,\n \"OPTIONS\": cls.options,\n }\n cls.engine = cls.engine_class(params)\n\n def test_from_string(self):\n ", "meta": {"filepath": "tests/template_backends/test_dummy.py", "language": "python", "file_size": 4088, "cut_index": 614, "middle_length": 229}} +{"prefix": "om .test_dummy import TemplateStringsTests\n\ntry:\n import jinja2\nexcept ImportError:\n jinja2 = None\n Jinja2 = None\nelse:\n from django.template.backends.jinja2 import Jinja2\n\n\n@skipIf(jinja2 is None, \"this test requires jinja2\")\nclass Jinja2Tests(TemplateStringsTests):\n engine_class = Jinja2\n backend_name = \"jinja2\"\n options = {\n \"keep_trailing_newline\": True,\n \"context_processors\": [\n \"django.template.context_processors.static\",\n ],\n }\n\n def test_ori", "suffix": "s/hello.html\")\n\n def test_origin_from_string(self):\n template = self.engine.from_string(\"Hello!\\n\")\n self.assertEqual(template.origin.name, \"