problem_id
stringlengths
18
22
source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
13
58
prompt
stringlengths
1.1k
10.2k
golden_diff
stringlengths
151
4.94k
verification_info
stringlengths
582
21k
num_tokens
int64
271
2.05k
num_tokens_diff
int64
47
1.02k
gh_patches_debug_3181
rasdani/github-patches
git_diff
translate__pootle-6456
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Terminology is not updated when term units are updated the terminology stemmer listens to `submission.post_save` - but submissions are always `bulk_created` so it doesn't seem to get triggered --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pootle/apps/pootle_terminology/receivers.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 # 3 # Copyright (C) Pootle contributors. 4 # 5 # This file is a part of the Pootle project. It is distributed under the GPL3 6 # or later license. See the LICENSE file for a copy of the license and the 7 # AUTHORS file for copyright and authorship information. 8 9 from django.db.models.signals import post_save 10 from django.dispatch import receiver 11 12 from pootle.core.delegate import terminology 13 from pootle_statistics.models import Submission, SubmissionFields 14 from pootle_store.constants import TRANSLATED 15 from pootle_store.models import Unit 16 17 18 @receiver(post_save, sender=Unit) 19 def handle_unit_save(**kwargs): 20 unit = kwargs["instance"] 21 if not kwargs.get("created"): 22 return 23 if unit.state != TRANSLATED: 24 return 25 is_terminology = ( 26 unit.store.name.startswith("pootle-terminology") 27 or (unit.store.translation_project.project.code 28 == "terminology")) 29 if not is_terminology: 30 return 31 terminology.get(Unit)(unit).stem() 32 33 34 @receiver(post_save, sender=Submission) 35 def handle_submission_save(**kwargs): 36 sub = kwargs["instance"] 37 if sub.type != SubmissionFields.TARGET: 38 return 39 unit = sub.unit 40 if unit.state != TRANSLATED: 41 return 42 is_terminology = ( 43 unit.store.name.startswith("pootle-terminology") 44 or (unit.store.translation_project.project.code 45 == "terminology")) 46 if not is_terminology: 47 return 48 terminology.get(Unit)(unit).stem() 49 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pootle/apps/pootle_terminology/receivers.py b/pootle/apps/pootle_terminology/receivers.py --- a/pootle/apps/pootle_terminology/receivers.py +++ b/pootle/apps/pootle_terminology/receivers.py @@ -34,7 +34,7 @@ @receiver(post_save, sender=Submission) def handle_submission_save(**kwargs): sub = kwargs["instance"] - if sub.type != SubmissionFields.TARGET: + if sub.field != SubmissionFields.TARGET: return unit = sub.unit if unit.state != TRANSLATED:
{"golden_diff": "diff --git a/pootle/apps/pootle_terminology/receivers.py b/pootle/apps/pootle_terminology/receivers.py\n--- a/pootle/apps/pootle_terminology/receivers.py\n+++ b/pootle/apps/pootle_terminology/receivers.py\n@@ -34,7 +34,7 @@\n @receiver(post_save, sender=Submission)\n def handle_submission_save(**kwargs):\n sub = kwargs[\"instance\"]\n- if sub.type != SubmissionFields.TARGET:\n+ if sub.field != SubmissionFields.TARGET:\n return\n unit = sub.unit\n if unit.state != TRANSLATED:\n", "issue": "Terminology is not updated when term units are updated\nthe terminology stemmer listens to `submission.post_save` - but submissions are always `bulk_created` so it doesn't seem to get triggered\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom pootle.core.delegate import terminology\nfrom pootle_statistics.models import Submission, SubmissionFields\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Unit\n\n\n@receiver(post_save, sender=Unit)\ndef handle_unit_save(**kwargs):\n unit = kwargs[\"instance\"]\n if not kwargs.get(\"created\"):\n return\n if unit.state != TRANSLATED:\n return\n is_terminology = (\n unit.store.name.startswith(\"pootle-terminology\")\n or (unit.store.translation_project.project.code\n == \"terminology\"))\n if not is_terminology:\n return\n terminology.get(Unit)(unit).stem()\n\n\n@receiver(post_save, sender=Submission)\ndef handle_submission_save(**kwargs):\n sub = kwargs[\"instance\"]\n if sub.type != SubmissionFields.TARGET:\n return\n unit = sub.unit\n if unit.state != TRANSLATED:\n return\n is_terminology = (\n unit.store.name.startswith(\"pootle-terminology\")\n or (unit.store.translation_project.project.code\n == \"terminology\"))\n if not is_terminology:\n return\n terminology.get(Unit)(unit).stem()\n", "path": "pootle/apps/pootle_terminology/receivers.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom pootle.core.delegate import terminology\nfrom pootle_statistics.models import Submission, SubmissionFields\nfrom pootle_store.constants import TRANSLATED\nfrom pootle_store.models import Unit\n\n\n@receiver(post_save, sender=Unit)\ndef handle_unit_save(**kwargs):\n unit = kwargs[\"instance\"]\n if not kwargs.get(\"created\"):\n return\n if unit.state != TRANSLATED:\n return\n is_terminology = (\n unit.store.name.startswith(\"pootle-terminology\")\n or (unit.store.translation_project.project.code\n == \"terminology\"))\n if not is_terminology:\n return\n terminology.get(Unit)(unit).stem()\n\n\n@receiver(post_save, sender=Submission)\ndef handle_submission_save(**kwargs):\n sub = kwargs[\"instance\"]\n if sub.field != SubmissionFields.TARGET:\n return\n unit = sub.unit\n if unit.state != TRANSLATED:\n return\n is_terminology = (\n unit.store.name.startswith(\"pootle-terminology\")\n or (unit.store.translation_project.project.code\n == \"terminology\"))\n if not is_terminology:\n return\n terminology.get(Unit)(unit).stem()\n", "path": "pootle/apps/pootle_terminology/receivers.py"}]}
741
143
gh_patches_debug_9819
rasdani/github-patches
git_diff
opensearch-project__opensearch-build-1520
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [Bug]: Maven sign and upload should be done inside a docker container ### Describe the bug We should be using a docker container to run jenkinsjob. https://github.com/opensearch-project/opensearch-infra/blob/main/jenkins/jobs/OpenSearch_CI/release_ci/opensearch_maven_release/Jenkinsfile#L3-L5 Also, should this file be a part of `opensearch-build`? ### To reproduce Docker container is not used - https://github.com/opensearch-project/opensearch-infra/blob/main/jenkins/jobs/OpenSearch_CI/release_ci/opensearch_maven_release/Jenkinsfile#L3-L5 ### Expected behavior _No response_ ### Screenshots If applicable, add screenshots to help explain your problem. ### Host / Environment _No response_ ### Additional context _No response_ ### Relevant log output _No response_ --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/run_sign.py` Content: ``` 1 #!/usr/bin/env python 2 3 # SPDX-License-Identifier: Apache-2.0 4 # 5 # The OpenSearch Contributors require contributions made to 6 # this file be licensed under the Apache-2.0 license or a 7 # compatible open source license. 8 9 import argparse 10 import logging 11 import sys 12 from pathlib import Path 13 14 from sign_workflow.sign_artifacts import SignArtifacts 15 from sign_workflow.signer import Signer 16 from system import console 17 18 ACCEPTED_SIGNATURE_FILE_TYPES = [".sig"] 19 20 21 def main(): 22 parser = argparse.ArgumentParser(description="Sign artifacts") 23 parser.add_argument("target", type=Path, help="Path to local manifest file or artifact directory.") 24 parser.add_argument("--component", nargs="?", help="Component name") 25 parser.add_argument("--type", nargs="?", help="Artifact type") 26 parser.add_argument("--sigtype", choices=ACCEPTED_SIGNATURE_FILE_TYPES, help="Type of Signature file", default=".asc") 27 parser.add_argument( 28 "-v", 29 "--verbose", 30 help="Show more verbose output.", 31 action="store_const", 32 default=logging.INFO, 33 const=logging.DEBUG, 34 dest="logging_level", 35 ) 36 args = parser.parse_args() 37 38 console.configure(level=args.logging_level) 39 40 sign = SignArtifacts.from_path(path=args.target, 41 component=args.component, 42 artifact_type=args.type, 43 signature_type=args.sigtype, 44 signer=Signer()) 45 46 sign.sign() 47 48 49 if __name__ == "__main__": 50 sys.exit(main()) 51 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/run_sign.py b/src/run_sign.py --- a/src/run_sign.py +++ b/src/run_sign.py @@ -24,6 +24,7 @@ parser.add_argument("--component", nargs="?", help="Component name") parser.add_argument("--type", nargs="?", help="Artifact type") parser.add_argument("--sigtype", choices=ACCEPTED_SIGNATURE_FILE_TYPES, help="Type of Signature file", default=".asc") + parser.add_argument("--platform", nargs="?", help="The distribution platform", default="linux") parser.add_argument( "-v", "--verbose",
{"golden_diff": "diff --git a/src/run_sign.py b/src/run_sign.py\n--- a/src/run_sign.py\n+++ b/src/run_sign.py\n@@ -24,6 +24,7 @@\n parser.add_argument(\"--component\", nargs=\"?\", help=\"Component name\")\n parser.add_argument(\"--type\", nargs=\"?\", help=\"Artifact type\")\n parser.add_argument(\"--sigtype\", choices=ACCEPTED_SIGNATURE_FILE_TYPES, help=\"Type of Signature file\", default=\".asc\")\n+ parser.add_argument(\"--platform\", nargs=\"?\", help=\"The distribution platform\", default=\"linux\")\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n", "issue": "[Bug]: Maven sign and upload should be done inside a docker container\n### Describe the bug\n\nWe should be using a docker container to run jenkinsjob. \r\n\r\nhttps://github.com/opensearch-project/opensearch-infra/blob/main/jenkins/jobs/OpenSearch_CI/release_ci/opensearch_maven_release/Jenkinsfile#L3-L5\r\n\r\nAlso, should this file be a part of `opensearch-build`?\n\n### To reproduce\n\nDocker container is not used - \r\n\r\nhttps://github.com/opensearch-project/opensearch-infra/blob/main/jenkins/jobs/OpenSearch_CI/release_ci/opensearch_maven_release/Jenkinsfile#L3-L5\n\n### Expected behavior\n\n_No response_\n\n### Screenshots\n\nIf applicable, add screenshots to help explain your problem.\n\n### Host / Environment\n\n_No response_\n\n### Additional context\n\n_No response_\n\n### Relevant log output\n\n_No response_\n", "before_files": [{"content": "#!/usr/bin/env python\n\n# SPDX-License-Identifier: Apache-2.0\n#\n# The OpenSearch Contributors require contributions made to\n# this file be licensed under the Apache-2.0 license or a\n# compatible open source license.\n\nimport argparse\nimport logging\nimport sys\nfrom pathlib import Path\n\nfrom sign_workflow.sign_artifacts import SignArtifacts\nfrom sign_workflow.signer import Signer\nfrom system import console\n\nACCEPTED_SIGNATURE_FILE_TYPES = [\".sig\"]\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Sign artifacts\")\n parser.add_argument(\"target\", type=Path, help=\"Path to local manifest file or artifact directory.\")\n parser.add_argument(\"--component\", nargs=\"?\", help=\"Component name\")\n parser.add_argument(\"--type\", nargs=\"?\", help=\"Artifact type\")\n parser.add_argument(\"--sigtype\", choices=ACCEPTED_SIGNATURE_FILE_TYPES, help=\"Type of Signature file\", default=\".asc\")\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"Show more verbose output.\",\n action=\"store_const\",\n default=logging.INFO,\n const=logging.DEBUG,\n dest=\"logging_level\",\n )\n args = parser.parse_args()\n\n console.configure(level=args.logging_level)\n\n sign = SignArtifacts.from_path(path=args.target,\n component=args.component,\n artifact_type=args.type,\n signature_type=args.sigtype,\n signer=Signer())\n\n sign.sign()\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n", "path": "src/run_sign.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\n# SPDX-License-Identifier: Apache-2.0\n#\n# The OpenSearch Contributors require contributions made to\n# this file be licensed under the Apache-2.0 license or a\n# compatible open source license.\n\nimport argparse\nimport logging\nimport sys\nfrom pathlib import Path\n\nfrom sign_workflow.sign_artifacts import SignArtifacts\nfrom sign_workflow.signer import Signer\nfrom system import console\n\nACCEPTED_SIGNATURE_FILE_TYPES = [\".sig\"]\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Sign artifacts\")\n parser.add_argument(\"target\", type=Path, help=\"Path to local manifest file or artifact directory.\")\n parser.add_argument(\"--component\", nargs=\"?\", help=\"Component name\")\n parser.add_argument(\"--type\", nargs=\"?\", help=\"Artifact type\")\n parser.add_argument(\"--sigtype\", choices=ACCEPTED_SIGNATURE_FILE_TYPES, help=\"Type of Signature file\", default=\".asc\")\n parser.add_argument(\"--platform\", nargs=\"?\", help=\"The distribution platform\", default=\"linux\")\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"Show more verbose output.\",\n action=\"store_const\",\n default=logging.INFO,\n const=logging.DEBUG,\n dest=\"logging_level\",\n )\n args = parser.parse_args()\n\n console.configure(level=args.logging_level)\n\n sign = SignArtifacts.from_path(path=args.target,\n component=args.component,\n artifact_type=args.type,\n signature_type=args.sigtype,\n signer=Signer())\n\n sign.sign()\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n", "path": "src/run_sign.py"}]}
852
131
gh_patches_debug_67079
rasdani/github-patches
git_diff
vyperlang__vyper-3936
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `vyper-serve` is still lingering in `setup.py` ### Version Information * vyper Version (output of `vyper --version`): doesn't matter * OS: doesn't matter * Python Version (output of `python --version`): doesn't matter ### What's your issue about? You removed `vyper-serve` with this commit: https://github.com/vyperlang/vyper/commit/98f502baea6385fe25dbf94a70fb4eddc9f02f56, but you forgot to remove `vyper-serve` from `setup.py`: ```python entry_points={ "console_scripts": [ "vyper=vyper.cli.vyper_compile:_parse_cli_args", "vyper-serve=vyper.cli.vyper_serve:_parse_cli_args", "fang=vyper.cli.vyper_ir:_parse_cli_args", "vyper-json=vyper.cli.vyper_json:_parse_cli_args", ] }, ``` ### How can it be fixed? Remove `vyper-serve` line. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 3 import os 4 import re 5 import subprocess 6 7 from setuptools import setup 8 9 extras_require = { 10 "test": [ 11 "pytest>=8.0,<9.0", 12 "pytest-cov>=4.1,<5.0", 13 "pytest-instafail>=0.4,<1.0", 14 "pytest-xdist>=3.0,<3.4", 15 "pytest-split>=0.7.0,<1.0", 16 "eth-tester[py-evm]>=0.10.0b4,<0.11", 17 "eth_abi>=4.0.0,<5.0.0", 18 "py-evm>=0.10.0b4,<0.11", 19 "web3==6.0.0", 20 "lark==1.1.9", 21 "hypothesis[lark]>=6.0,<7.0", 22 "eth-stdlib==0.2.7", 23 "setuptools", 24 "hexbytes>=1.2", 25 ], 26 "lint": [ 27 "black==23.12.0", 28 "flake8==6.1.0", 29 "flake8-bugbear==23.12.2", 30 "flake8-use-fstring==1.4", 31 "isort==5.13.2", 32 "mypy==1.5", 33 ], 34 "dev": ["ipython", "pre-commit", "pyinstaller", "twine"], 35 } 36 37 extras_require["dev"] = extras_require["dev"] + extras_require["test"] + extras_require["lint"] 38 39 with open("README.md", "r") as f: 40 long_description = f.read() 41 42 43 # strip local version 44 def _local_version(version): 45 return "" 46 47 48 def _global_version(version): 49 from setuptools_scm.version import guess_next_dev_version 50 51 # strip `.devN` suffix since it is not semver compatible 52 # minor regex hack to avoid messing too much with setuptools-scm internals 53 version_str = guess_next_dev_version(version) 54 return re.sub(r"\.dev\d+", "", version_str) 55 56 57 hash_file_rel_path = os.path.join("vyper", "vyper_git_commithash.txt") 58 hashfile = os.path.relpath(hash_file_rel_path) 59 60 # there is no way in setuptools-scm to get metadata besides the package 61 # version into version.py. (and we need that version to be PEP440 compliant 62 # in order to get it into pypi). so, add the commit hash to the package 63 # separately, in order so that we can add it to `vyper --version`. 64 try: 65 commithash = subprocess.check_output("git rev-parse --short HEAD".split()) 66 commithash_str = commithash.decode("utf-8").strip() 67 with open(hashfile, "w") as fh: 68 fh.write(commithash_str) 69 except subprocess.CalledProcessError: 70 pass 71 72 73 setup( 74 name="vyper", 75 use_scm_version={ 76 "local_scheme": _local_version, 77 "version_scheme": _global_version, 78 "write_to": "vyper/version.py", 79 }, 80 description="Vyper: the Pythonic Programming Language for the EVM", 81 long_description=long_description, 82 long_description_content_type="text/markdown", 83 author="Vyper Team", 84 author_email="", 85 url="https://github.com/vyperlang/vyper", 86 license="Apache License 2.0", 87 keywords="ethereum evm smart contract language", 88 include_package_data=True, 89 packages=["vyper"], 90 python_requires=">=3.10,<4", 91 py_modules=["vyper"], 92 install_requires=[ 93 "cbor2>=5.4.6,<6", 94 "asttokens>=2.0.5,<3", 95 "pycryptodome>=3.5.1,<4", 96 "packaging>=23.1,<24", 97 "importlib-metadata", 98 "wheel", 99 ], 100 setup_requires=["pytest-runner", "setuptools_scm>=7.1.0,<8.0.0"], 101 tests_require=extras_require["test"], 102 extras_require=extras_require, 103 entry_points={ 104 "console_scripts": [ 105 "vyper=vyper.cli.vyper_compile:_parse_cli_args", 106 "vyper-serve=vyper.cli.vyper_serve:_parse_cli_args", 107 "fang=vyper.cli.vyper_ir:_parse_cli_args", 108 "vyper-json=vyper.cli.vyper_json:_parse_cli_args", 109 ] 110 }, 111 classifiers=[ 112 "Intended Audience :: Developers", 113 "License :: OSI Approved :: Apache Software License", 114 "Programming Language :: Python :: 3.10", 115 "Programming Language :: Python :: 3.11", 116 "Programming Language :: Python :: 3.12", 117 ], 118 package_data={"vyper.ast": ["grammar.lark"]}, 119 data_files=[("", [hash_file_rel_path])], 120 ) 121 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -103,7 +103,6 @@ entry_points={ "console_scripts": [ "vyper=vyper.cli.vyper_compile:_parse_cli_args", - "vyper-serve=vyper.cli.vyper_serve:_parse_cli_args", "fang=vyper.cli.vyper_ir:_parse_cli_args", "vyper-json=vyper.cli.vyper_json:_parse_cli_args", ]
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -103,7 +103,6 @@\n entry_points={\n \"console_scripts\": [\n \"vyper=vyper.cli.vyper_compile:_parse_cli_args\",\n- \"vyper-serve=vyper.cli.vyper_serve:_parse_cli_args\",\n \"fang=vyper.cli.vyper_ir:_parse_cli_args\",\n \"vyper-json=vyper.cli.vyper_json:_parse_cli_args\",\n ]\n", "issue": "`vyper-serve` is still lingering in `setup.py`\n### Version Information\r\n\r\n* vyper Version (output of `vyper --version`): doesn't matter\r\n* OS: doesn't matter\r\n* Python Version (output of `python --version`): doesn't matter\r\n\r\n### What's your issue about?\r\n\r\nYou removed `vyper-serve` with this commit: https://github.com/vyperlang/vyper/commit/98f502baea6385fe25dbf94a70fb4eddc9f02f56, but you forgot to remove `vyper-serve` from `setup.py`:\r\n\r\n```python\r\nentry_points={\r\n \"console_scripts\": [\r\n \"vyper=vyper.cli.vyper_compile:_parse_cli_args\",\r\n \"vyper-serve=vyper.cli.vyper_serve:_parse_cli_args\",\r\n \"fang=vyper.cli.vyper_ir:_parse_cli_args\",\r\n \"vyper-json=vyper.cli.vyper_json:_parse_cli_args\",\r\n ]\r\n },\r\n```\r\n\r\n### How can it be fixed?\r\n\r\nRemove `vyper-serve` line.\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport subprocess\n\nfrom setuptools import setup\n\nextras_require = {\n \"test\": [\n \"pytest>=8.0,<9.0\",\n \"pytest-cov>=4.1,<5.0\",\n \"pytest-instafail>=0.4,<1.0\",\n \"pytest-xdist>=3.0,<3.4\",\n \"pytest-split>=0.7.0,<1.0\",\n \"eth-tester[py-evm]>=0.10.0b4,<0.11\",\n \"eth_abi>=4.0.0,<5.0.0\",\n \"py-evm>=0.10.0b4,<0.11\",\n \"web3==6.0.0\",\n \"lark==1.1.9\",\n \"hypothesis[lark]>=6.0,<7.0\",\n \"eth-stdlib==0.2.7\",\n \"setuptools\",\n \"hexbytes>=1.2\",\n ],\n \"lint\": [\n \"black==23.12.0\",\n \"flake8==6.1.0\",\n \"flake8-bugbear==23.12.2\",\n \"flake8-use-fstring==1.4\",\n \"isort==5.13.2\",\n \"mypy==1.5\",\n ],\n \"dev\": [\"ipython\", \"pre-commit\", \"pyinstaller\", \"twine\"],\n}\n\nextras_require[\"dev\"] = extras_require[\"dev\"] + extras_require[\"test\"] + extras_require[\"lint\"]\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\n\n# strip local version\ndef _local_version(version):\n return \"\"\n\n\ndef _global_version(version):\n from setuptools_scm.version import guess_next_dev_version\n\n # strip `.devN` suffix since it is not semver compatible\n # minor regex hack to avoid messing too much with setuptools-scm internals\n version_str = guess_next_dev_version(version)\n return re.sub(r\"\\.dev\\d+\", \"\", version_str)\n\n\nhash_file_rel_path = os.path.join(\"vyper\", \"vyper_git_commithash.txt\")\nhashfile = os.path.relpath(hash_file_rel_path)\n\n# there is no way in setuptools-scm to get metadata besides the package\n# version into version.py. (and we need that version to be PEP440 compliant\n# in order to get it into pypi). so, add the commit hash to the package\n# separately, in order so that we can add it to `vyper --version`.\ntry:\n commithash = subprocess.check_output(\"git rev-parse --short HEAD\".split())\n commithash_str = commithash.decode(\"utf-8\").strip()\n with open(hashfile, \"w\") as fh:\n fh.write(commithash_str)\nexcept subprocess.CalledProcessError:\n pass\n\n\nsetup(\n name=\"vyper\",\n use_scm_version={\n \"local_scheme\": _local_version,\n \"version_scheme\": _global_version,\n \"write_to\": \"vyper/version.py\",\n },\n description=\"Vyper: the Pythonic Programming Language for the EVM\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Vyper Team\",\n author_email=\"\",\n url=\"https://github.com/vyperlang/vyper\",\n license=\"Apache License 2.0\",\n keywords=\"ethereum evm smart contract language\",\n include_package_data=True,\n packages=[\"vyper\"],\n python_requires=\">=3.10,<4\",\n py_modules=[\"vyper\"],\n install_requires=[\n \"cbor2>=5.4.6,<6\",\n \"asttokens>=2.0.5,<3\",\n \"pycryptodome>=3.5.1,<4\",\n \"packaging>=23.1,<24\",\n \"importlib-metadata\",\n \"wheel\",\n ],\n setup_requires=[\"pytest-runner\", \"setuptools_scm>=7.1.0,<8.0.0\"],\n tests_require=extras_require[\"test\"],\n extras_require=extras_require,\n entry_points={\n \"console_scripts\": [\n \"vyper=vyper.cli.vyper_compile:_parse_cli_args\",\n \"vyper-serve=vyper.cli.vyper_serve:_parse_cli_args\",\n \"fang=vyper.cli.vyper_ir:_parse_cli_args\",\n \"vyper-json=vyper.cli.vyper_json:_parse_cli_args\",\n ]\n },\n classifiers=[\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Programming Language :: Python :: 3.12\",\n ],\n package_data={\"vyper.ast\": [\"grammar.lark\"]},\n data_files=[(\"\", [hash_file_rel_path])],\n)\n", "path": "setup.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport subprocess\n\nfrom setuptools import setup\n\nextras_require = {\n \"test\": [\n \"pytest>=8.0,<9.0\",\n \"pytest-cov>=4.1,<5.0\",\n \"pytest-instafail>=0.4,<1.0\",\n \"pytest-xdist>=3.0,<3.4\",\n \"pytest-split>=0.7.0,<1.0\",\n \"eth-tester[py-evm]>=0.10.0b4,<0.11\",\n \"eth_abi>=4.0.0,<5.0.0\",\n \"py-evm>=0.10.0b4,<0.11\",\n \"web3==6.0.0\",\n \"lark==1.1.9\",\n \"hypothesis[lark]>=6.0,<7.0\",\n \"eth-stdlib==0.2.7\",\n \"setuptools\",\n \"hexbytes>=1.2\",\n ],\n \"lint\": [\n \"black==23.12.0\",\n \"flake8==6.1.0\",\n \"flake8-bugbear==23.12.2\",\n \"flake8-use-fstring==1.4\",\n \"isort==5.13.2\",\n \"mypy==1.5\",\n ],\n \"dev\": [\"ipython\", \"pre-commit\", \"pyinstaller\", \"twine\"],\n}\n\nextras_require[\"dev\"] = extras_require[\"dev\"] + extras_require[\"test\"] + extras_require[\"lint\"]\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\n\n# strip local version\ndef _local_version(version):\n return \"\"\n\n\ndef _global_version(version):\n from setuptools_scm.version import guess_next_dev_version\n\n # strip `.devN` suffix since it is not semver compatible\n # minor regex hack to avoid messing too much with setuptools-scm internals\n version_str = guess_next_dev_version(version)\n return re.sub(r\"\\.dev\\d+\", \"\", version_str)\n\n\nhash_file_rel_path = os.path.join(\"vyper\", \"vyper_git_commithash.txt\")\nhashfile = os.path.relpath(hash_file_rel_path)\n\n# there is no way in setuptools-scm to get metadata besides the package\n# version into version.py. (and we need that version to be PEP440 compliant\n# in order to get it into pypi). so, add the commit hash to the package\n# separately, in order so that we can add it to `vyper --version`.\ntry:\n commithash = subprocess.check_output(\"git rev-parse --short HEAD\".split())\n commithash_str = commithash.decode(\"utf-8\").strip()\n with open(hashfile, \"w\") as fh:\n fh.write(commithash_str)\nexcept subprocess.CalledProcessError:\n pass\n\n\nsetup(\n name=\"vyper\",\n use_scm_version={\n \"local_scheme\": _local_version,\n \"version_scheme\": _global_version,\n \"write_to\": \"vyper/version.py\",\n },\n description=\"Vyper: the Pythonic Programming Language for the EVM\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Vyper Team\",\n author_email=\"\",\n url=\"https://github.com/vyperlang/vyper\",\n license=\"Apache License 2.0\",\n keywords=\"ethereum evm smart contract language\",\n include_package_data=True,\n packages=[\"vyper\"],\n python_requires=\">=3.10,<4\",\n py_modules=[\"vyper\"],\n install_requires=[\n \"cbor2>=5.4.6,<6\",\n \"asttokens>=2.0.5,<3\",\n \"pycryptodome>=3.5.1,<4\",\n \"packaging>=23.1,<24\",\n \"importlib-metadata\",\n \"wheel\",\n ],\n setup_requires=[\"pytest-runner\", \"setuptools_scm>=7.1.0,<8.0.0\"],\n tests_require=extras_require[\"test\"],\n extras_require=extras_require,\n entry_points={\n \"console_scripts\": [\n \"vyper=vyper.cli.vyper_compile:_parse_cli_args\",\n \"fang=vyper.cli.vyper_ir:_parse_cli_args\",\n \"vyper-json=vyper.cli.vyper_json:_parse_cli_args\",\n ]\n },\n classifiers=[\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Programming Language :: Python :: 3.12\",\n ],\n package_data={\"vyper.ast\": [\"grammar.lark\"]},\n data_files=[(\"\", [hash_file_rel_path])],\n)\n", "path": "setup.py"}]}
1,844
114
gh_patches_debug_7424
rasdani/github-patches
git_diff
facebookresearch__habitat-lab-132
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Recursive directory lookup can take long This [line](https://github.com/facebookresearch/habitat-api/blob/master/setup.py#L38) looks for requirements.txt under all directories, this can be especially costly if you have data directories. One way to get around this is to only look at specific set of directories and ignore data directories. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 #!/usr/bin/env python3 2 3 # Copyright (c) Facebook, Inc. and its affiliates. 4 # This source code is licensed under the MIT license found in the 5 # LICENSE file in the root directory of this source tree. 6 7 import glob 8 import os.path 9 import sys 10 11 import setuptools 12 from setuptools.command.develop import develop as DefaultDevelopCommand 13 from setuptools.command.install import install as DefaultInstallCommand 14 15 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "habitat")) 16 from version import VERSION # isort:skip noqa 17 18 19 with open("README.md", encoding="utf8") as f: 20 readme = f.read() 21 22 with open("LICENSE") as f: 23 license = f.read() 24 25 with open("requirements.txt") as f: 26 reqs = f.read() 27 28 DISTNAME = "habitat" 29 DESCRIPTION = "habitat: a suite for embodied agent tasks and benchmarks" 30 LONG_DESCRIPTION = readme 31 AUTHOR = "Facebook AI Research" 32 LICENSE = license 33 REQUIREMENTS = reqs.strip().split("\n") 34 BASELINE_PATH = ["habitat_baselines", "habitat_baselines.*"] 35 DEFAULT_EXCLUSION = ["test", "examples"] 36 FULL_REQUIREMENTS = set() 37 # collect requirements.txt file in all subdirectories 38 for file_name in glob.glob("**/requirements.txt", recursive=True): 39 with open(file_name) as f: 40 reqs = f.read() 41 FULL_REQUIREMENTS.update(reqs.strip().split("\n")) 42 43 44 class OptionedCommand: 45 r"""Generic Command class that takes extra user options and modifies 46 arguments in setuptools.setup() accordingly. 47 Though OptionedCommand inherits directly from object, it assumes 48 inheritance from DefaultDevelopCommand or DefaultInstallCommand, as it 49 overrides methods from those two classes. 50 """ 51 52 user_options = [("all", None, "include habitat_baselines in installation")] 53 54 def initialize_options(self): 55 super().initialize_options() 56 self.all = None 57 58 def run(self): 59 if not self.all: # install core only 60 DEFAULT_EXCLUSION.extend(BASELINE_PATH) 61 self.distribution.packages = setuptools.find_packages( 62 exclude=DEFAULT_EXCLUSION 63 ) 64 # self.distribution accesses arguments of setup() in main() 65 else: # install all except test and examples 66 self.distribution.install_requires = FULL_REQUIREMENTS 67 super().run() 68 69 70 class InstallCommand(OptionedCommand, DefaultInstallCommand): 71 user_options = ( 72 getattr(DefaultInstallCommand, "user_options", []) 73 + OptionedCommand.user_options 74 ) 75 76 77 class DevelopCommand(OptionedCommand, DefaultDevelopCommand): 78 user_options = ( 79 getattr(DefaultDevelopCommand, "user_options", []) 80 + OptionedCommand.user_options 81 ) 82 83 84 if __name__ == "__main__": 85 setuptools.setup( 86 name=DISTNAME, 87 install_requires=REQUIREMENTS, 88 packages=setuptools.find_packages(exclude=DEFAULT_EXCLUSION), 89 version=VERSION, 90 description=DESCRIPTION, 91 long_description=LONG_DESCRIPTION, 92 author=AUTHOR, 93 license=LICENSE, 94 setup_requires=["pytest-runner"], 95 tests_require=["pytest"], 96 include_package_data=True, 97 cmdclass={"install": InstallCommand, "develop": DevelopCommand}, 98 ) 99 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -35,7 +35,9 @@ DEFAULT_EXCLUSION = ["test", "examples"] FULL_REQUIREMENTS = set() # collect requirements.txt file in all subdirectories -for file_name in glob.glob("**/requirements.txt", recursive=True): +for file_name in ["requirements.txt"] + glob.glob( + "habitat_baselines/**/requirements.txt", recursive=True +): with open(file_name) as f: reqs = f.read() FULL_REQUIREMENTS.update(reqs.strip().split("\n"))
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -35,7 +35,9 @@\n DEFAULT_EXCLUSION = [\"test\", \"examples\"]\n FULL_REQUIREMENTS = set()\n # collect requirements.txt file in all subdirectories\n-for file_name in glob.glob(\"**/requirements.txt\", recursive=True):\n+for file_name in [\"requirements.txt\"] + glob.glob(\n+ \"habitat_baselines/**/requirements.txt\", recursive=True\n+):\n with open(file_name) as f:\n reqs = f.read()\n FULL_REQUIREMENTS.update(reqs.strip().split(\"\\n\"))\n", "issue": "Recursive directory lookup can take long\nThis [line](https://github.com/facebookresearch/habitat-api/blob/master/setup.py#L38) looks for requirements.txt under all directories, this can be especially costly if you have data directories. \r\n\r\nOne way to get around this is to only look at specific set of directories and ignore data directories.\n", "before_files": [{"content": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport glob\nimport os.path\nimport sys\n\nimport setuptools\nfrom setuptools.command.develop import develop as DefaultDevelopCommand\nfrom setuptools.command.install import install as DefaultInstallCommand\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"habitat\"))\nfrom version import VERSION # isort:skip noqa\n\n\nwith open(\"README.md\", encoding=\"utf8\") as f:\n readme = f.read()\n\nwith open(\"LICENSE\") as f:\n license = f.read()\n\nwith open(\"requirements.txt\") as f:\n reqs = f.read()\n\nDISTNAME = \"habitat\"\nDESCRIPTION = \"habitat: a suite for embodied agent tasks and benchmarks\"\nLONG_DESCRIPTION = readme\nAUTHOR = \"Facebook AI Research\"\nLICENSE = license\nREQUIREMENTS = reqs.strip().split(\"\\n\")\nBASELINE_PATH = [\"habitat_baselines\", \"habitat_baselines.*\"]\nDEFAULT_EXCLUSION = [\"test\", \"examples\"]\nFULL_REQUIREMENTS = set()\n# collect requirements.txt file in all subdirectories\nfor file_name in glob.glob(\"**/requirements.txt\", recursive=True):\n with open(file_name) as f:\n reqs = f.read()\n FULL_REQUIREMENTS.update(reqs.strip().split(\"\\n\"))\n\n\nclass OptionedCommand:\n r\"\"\"Generic Command class that takes extra user options and modifies\n arguments in setuptools.setup() accordingly.\n Though OptionedCommand inherits directly from object, it assumes\n inheritance from DefaultDevelopCommand or DefaultInstallCommand, as it\n overrides methods from those two classes.\n \"\"\"\n\n user_options = [(\"all\", None, \"include habitat_baselines in installation\")]\n\n def initialize_options(self):\n super().initialize_options()\n self.all = None\n\n def run(self):\n if not self.all: # install core only\n DEFAULT_EXCLUSION.extend(BASELINE_PATH)\n self.distribution.packages = setuptools.find_packages(\n exclude=DEFAULT_EXCLUSION\n )\n # self.distribution accesses arguments of setup() in main()\n else: # install all except test and examples\n self.distribution.install_requires = FULL_REQUIREMENTS\n super().run()\n\n\nclass InstallCommand(OptionedCommand, DefaultInstallCommand):\n user_options = (\n getattr(DefaultInstallCommand, \"user_options\", [])\n + OptionedCommand.user_options\n )\n\n\nclass DevelopCommand(OptionedCommand, DefaultDevelopCommand):\n user_options = (\n getattr(DefaultDevelopCommand, \"user_options\", [])\n + OptionedCommand.user_options\n )\n\n\nif __name__ == \"__main__\":\n setuptools.setup(\n name=DISTNAME,\n install_requires=REQUIREMENTS,\n packages=setuptools.find_packages(exclude=DEFAULT_EXCLUSION),\n version=VERSION,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n author=AUTHOR,\n license=LICENSE,\n setup_requires=[\"pytest-runner\"],\n tests_require=[\"pytest\"],\n include_package_data=True,\n cmdclass={\"install\": InstallCommand, \"develop\": DevelopCommand},\n )\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport glob\nimport os.path\nimport sys\n\nimport setuptools\nfrom setuptools.command.develop import develop as DefaultDevelopCommand\nfrom setuptools.command.install import install as DefaultInstallCommand\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"habitat\"))\nfrom version import VERSION # isort:skip noqa\n\n\nwith open(\"README.md\", encoding=\"utf8\") as f:\n readme = f.read()\n\nwith open(\"LICENSE\") as f:\n license = f.read()\n\nwith open(\"requirements.txt\") as f:\n reqs = f.read()\n\nDISTNAME = \"habitat\"\nDESCRIPTION = \"habitat: a suite for embodied agent tasks and benchmarks\"\nLONG_DESCRIPTION = readme\nAUTHOR = \"Facebook AI Research\"\nLICENSE = license\nREQUIREMENTS = reqs.strip().split(\"\\n\")\nBASELINE_PATH = [\"habitat_baselines\", \"habitat_baselines.*\"]\nDEFAULT_EXCLUSION = [\"test\", \"examples\"]\nFULL_REQUIREMENTS = set()\n# collect requirements.txt file in all subdirectories\nfor file_name in [\"requirements.txt\"] + glob.glob(\n \"habitat_baselines/**/requirements.txt\", recursive=True\n):\n with open(file_name) as f:\n reqs = f.read()\n FULL_REQUIREMENTS.update(reqs.strip().split(\"\\n\"))\n\n\nclass OptionedCommand:\n r\"\"\"Generic Command class that takes extra user options and modifies\n arguments in setuptools.setup() accordingly.\n Though OptionedCommand inherits directly from object, it assumes\n inheritance from DefaultDevelopCommand or DefaultInstallCommand, as it\n overrides methods from those two classes.\n \"\"\"\n\n user_options = [(\"all\", None, \"include habitat_baselines in installation\")]\n\n def initialize_options(self):\n super().initialize_options()\n self.all = None\n\n def run(self):\n if not self.all: # install core only\n DEFAULT_EXCLUSION.extend(BASELINE_PATH)\n self.distribution.packages = setuptools.find_packages(\n exclude=DEFAULT_EXCLUSION\n )\n # self.distribution accesses arguments of setup() in main()\n else: # install all except test and examples\n self.distribution.install_requires = FULL_REQUIREMENTS\n super().run()\n\n\nclass InstallCommand(OptionedCommand, DefaultInstallCommand):\n user_options = (\n getattr(DefaultInstallCommand, \"user_options\", [])\n + OptionedCommand.user_options\n )\n\n\nclass DevelopCommand(OptionedCommand, DefaultDevelopCommand):\n user_options = (\n getattr(DefaultDevelopCommand, \"user_options\", [])\n + OptionedCommand.user_options\n )\n\n\nif __name__ == \"__main__\":\n setuptools.setup(\n name=DISTNAME,\n install_requires=REQUIREMENTS,\n packages=setuptools.find_packages(exclude=DEFAULT_EXCLUSION),\n version=VERSION,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n author=AUTHOR,\n license=LICENSE,\n setup_requires=[\"pytest-runner\"],\n tests_require=[\"pytest\"],\n include_package_data=True,\n cmdclass={\"install\": InstallCommand, \"develop\": DevelopCommand},\n )\n", "path": "setup.py"}]}
1,202
132
gh_patches_debug_40883
rasdani/github-patches
git_diff
fossasia__open-event-server-5135
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add completed orders to order-statistics endpoint **Is your feature request related to a problem? Please describe.** Currently order statistics endpoint does not return completed orders. **Describe the solution you'd like** It should return completed orders and also fix sales accordingly. sales should return order values calculated from completed orders only. **Additional context** Needed in FE. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `app/api/order_statistics/events.py` Content: ``` 1 from flask_rest_jsonapi import ResourceDetail 2 from marshmallow_jsonapi import fields 3 from marshmallow_jsonapi.flask import Schema 4 from sqlalchemy import func 5 6 from app.api.bootstrap import api 7 from app.api.helpers.db import get_count 8 from app.api.helpers.db import safe_query 9 from app.api.helpers.utilities import dasherize 10 from app.models import db 11 from app.models.event import Event 12 from app.models.order import Order, OrderTicket 13 14 15 class OrderStatisticsEventSchema(Schema): 16 """ 17 Api schema for general statistics of event 18 """ 19 20 class Meta: 21 """ 22 Meta class 23 """ 24 type_ = 'order-statistics-event' 25 self_view = 'v1.order_statistics_event_detail' 26 self_view_kwargs = {'id': '<id>'} 27 inflect = dasherize 28 29 id = fields.Str() 30 identifier = fields.Str() 31 tickets = fields.Method("tickets_count") 32 orders = fields.Method("orders_count") 33 sales = fields.Method("sales_count") 34 35 def tickets_count(self, obj): 36 obj_id = obj.id 37 total = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 38 Order.event_id == obj_id).scalar() 39 draft = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 40 Order.event_id == obj_id, Order.status == 'draft').scalar() 41 cancelled = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 42 Order.event_id == obj_id, Order.status == 'cancelled').scalar() 43 pending = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 44 Order.event_id == obj_id, Order.status == 'pending').scalar() 45 expired = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 46 Order.event_id == obj_id, Order.status == 'expired').scalar() 47 placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( 48 Order.event_id == obj_id, Order.status == 'placed').scalar() 49 result = { 50 'total': total or 0, 51 'draft': draft or 0, 52 'cancelled': cancelled or 0, 53 'pending': pending or 0, 54 'expired': expired or 0, 55 'placed': placed or 0 56 } 57 return result 58 59 def orders_count(self, obj): 60 obj_id = obj.id 61 total = get_count(db.session.query(Order).filter(Order.event_id == obj_id)) 62 draft = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'draft')) 63 cancelled = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'cancelled')) 64 pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending')) 65 expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired')) 66 placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed')) 67 result = { 68 'total': total or 0, 69 'draft': draft or 0, 70 'cancelled': cancelled or 0, 71 'pending': pending or 0, 72 'expired': expired or 0, 73 'placed': placed or 0 74 } 75 return result 76 77 def sales_count(self, obj): 78 obj_id = obj.id 79 total = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id).scalar() 80 draft = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, 81 Order.status == 'draft').scalar() 82 cancelled = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, 83 Order.status == 'cancelled').scalar() 84 pending = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, 85 Order.status == 'pending').scalar() 86 expired = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, 87 Order.status == 'expired').scalar() 88 placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, 89 Order.status == 'placed').scalar() 90 result = { 91 'total': total or 0, 92 'draft': draft or 0, 93 'cancelled': cancelled or 0, 94 'pending': pending or 0, 95 'expired': expired or 0, 96 'placed': placed or 0 97 } 98 return result 99 100 101 class OrderStatisticsEventDetail(ResourceDetail): 102 """ 103 Event statistics detail by id 104 """ 105 106 def before_get_object(self, view_kwargs): 107 if view_kwargs.get('identifier'): 108 event = safe_query(self, Event, 'identifier', view_kwargs['identifier'], 'identifier') 109 view_kwargs['id'] = event.id 110 111 methods = ['GET'] 112 decorators = (api.has_permission('is_coorganizer', fetch="id", fetch_as="event_id", model=Event),) 113 schema = OrderStatisticsEventSchema 114 data_layer = {'session': db.session, 115 'model': Event, 116 'methods': { 117 'before_get_object': before_get_object 118 }} 119 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/app/api/order_statistics/events.py b/app/api/order_statistics/events.py --- a/app/api/order_statistics/events.py +++ b/app/api/order_statistics/events.py @@ -46,13 +46,16 @@ Order.event_id == obj_id, Order.status == 'expired').scalar() placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( Order.event_id == obj_id, Order.status == 'placed').scalar() + completed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter( + Order.event_id == obj_id, Order.status == 'completed').scalar() result = { 'total': total or 0, 'draft': draft or 0, 'cancelled': cancelled or 0, 'pending': pending or 0, 'expired': expired or 0, - 'placed': placed or 0 + 'placed': placed or 0, + 'completed': completed or 0 } return result @@ -64,13 +67,15 @@ pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending')) expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired')) placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed')) + completed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'completed')) result = { 'total': total or 0, 'draft': draft or 0, 'cancelled': cancelled or 0, 'pending': pending or 0, 'expired': expired or 0, - 'placed': placed or 0 + 'placed': placed or 0, + 'completed': completed or 0 } return result @@ -87,13 +92,16 @@ Order.status == 'expired').scalar() placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, Order.status == 'placed').scalar() + completed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id, + Order.status == 'completed').scalar() result = { 'total': total or 0, 'draft': draft or 0, 'cancelled': cancelled or 0, 'pending': pending or 0, 'expired': expired or 0, - 'placed': placed or 0 + 'placed': placed or 0, + 'completed': completed or 0 } return result
{"golden_diff": "diff --git a/app/api/order_statistics/events.py b/app/api/order_statistics/events.py\n--- a/app/api/order_statistics/events.py\n+++ b/app/api/order_statistics/events.py\n@@ -46,13 +46,16 @@\n Order.event_id == obj_id, Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'placed').scalar()\n+ completed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n+ Order.event_id == obj_id, Order.status == 'completed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n- 'placed': placed or 0\n+ 'placed': placed or 0,\n+ 'completed': completed or 0\n }\n return result\n \n@@ -64,13 +67,15 @@\n pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending'))\n expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired'))\n placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed'))\n+ completed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'completed'))\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n- 'placed': placed or 0\n+ 'placed': placed or 0,\n+ 'completed': completed or 0\n }\n return result\n \n@@ -87,13 +92,16 @@\n Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'placed').scalar()\n+ completed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n+ Order.status == 'completed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n- 'placed': placed or 0\n+ 'placed': placed or 0,\n+ 'completed': completed or 0\n }\n return result\n", "issue": "Add completed orders to order-statistics endpoint\n**Is your feature request related to a problem? Please describe.**\r\nCurrently order statistics endpoint does not return completed orders.\r\n\r\n**Describe the solution you'd like**\r\nIt should return completed orders and also fix sales accordingly. sales should return order values calculated from completed orders only.\r\n\r\n**Additional context**\r\nNeeded in FE.\r\n\n", "before_files": [{"content": "from flask_rest_jsonapi import ResourceDetail\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Schema\nfrom sqlalchemy import func\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import get_count\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.utilities import dasherize\nfrom app.models import db\nfrom app.models.event import Event\nfrom app.models.order import Order, OrderTicket\n\n\nclass OrderStatisticsEventSchema(Schema):\n \"\"\"\n Api schema for general statistics of event\n \"\"\"\n\n class Meta:\n \"\"\"\n Meta class\n \"\"\"\n type_ = 'order-statistics-event'\n self_view = 'v1.order_statistics_event_detail'\n self_view_kwargs = {'id': '<id>'}\n inflect = dasherize\n\n id = fields.Str()\n identifier = fields.Str()\n tickets = fields.Method(\"tickets_count\")\n orders = fields.Method(\"orders_count\")\n sales = fields.Method(\"sales_count\")\n\n def tickets_count(self, obj):\n obj_id = obj.id\n total = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id).scalar()\n draft = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'draft').scalar()\n cancelled = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'cancelled').scalar()\n pending = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'pending').scalar()\n expired = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'placed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0\n }\n return result\n\n def orders_count(self, obj):\n obj_id = obj.id\n total = get_count(db.session.query(Order).filter(Order.event_id == obj_id))\n draft = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'draft'))\n cancelled = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'cancelled'))\n pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending'))\n expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired'))\n placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed'))\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0\n }\n return result\n\n def sales_count(self, obj):\n obj_id = obj.id\n total = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id).scalar()\n draft = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'draft').scalar()\n cancelled = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'cancelled').scalar()\n pending = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'pending').scalar()\n expired = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'placed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0\n }\n return result\n\n\nclass OrderStatisticsEventDetail(ResourceDetail):\n \"\"\"\n Event statistics detail by id\n \"\"\"\n\n def before_get_object(self, view_kwargs):\n if view_kwargs.get('identifier'):\n event = safe_query(self, Event, 'identifier', view_kwargs['identifier'], 'identifier')\n view_kwargs['id'] = event.id\n\n methods = ['GET']\n decorators = (api.has_permission('is_coorganizer', fetch=\"id\", fetch_as=\"event_id\", model=Event),)\n schema = OrderStatisticsEventSchema\n data_layer = {'session': db.session,\n 'model': Event,\n 'methods': {\n 'before_get_object': before_get_object\n }}\n", "path": "app/api/order_statistics/events.py"}], "after_files": [{"content": "from flask_rest_jsonapi import ResourceDetail\nfrom marshmallow_jsonapi import fields\nfrom marshmallow_jsonapi.flask import Schema\nfrom sqlalchemy import func\n\nfrom app.api.bootstrap import api\nfrom app.api.helpers.db import get_count\nfrom app.api.helpers.db import safe_query\nfrom app.api.helpers.utilities import dasherize\nfrom app.models import db\nfrom app.models.event import Event\nfrom app.models.order import Order, OrderTicket\n\n\nclass OrderStatisticsEventSchema(Schema):\n \"\"\"\n Api schema for general statistics of event\n \"\"\"\n\n class Meta:\n \"\"\"\n Meta class\n \"\"\"\n type_ = 'order-statistics-event'\n self_view = 'v1.order_statistics_event_detail'\n self_view_kwargs = {'id': '<id>'}\n inflect = dasherize\n\n id = fields.Str()\n identifier = fields.Str()\n tickets = fields.Method(\"tickets_count\")\n orders = fields.Method(\"orders_count\")\n sales = fields.Method(\"sales_count\")\n\n def tickets_count(self, obj):\n obj_id = obj.id\n total = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id).scalar()\n draft = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'draft').scalar()\n cancelled = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'cancelled').scalar()\n pending = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'pending').scalar()\n expired = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'placed').scalar()\n completed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(\n Order.event_id == obj_id, Order.status == 'completed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0,\n 'completed': completed or 0\n }\n return result\n\n def orders_count(self, obj):\n obj_id = obj.id\n total = get_count(db.session.query(Order).filter(Order.event_id == obj_id))\n draft = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'draft'))\n cancelled = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'cancelled'))\n pending = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'pending'))\n expired = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'expired'))\n placed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'placed'))\n completed = get_count(db.session.query(Order).filter(Order.event_id == obj_id, Order.status == 'completed'))\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0,\n 'completed': completed or 0\n }\n return result\n\n def sales_count(self, obj):\n obj_id = obj.id\n total = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id).scalar()\n draft = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'draft').scalar()\n cancelled = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'cancelled').scalar()\n pending = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'pending').scalar()\n expired = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'expired').scalar()\n placed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'placed').scalar()\n completed = db.session.query(func.sum(Order.amount.label('sum'))).filter(Order.event_id == obj_id,\n Order.status == 'completed').scalar()\n result = {\n 'total': total or 0,\n 'draft': draft or 0,\n 'cancelled': cancelled or 0,\n 'pending': pending or 0,\n 'expired': expired or 0,\n 'placed': placed or 0,\n 'completed': completed or 0\n }\n return result\n\n\nclass OrderStatisticsEventDetail(ResourceDetail):\n \"\"\"\n Event statistics detail by id\n \"\"\"\n\n def before_get_object(self, view_kwargs):\n if view_kwargs.get('identifier'):\n event = safe_query(self, Event, 'identifier', view_kwargs['identifier'], 'identifier')\n view_kwargs['id'] = event.id\n\n methods = ['GET']\n decorators = (api.has_permission('is_coorganizer', fetch=\"id\", fetch_as=\"event_id\", model=Event),)\n schema = OrderStatisticsEventSchema\n data_layer = {'session': db.session,\n 'model': Event,\n 'methods': {\n 'before_get_object': before_get_object\n }}\n", "path": "app/api/order_statistics/events.py"}]}
1,728
601
gh_patches_debug_5684
rasdani/github-patches
git_diff
pulp__pulpcore-4011
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- RESTAPI document fix for Upstream Pulp Replication API **Version** Pulp installed through the Python modules. "core:3.28.0" "certguard:3.28.0" "file:3.28.0" "python:3.28.0" "rpm:3.28.0" **Describe the bug** Why the attributes of **upstream_pulps_create**/**update** is mentioned again in the **upstream_pulps_replicate" document? Are those attributes (base_url, api_root, domain,...) used at time making an API request "https://PULP-SERVER/pulp/api/v3/upstream_pulps/{object_id}/replicate/"? **To Reproduce** None. **Expected behavior** A fix is required in the REST API document. **Additional context** Create Upstream Pulp API document: https://docs.pulpproject.org/pulpcore/restapi.html#tag/Upstream-Pulps/operation/upstream_pulps_create Upstream Replication API document: https://docs.pulpproject.org/pulpcore/restapi.html#tag/Upstream-Pulps/operation/upstream_pulps_replicate --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pulpcore/app/viewsets/replica.py` Content: ``` 1 """ 2 ViewSet for replicating repositories and distributions from an upstream Pulp 3 """ 4 from django.conf import settings 5 from drf_spectacular.utils import extend_schema 6 from rest_framework import mixins 7 from rest_framework.decorators import action 8 9 from pulpcore.app.models import TaskGroup, UpstreamPulp 10 from pulpcore.app.serializers import AsyncOperationResponseSerializer, UpstreamPulpSerializer 11 from pulpcore.app.viewsets import NamedModelViewSet 12 from pulpcore.app.response import TaskGroupOperationResponse 13 from pulpcore.app.tasks import replicate_distributions 14 from pulpcore.tasking.tasks import dispatch 15 16 17 class UpstreamPulpViewSet( 18 NamedModelViewSet, 19 mixins.CreateModelMixin, 20 mixins.RetrieveModelMixin, 21 mixins.ListModelMixin, 22 mixins.DestroyModelMixin, 23 mixins.UpdateModelMixin, 24 ): 25 """API for configuring an upstream Pulp to replicate. This API is provided as a tech preview.""" 26 27 queryset = UpstreamPulp.objects.all() 28 endpoint_name = "upstream-pulps" 29 serializer_class = UpstreamPulpSerializer 30 ordering = "-pulp_created" 31 32 @extend_schema( 33 summary="Replicate", 34 description="Trigger an asynchronous repository replication task group. This API is " 35 "provided as a tech preview.", 36 responses={202: AsyncOperationResponseSerializer}, 37 ) 38 @action(detail=True, methods=["post"]) 39 def replicate(self, request, pk): 40 """ 41 Triggers an asynchronous repository replication operation. 42 """ 43 server = UpstreamPulp.objects.get(pk=pk) 44 task_group = TaskGroup.objects.create(description=f"Replication of {server.name}") 45 46 uri = "/api/v3/servers/" 47 if settings.DOMAIN_ENABLED: 48 uri = f"/{request.domain.name}{uri}" 49 50 dispatch( 51 replicate_distributions, 52 exclusive_resources=[uri], 53 kwargs={"server_pk": pk}, 54 task_group=task_group, 55 ) 56 57 return TaskGroupOperationResponse(task_group, request) 58 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pulpcore/app/viewsets/replica.py b/pulpcore/app/viewsets/replica.py --- a/pulpcore/app/viewsets/replica.py +++ b/pulpcore/app/viewsets/replica.py @@ -33,6 +33,7 @@ summary="Replicate", description="Trigger an asynchronous repository replication task group. This API is " "provided as a tech preview.", + request=None, responses={202: AsyncOperationResponseSerializer}, ) @action(detail=True, methods=["post"])
{"golden_diff": "diff --git a/pulpcore/app/viewsets/replica.py b/pulpcore/app/viewsets/replica.py\n--- a/pulpcore/app/viewsets/replica.py\n+++ b/pulpcore/app/viewsets/replica.py\n@@ -33,6 +33,7 @@\n summary=\"Replicate\",\n description=\"Trigger an asynchronous repository replication task group. This API is \"\n \"provided as a tech preview.\",\n+ request=None,\n responses={202: AsyncOperationResponseSerializer},\n )\n @action(detail=True, methods=[\"post\"])\n", "issue": "RESTAPI document fix for Upstream Pulp Replication API\n**Version**\r\nPulp installed through the Python modules.\r\n\"core:3.28.0\"\r\n\"certguard:3.28.0\"\r\n\"file:3.28.0\"\r\n\"python:3.28.0\"\r\n\"rpm:3.28.0\"\r\n\r\n**Describe the bug**\r\nWhy the attributes of **upstream_pulps_create**/**update** is mentioned again in the **upstream_pulps_replicate\" document? Are those attributes (base_url, api_root, domain,...) used at time making an API request \"https://PULP-SERVER/pulp/api/v3/upstream_pulps/{object_id}/replicate/\"?\r\n\r\n**To Reproduce**\r\nNone.\r\n\r\n**Expected behavior**\r\nA fix is required in the REST API document.\r\n\r\n**Additional context**\r\nCreate Upstream Pulp API document: https://docs.pulpproject.org/pulpcore/restapi.html#tag/Upstream-Pulps/operation/upstream_pulps_create\r\nUpstream Replication API document: https://docs.pulpproject.org/pulpcore/restapi.html#tag/Upstream-Pulps/operation/upstream_pulps_replicate\r\n\r\n\n", "before_files": [{"content": "\"\"\"\nViewSet for replicating repositories and distributions from an upstream Pulp\n\"\"\"\nfrom django.conf import settings\nfrom drf_spectacular.utils import extend_schema\nfrom rest_framework import mixins\nfrom rest_framework.decorators import action\n\nfrom pulpcore.app.models import TaskGroup, UpstreamPulp\nfrom pulpcore.app.serializers import AsyncOperationResponseSerializer, UpstreamPulpSerializer\nfrom pulpcore.app.viewsets import NamedModelViewSet\nfrom pulpcore.app.response import TaskGroupOperationResponse\nfrom pulpcore.app.tasks import replicate_distributions\nfrom pulpcore.tasking.tasks import dispatch\n\n\nclass UpstreamPulpViewSet(\n NamedModelViewSet,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n mixins.DestroyModelMixin,\n mixins.UpdateModelMixin,\n):\n \"\"\"API for configuring an upstream Pulp to replicate. This API is provided as a tech preview.\"\"\"\n\n queryset = UpstreamPulp.objects.all()\n endpoint_name = \"upstream-pulps\"\n serializer_class = UpstreamPulpSerializer\n ordering = \"-pulp_created\"\n\n @extend_schema(\n summary=\"Replicate\",\n description=\"Trigger an asynchronous repository replication task group. This API is \"\n \"provided as a tech preview.\",\n responses={202: AsyncOperationResponseSerializer},\n )\n @action(detail=True, methods=[\"post\"])\n def replicate(self, request, pk):\n \"\"\"\n Triggers an asynchronous repository replication operation.\n \"\"\"\n server = UpstreamPulp.objects.get(pk=pk)\n task_group = TaskGroup.objects.create(description=f\"Replication of {server.name}\")\n\n uri = \"/api/v3/servers/\"\n if settings.DOMAIN_ENABLED:\n uri = f\"/{request.domain.name}{uri}\"\n\n dispatch(\n replicate_distributions,\n exclusive_resources=[uri],\n kwargs={\"server_pk\": pk},\n task_group=task_group,\n )\n\n return TaskGroupOperationResponse(task_group, request)\n", "path": "pulpcore/app/viewsets/replica.py"}], "after_files": [{"content": "\"\"\"\nViewSet for replicating repositories and distributions from an upstream Pulp\n\"\"\"\nfrom django.conf import settings\nfrom drf_spectacular.utils import extend_schema\nfrom rest_framework import mixins\nfrom rest_framework.decorators import action\n\nfrom pulpcore.app.models import TaskGroup, UpstreamPulp\nfrom pulpcore.app.serializers import AsyncOperationResponseSerializer, UpstreamPulpSerializer\nfrom pulpcore.app.viewsets import NamedModelViewSet\nfrom pulpcore.app.response import TaskGroupOperationResponse\nfrom pulpcore.app.tasks import replicate_distributions\nfrom pulpcore.tasking.tasks import dispatch\n\n\nclass UpstreamPulpViewSet(\n NamedModelViewSet,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.ListModelMixin,\n mixins.DestroyModelMixin,\n mixins.UpdateModelMixin,\n):\n \"\"\"API for configuring an upstream Pulp to replicate. This API is provided as a tech preview.\"\"\"\n\n queryset = UpstreamPulp.objects.all()\n endpoint_name = \"upstream-pulps\"\n serializer_class = UpstreamPulpSerializer\n ordering = \"-pulp_created\"\n\n @extend_schema(\n summary=\"Replicate\",\n description=\"Trigger an asynchronous repository replication task group. This API is \"\n \"provided as a tech preview.\",\n request=None,\n responses={202: AsyncOperationResponseSerializer},\n )\n @action(detail=True, methods=[\"post\"])\n def replicate(self, request, pk):\n \"\"\"\n Triggers an asynchronous repository replication operation.\n \"\"\"\n server = UpstreamPulp.objects.get(pk=pk)\n task_group = TaskGroup.objects.create(description=f\"Replication of {server.name}\")\n\n uri = \"/api/v3/servers/\"\n if settings.DOMAIN_ENABLED:\n uri = f\"/{request.domain.name}{uri}\"\n\n dispatch(\n replicate_distributions,\n exclusive_resources=[uri],\n kwargs={\"server_pk\": pk},\n task_group=task_group,\n )\n\n return TaskGroupOperationResponse(task_group, request)\n", "path": "pulpcore/app/viewsets/replica.py"}]}
1,049
122
gh_patches_debug_121
rasdani/github-patches
git_diff
rotki__rotki-4490
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Extract SQLCipher and pysqlcipher building to different repo ## Problem Definition We have pinned versions of SQLCipher, and pysqlcipher that we use. The build of SQLCipher happens on every build, docker, windows, macos, linux, arm64. Since we use pinned versions we should create a new repo that builds sqlcipher for all the supported OSes/architectures and maybe publishes the wheels/packages to PyPI We only need to build these dependencies when there is a change in version, otherwise there is no need to build them every single time since this increases the build times everywhere and complicates the windows development part. Ideally, it would be nice to include SQLcipher in the python package to make things easier ### Task - Create a separate repo to handle the building and publishing --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `tools/pyinstaller_hooks/hook-pysqlcipher3.py` Content: ``` 1 from PyInstaller.utils.hooks import copy_metadata 2 3 datas = copy_metadata("pysqlcipher3") 4 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/tools/pyinstaller_hooks/hook-pysqlcipher3.py b/tools/pyinstaller_hooks/hook-pysqlcipher3.py --- a/tools/pyinstaller_hooks/hook-pysqlcipher3.py +++ b/tools/pyinstaller_hooks/hook-pysqlcipher3.py @@ -1,3 +1,3 @@ from PyInstaller.utils.hooks import copy_metadata -datas = copy_metadata("pysqlcipher3") +datas = copy_metadata("rotki-pysqlcipher3")
{"golden_diff": "diff --git a/tools/pyinstaller_hooks/hook-pysqlcipher3.py b/tools/pyinstaller_hooks/hook-pysqlcipher3.py\n--- a/tools/pyinstaller_hooks/hook-pysqlcipher3.py\n+++ b/tools/pyinstaller_hooks/hook-pysqlcipher3.py\n@@ -1,3 +1,3 @@\n from PyInstaller.utils.hooks import copy_metadata\n \n-datas = copy_metadata(\"pysqlcipher3\")\n+datas = copy_metadata(\"rotki-pysqlcipher3\")\n", "issue": "Extract SQLCipher and pysqlcipher building to different repo\n## Problem Definition\r\n\r\nWe have pinned versions of SQLCipher, and pysqlcipher that we use.\r\n\r\nThe build of SQLCipher happens on every build, docker, windows, macos, linux, arm64.\r\nSince we use pinned versions we should create a new repo that builds sqlcipher for all the supported OSes/architectures and maybe publishes the wheels/packages to PyPI\r\n\r\nWe only need to build these dependencies when there is a change in version, otherwise there is no need to build them every single time since this increases the build times everywhere and complicates the windows development part.\r\n\r\nIdeally, it would be nice to include SQLcipher in the python package to make things easier\r\n\r\n### Task\r\n- Create a separate repo to handle the building and publishing\r\n\r\n\r\n\n", "before_files": [{"content": "from PyInstaller.utils.hooks import copy_metadata\n\ndatas = copy_metadata(\"pysqlcipher3\")\n", "path": "tools/pyinstaller_hooks/hook-pysqlcipher3.py"}], "after_files": [{"content": "from PyInstaller.utils.hooks import copy_metadata\n\ndatas = copy_metadata(\"rotki-pysqlcipher3\")\n", "path": "tools/pyinstaller_hooks/hook-pysqlcipher3.py"}]}
457
100
gh_patches_debug_36020
rasdani/github-patches
git_diff
scoutapp__scout_apm_python-711
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- PyMongo v4 removed collection methods [PyMongo v4 removed a number of collection methods](https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html). While the agent still functions properly, it's logging failed instrumentation warnings and is breaking the build. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/scout_apm/instruments/pymongo.py` Content: ``` 1 # coding=utf-8 2 from __future__ import absolute_import, division, print_function, unicode_literals 3 4 import logging 5 6 import wrapt 7 8 from scout_apm.core.tracked_request import TrackedRequest 9 10 try: 11 from pymongo.collection import Collection 12 except ImportError: 13 Collection = None 14 15 logger = logging.getLogger(__name__) 16 17 have_patched_collection = False 18 19 20 def ensure_installed(): 21 global have_patched_collection 22 23 logger.debug("Instrumenting pymongo.") 24 25 if Collection is None: 26 logger.debug("Couldn't import pymongo.Collection - probably not installed.") 27 elif not have_patched_collection: 28 for name in COLLECTION_METHODS: 29 try: 30 setattr( 31 Collection, name, wrap_collection_method(getattr(Collection, name)) 32 ) 33 except Exception as exc: 34 logger.warning( 35 "Failed to instrument pymongo.Collection.%s: %r", 36 name, 37 exc, 38 exc_info=exc, 39 ) 40 have_patched_collection = True 41 42 43 COLLECTION_METHODS = [ 44 "aggregate", 45 "aggregate_raw_batches", 46 "bulk_write", 47 "count", 48 "count_documents", 49 "create_index", 50 "create_indexes", 51 "delete_many", 52 "delete_one", 53 "distinct", 54 "drop", 55 "drop_index", 56 "drop_indexes", 57 "ensure_index", 58 "estimated_document_count", 59 "find", 60 "find_and_modify", 61 "find_one", 62 "find_one_and_delete", 63 "find_one_and_replace", 64 "find_one_and_update", 65 "find_raw_batches", 66 "group", 67 "index_information", 68 "inline_map_reduce", 69 "insert", 70 "insert_many", 71 "insert_one", 72 "list_indexes", 73 "map_reduce", 74 "parallel_scan", 75 "reindex", 76 "remove", 77 "rename", 78 "replace_one", 79 "save", 80 "update", 81 "update_many", 82 "update_one", 83 ] 84 85 86 @wrapt.decorator 87 def wrap_collection_method(wrapped, instance, args, kwargs): 88 tracked_request = TrackedRequest.instance() 89 camel_name = "".join(c.title() for c in wrapped.__name__.split("_")) 90 operation = "MongoDB/{}.{}".format(instance.name, camel_name) 91 with tracked_request.span(operation=operation, ignore_children=True) as span: 92 span.tag("name", instance.name) 93 return wrapped(*args, **kwargs) 94 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/scout_apm/instruments/pymongo.py b/src/scout_apm/instruments/pymongo.py --- a/src/scout_apm/instruments/pymongo.py +++ b/src/scout_apm/instruments/pymongo.py @@ -8,8 +8,10 @@ from scout_apm.core.tracked_request import TrackedRequest try: + import pymongo from pymongo.collection import Collection except ImportError: + pymongo = None Collection = None logger = logging.getLogger(__name__) @@ -25,7 +27,10 @@ if Collection is None: logger.debug("Couldn't import pymongo.Collection - probably not installed.") elif not have_patched_collection: - for name in COLLECTION_METHODS: + methods = COLLECTION_METHODS + if pymongo.version_tuple < (4, 0): + methods = COLLECTION_METHODS_V3 + for name in methods: try: setattr( Collection, name, wrap_collection_method(getattr(Collection, name)) @@ -44,7 +49,6 @@ "aggregate", "aggregate_raw_batches", "bulk_write", - "count", "count_documents", "create_index", "create_indexes", @@ -54,32 +58,36 @@ "drop", "drop_index", "drop_indexes", - "ensure_index", "estimated_document_count", "find", - "find_and_modify", "find_one", "find_one_and_delete", "find_one_and_replace", "find_one_and_update", "find_raw_batches", - "group", "index_information", - "inline_map_reduce", - "insert", "insert_many", "insert_one", "list_indexes", + "rename", + "replace_one", + "update_many", + "update_one", +] + +COLLECTION_METHODS_V3 = COLLECTION_METHODS + [ + "count", + "ensure_index", + "find_and_modify", + "group", + "inline_map_reduce", + "insert", "map_reduce", "parallel_scan", "reindex", "remove", - "rename", - "replace_one", "save", "update", - "update_many", - "update_one", ]
{"golden_diff": "diff --git a/src/scout_apm/instruments/pymongo.py b/src/scout_apm/instruments/pymongo.py\n--- a/src/scout_apm/instruments/pymongo.py\n+++ b/src/scout_apm/instruments/pymongo.py\n@@ -8,8 +8,10 @@\n from scout_apm.core.tracked_request import TrackedRequest\n \n try:\n+ import pymongo\n from pymongo.collection import Collection\n except ImportError:\n+ pymongo = None\n Collection = None\n \n logger = logging.getLogger(__name__)\n@@ -25,7 +27,10 @@\n if Collection is None:\n logger.debug(\"Couldn't import pymongo.Collection - probably not installed.\")\n elif not have_patched_collection:\n- for name in COLLECTION_METHODS:\n+ methods = COLLECTION_METHODS\n+ if pymongo.version_tuple < (4, 0):\n+ methods = COLLECTION_METHODS_V3\n+ for name in methods:\n try:\n setattr(\n Collection, name, wrap_collection_method(getattr(Collection, name))\n@@ -44,7 +49,6 @@\n \"aggregate\",\n \"aggregate_raw_batches\",\n \"bulk_write\",\n- \"count\",\n \"count_documents\",\n \"create_index\",\n \"create_indexes\",\n@@ -54,32 +58,36 @@\n \"drop\",\n \"drop_index\",\n \"drop_indexes\",\n- \"ensure_index\",\n \"estimated_document_count\",\n \"find\",\n- \"find_and_modify\",\n \"find_one\",\n \"find_one_and_delete\",\n \"find_one_and_replace\",\n \"find_one_and_update\",\n \"find_raw_batches\",\n- \"group\",\n \"index_information\",\n- \"inline_map_reduce\",\n- \"insert\",\n \"insert_many\",\n \"insert_one\",\n \"list_indexes\",\n+ \"rename\",\n+ \"replace_one\",\n+ \"update_many\",\n+ \"update_one\",\n+]\n+\n+COLLECTION_METHODS_V3 = COLLECTION_METHODS + [\n+ \"count\",\n+ \"ensure_index\",\n+ \"find_and_modify\",\n+ \"group\",\n+ \"inline_map_reduce\",\n+ \"insert\",\n \"map_reduce\",\n \"parallel_scan\",\n \"reindex\",\n \"remove\",\n- \"rename\",\n- \"replace_one\",\n \"save\",\n \"update\",\n- \"update_many\",\n- \"update_one\",\n ]\n", "issue": "PyMongo v4 removed collection methods\n[PyMongo v4 removed a number of collection methods](https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html). While the agent still functions properly, it's logging failed instrumentation warnings and is breaking the build. \n", "before_files": [{"content": "# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport wrapt\n\nfrom scout_apm.core.tracked_request import TrackedRequest\n\ntry:\n from pymongo.collection import Collection\nexcept ImportError:\n Collection = None\n\nlogger = logging.getLogger(__name__)\n\nhave_patched_collection = False\n\n\ndef ensure_installed():\n global have_patched_collection\n\n logger.debug(\"Instrumenting pymongo.\")\n\n if Collection is None:\n logger.debug(\"Couldn't import pymongo.Collection - probably not installed.\")\n elif not have_patched_collection:\n for name in COLLECTION_METHODS:\n try:\n setattr(\n Collection, name, wrap_collection_method(getattr(Collection, name))\n )\n except Exception as exc:\n logger.warning(\n \"Failed to instrument pymongo.Collection.%s: %r\",\n name,\n exc,\n exc_info=exc,\n )\n have_patched_collection = True\n\n\nCOLLECTION_METHODS = [\n \"aggregate\",\n \"aggregate_raw_batches\",\n \"bulk_write\",\n \"count\",\n \"count_documents\",\n \"create_index\",\n \"create_indexes\",\n \"delete_many\",\n \"delete_one\",\n \"distinct\",\n \"drop\",\n \"drop_index\",\n \"drop_indexes\",\n \"ensure_index\",\n \"estimated_document_count\",\n \"find\",\n \"find_and_modify\",\n \"find_one\",\n \"find_one_and_delete\",\n \"find_one_and_replace\",\n \"find_one_and_update\",\n \"find_raw_batches\",\n \"group\",\n \"index_information\",\n \"inline_map_reduce\",\n \"insert\",\n \"insert_many\",\n \"insert_one\",\n \"list_indexes\",\n \"map_reduce\",\n \"parallel_scan\",\n \"reindex\",\n \"remove\",\n \"rename\",\n \"replace_one\",\n \"save\",\n \"update\",\n \"update_many\",\n \"update_one\",\n]\n\n\[email protected]\ndef wrap_collection_method(wrapped, instance, args, kwargs):\n tracked_request = TrackedRequest.instance()\n camel_name = \"\".join(c.title() for c in wrapped.__name__.split(\"_\"))\n operation = \"MongoDB/{}.{}\".format(instance.name, camel_name)\n with tracked_request.span(operation=operation, ignore_children=True) as span:\n span.tag(\"name\", instance.name)\n return wrapped(*args, **kwargs)\n", "path": "src/scout_apm/instruments/pymongo.py"}], "after_files": [{"content": "# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport wrapt\n\nfrom scout_apm.core.tracked_request import TrackedRequest\n\ntry:\n import pymongo\n from pymongo.collection import Collection\nexcept ImportError:\n pymongo = None\n Collection = None\n\nlogger = logging.getLogger(__name__)\n\nhave_patched_collection = False\n\n\ndef ensure_installed():\n global have_patched_collection\n\n logger.debug(\"Instrumenting pymongo.\")\n\n if Collection is None:\n logger.debug(\"Couldn't import pymongo.Collection - probably not installed.\")\n elif not have_patched_collection:\n methods = COLLECTION_METHODS\n if pymongo.version_tuple < (4, 0):\n methods = COLLECTION_METHODS_V3\n for name in methods:\n try:\n setattr(\n Collection, name, wrap_collection_method(getattr(Collection, name))\n )\n except Exception as exc:\n logger.warning(\n \"Failed to instrument pymongo.Collection.%s: %r\",\n name,\n exc,\n exc_info=exc,\n )\n have_patched_collection = True\n\n\nCOLLECTION_METHODS = [\n \"aggregate\",\n \"aggregate_raw_batches\",\n \"bulk_write\",\n \"count_documents\",\n \"create_index\",\n \"create_indexes\",\n \"delete_many\",\n \"delete_one\",\n \"distinct\",\n \"drop\",\n \"drop_index\",\n \"drop_indexes\",\n \"estimated_document_count\",\n \"find\",\n \"find_one\",\n \"find_one_and_delete\",\n \"find_one_and_replace\",\n \"find_one_and_update\",\n \"find_raw_batches\",\n \"index_information\",\n \"insert_many\",\n \"insert_one\",\n \"list_indexes\",\n \"rename\",\n \"replace_one\",\n \"update_many\",\n \"update_one\",\n]\n\nCOLLECTION_METHODS_V3 = COLLECTION_METHODS + [\n \"count\",\n \"ensure_index\",\n \"find_and_modify\",\n \"group\",\n \"inline_map_reduce\",\n \"insert\",\n \"map_reduce\",\n \"parallel_scan\",\n \"reindex\",\n \"remove\",\n \"save\",\n \"update\",\n]\n\n\[email protected]\ndef wrap_collection_method(wrapped, instance, args, kwargs):\n tracked_request = TrackedRequest.instance()\n camel_name = \"\".join(c.title() for c in wrapped.__name__.split(\"_\"))\n operation = \"MongoDB/{}.{}\".format(instance.name, camel_name)\n with tracked_request.span(operation=operation, ignore_children=True) as span:\n span.tag(\"name\", instance.name)\n return wrapped(*args, **kwargs)\n", "path": "src/scout_apm/instruments/pymongo.py"}]}
1,012
515
gh_patches_debug_16145
rasdani/github-patches
git_diff
dmlc__dgl-4219
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [Example][Bug] Running error on the example case: example/pytorch/dimenet ## 🐛 Bug Dimenet example is crashed. ## To Reproduce `python main.py --model-cnf config/dimenet.yaml` ``` Traceback (most recent call last): File "main.py", line 254, in <module> main() File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "main.py", line 165, in main model = DimeNet(emb_size=model_params['emb_size'], File "/workspace/examples/dimenet/modules/dimenet.py", line 64, in __init__ self.rbf_layer = BesselBasisLayer(num_radial=num_radial, File "/workspace/examples/dimenet/modules/bessel_basis_layer.py", line 17, in __init__ self.reset_params() File "/workspace/examples/dimenet/modules/bessel_basis_layer.py", line 20, in reset_params torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi) RuntimeError: a leaf Variable that requires grad is being used in an in-place operation. ``` ## Expected behavior The case should run through ## Environment - DGL Version (e.g., 1.0): 0.9 - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): 1.12 - OS (e.g., Linux): ubuntu - How you installed DGL (`conda`, `pip`, source): source - Build command you used (if compiling from source): - Python version: 3.8 - CUDA/cuDNN version (if applicable): 11.7 - GPU models and configuration (e.g. V100): A100 - Any other relevant information: --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `examples/pytorch/dimenet/modules/bessel_basis_layer.py` Content: ``` 1 import numpy as np 2 import torch 3 import torch.nn as nn 4 5 from modules.envelope import Envelope 6 7 class BesselBasisLayer(nn.Module): 8 def __init__(self, 9 num_radial, 10 cutoff, 11 envelope_exponent=5): 12 super(BesselBasisLayer, self).__init__() 13 14 self.cutoff = cutoff 15 self.envelope = Envelope(envelope_exponent) 16 self.frequencies = nn.Parameter(torch.Tensor(num_radial)) 17 self.reset_params() 18 19 def reset_params(self): 20 torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi) 21 22 def forward(self, g): 23 d_scaled = g.edata['d'] / self.cutoff 24 # Necessary for proper broadcasting behaviour 25 d_scaled = torch.unsqueeze(d_scaled, -1) 26 d_cutoff = self.envelope(d_scaled) 27 g.edata['rbf'] = d_cutoff * torch.sin(self.frequencies * d_scaled) 28 return g ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/examples/pytorch/dimenet/modules/bessel_basis_layer.py b/examples/pytorch/dimenet/modules/bessel_basis_layer.py --- a/examples/pytorch/dimenet/modules/bessel_basis_layer.py +++ b/examples/pytorch/dimenet/modules/bessel_basis_layer.py @@ -17,7 +17,9 @@ self.reset_params() def reset_params(self): - torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi) + with torch.no_grad(): + torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi) + self.frequencies.requires_grad_() def forward(self, g): d_scaled = g.edata['d'] / self.cutoff @@ -25,4 +27,4 @@ d_scaled = torch.unsqueeze(d_scaled, -1) d_cutoff = self.envelope(d_scaled) g.edata['rbf'] = d_cutoff * torch.sin(self.frequencies * d_scaled) - return g \ No newline at end of file + return g
{"golden_diff": "diff --git a/examples/pytorch/dimenet/modules/bessel_basis_layer.py b/examples/pytorch/dimenet/modules/bessel_basis_layer.py\n--- a/examples/pytorch/dimenet/modules/bessel_basis_layer.py\n+++ b/examples/pytorch/dimenet/modules/bessel_basis_layer.py\n@@ -17,7 +17,9 @@\n self.reset_params()\n \n def reset_params(self):\n- torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi)\n+ with torch.no_grad():\n+ torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi)\n+ self.frequencies.requires_grad_()\n \n def forward(self, g):\n d_scaled = g.edata['d'] / self.cutoff\n@@ -25,4 +27,4 @@\n d_scaled = torch.unsqueeze(d_scaled, -1)\n d_cutoff = self.envelope(d_scaled)\n g.edata['rbf'] = d_cutoff * torch.sin(self.frequencies * d_scaled)\n- return g\n\\ No newline at end of file\n+ return g\n", "issue": "[Example][Bug] Running error on the example case: example/pytorch/dimenet\n## \ud83d\udc1b Bug\r\n\r\nDimenet example is crashed. \r\n\r\n## To Reproduce\r\n\r\n`python main.py --model-cnf config/dimenet.yaml`\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"main.py\", line 254, in <module>\r\n main()\r\n File \"/opt/conda/lib/python3.8/site-packages/click/core.py\", line 1128, in __call__\r\n return self.main(*args, **kwargs)\r\n File \"/opt/conda/lib/python3.8/site-packages/click/core.py\", line 1053, in main\r\n rv = self.invoke(ctx)\r\n File \"/opt/conda/lib/python3.8/site-packages/click/core.py\", line 1395, in invoke\r\n return ctx.invoke(self.callback, **ctx.params)\r\n File \"/opt/conda/lib/python3.8/site-packages/click/core.py\", line 754, in invoke\r\n return __callback(*args, **kwargs)\r\n File \"main.py\", line 165, in main\r\n model = DimeNet(emb_size=model_params['emb_size'],\r\n File \"/workspace/examples/dimenet/modules/dimenet.py\", line 64, in __init__\r\n self.rbf_layer = BesselBasisLayer(num_radial=num_radial,\r\n File \"/workspace/examples/dimenet/modules/bessel_basis_layer.py\", line 17, in __init__\r\n self.reset_params()\r\n File \"/workspace/examples/dimenet/modules/bessel_basis_layer.py\", line 20, in reset_params\r\n torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi)\r\nRuntimeError: a leaf Variable that requires grad is being used in an in-place operation.\r\n```\r\n\r\n## Expected behavior\r\n\r\nThe case should run through\r\n\r\n## Environment\r\n\r\n - DGL Version (e.g., 1.0): 0.9\r\n - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): 1.12\r\n - OS (e.g., Linux): ubuntu\r\n - How you installed DGL (`conda`, `pip`, source): source\r\n - Build command you used (if compiling from source):\r\n - Python version: 3.8\r\n - CUDA/cuDNN version (if applicable): 11.7\r\n - GPU models and configuration (e.g. V100): A100\r\n - Any other relevant information:\r\n\r\n\n", "before_files": [{"content": "import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom modules.envelope import Envelope\n\nclass BesselBasisLayer(nn.Module):\n def __init__(self,\n num_radial,\n cutoff,\n envelope_exponent=5):\n super(BesselBasisLayer, self).__init__()\n \n self.cutoff = cutoff\n self.envelope = Envelope(envelope_exponent)\n self.frequencies = nn.Parameter(torch.Tensor(num_radial))\n self.reset_params()\n\n def reset_params(self):\n torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi)\n\n def forward(self, g):\n d_scaled = g.edata['d'] / self.cutoff\n # Necessary for proper broadcasting behaviour\n d_scaled = torch.unsqueeze(d_scaled, -1)\n d_cutoff = self.envelope(d_scaled)\n g.edata['rbf'] = d_cutoff * torch.sin(self.frequencies * d_scaled)\n return g", "path": "examples/pytorch/dimenet/modules/bessel_basis_layer.py"}], "after_files": [{"content": "import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom modules.envelope import Envelope\n\nclass BesselBasisLayer(nn.Module):\n def __init__(self,\n num_radial,\n cutoff,\n envelope_exponent=5):\n super(BesselBasisLayer, self).__init__()\n \n self.cutoff = cutoff\n self.envelope = Envelope(envelope_exponent)\n self.frequencies = nn.Parameter(torch.Tensor(num_radial))\n self.reset_params()\n\n def reset_params(self):\n with torch.no_grad():\n torch.arange(1, self.frequencies.numel() + 1, out=self.frequencies).mul_(np.pi)\n self.frequencies.requires_grad_()\n\n def forward(self, g):\n d_scaled = g.edata['d'] / self.cutoff\n # Necessary for proper broadcasting behaviour\n d_scaled = torch.unsqueeze(d_scaled, -1)\n d_cutoff = self.envelope(d_scaled)\n g.edata['rbf'] = d_cutoff * torch.sin(self.frequencies * d_scaled)\n return g\n", "path": "examples/pytorch/dimenet/modules/bessel_basis_layer.py"}]}
1,084
249
gh_patches_debug_22613
rasdani/github-patches
git_diff
facebookresearch__fairscale-237
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [ShardedGradScaler] Handle optimizers not being OSS instances ## 🚀 Feature Some frameworks (Classy for instance) change the optimizers to enable different non-pytorch-compliant features. ShardedGradScaler asserts on that ## Motivation Enable ShardedDDP + AMP on Classy-like frameworks ## Pitch Remove the assert, replace by a one time warning ## Alternatives Not doing anything ## Additional context @mannatsingh --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `fairscale/optim/grad_scaler.py` Content: ``` 1 # Copyright (c) Facebook, Inc. and its affiliates. 2 # 3 # This source code is licensed under the MIT license found in the 4 # LICENSE file in the root directory of this source tree. 5 6 from typing import Dict 7 8 import torch 9 from torch.cuda.amp import GradScaler as TorchGradScaler 10 import torch.distributed as dist 11 from torch.optim import Optimizer 12 13 from .oss import OSS 14 15 16 class GradScaler(TorchGradScaler): 17 def _unscale_grads_( 18 self, optimizer: Optimizer, inv_scale: torch.Tensor, found_inf: torch.Tensor, allow_fp16: bool 19 ) -> Dict[torch.device, torch.Tensor]: 20 return super()._unscale_grads_(optimizer, inv_scale, found_inf, True) 21 22 23 class ShardedGradScaler(TorchGradScaler): 24 """ 25 A shard-aware :class:`GradScaler<torch.cuda.amp.GradScaler>`, to be used in conjunction with 26 :class:`OSS` and :class:`ShardedOptimizer`. 27 28 Interface and usecases are not changed, more explanations can be found in the corresponding pytorch 29 documentation https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.GradScaler 30 """ 31 32 def __init__(self) -> None: 33 super().__init__() 34 35 def unscale_(self, optimizer: Optimizer) -> None: 36 assert isinstance(optimizer, OSS), "ShardedGradScaler is to be used in combination with a sharded optimizer" 37 38 # Call the upstream unscale_ method which will only act on this rank's gradients 39 super().unscale_(optimizer) 40 41 # Synchronize the detected inf across the ranks 42 optimizer_state = self._per_optimizer_states[id(optimizer)] 43 handles = [dist.all_reduce(v, async_op=True) for v in optimizer_state["found_inf_per_device"].values()] 44 45 # Make sure that the calls are done before moving out 46 _ = list(map(lambda x: x.wait(), handles)) 47 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/fairscale/optim/grad_scaler.py b/fairscale/optim/grad_scaler.py --- a/fairscale/optim/grad_scaler.py +++ b/fairscale/optim/grad_scaler.py @@ -3,6 +3,7 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. +import logging from typing import Dict import torch @@ -31,9 +32,16 @@ def __init__(self) -> None: super().__init__() + self.display_warning = True def unscale_(self, optimizer: Optimizer) -> None: - assert isinstance(optimizer, OSS), "ShardedGradScaler is to be used in combination with a sharded optimizer" + # Could be a mistake, this scaler is supposed to work with ZeroRedundancyOptimizer only + if self.display_warning and not isinstance(optimizer, OSS): + logging.warning( + "ShardedGradScaler is to be used in combination with a sharded optimizer, this could not be checked" + ) + + self.display_warning = False # Only warn once # Call the upstream unscale_ method which will only act on this rank's gradients super().unscale_(optimizer)
{"golden_diff": "diff --git a/fairscale/optim/grad_scaler.py b/fairscale/optim/grad_scaler.py\n--- a/fairscale/optim/grad_scaler.py\n+++ b/fairscale/optim/grad_scaler.py\n@@ -3,6 +3,7 @@\n # This source code is licensed under the MIT license found in the\n # LICENSE file in the root directory of this source tree.\n \n+import logging\n from typing import Dict\n \n import torch\n@@ -31,9 +32,16 @@\n \n def __init__(self) -> None:\n super().__init__()\n+ self.display_warning = True\n \n def unscale_(self, optimizer: Optimizer) -> None:\n- assert isinstance(optimizer, OSS), \"ShardedGradScaler is to be used in combination with a sharded optimizer\"\n+ # Could be a mistake, this scaler is supposed to work with ZeroRedundancyOptimizer only\n+ if self.display_warning and not isinstance(optimizer, OSS):\n+ logging.warning(\n+ \"ShardedGradScaler is to be used in combination with a sharded optimizer, this could not be checked\"\n+ )\n+\n+ self.display_warning = False # Only warn once\n \n # Call the upstream unscale_ method which will only act on this rank's gradients\n super().unscale_(optimizer)\n", "issue": "[ShardedGradScaler] Handle optimizers not being OSS instances\n## \ud83d\ude80 Feature\r\nSome frameworks (Classy for instance) change the optimizers to enable different non-pytorch-compliant features. ShardedGradScaler asserts on that\r\n\r\n## Motivation\r\nEnable ShardedDDP + AMP on Classy-like frameworks\r\n\r\n## Pitch\r\nRemove the assert, replace by a one time warning\r\n\r\n## Alternatives\r\nNot doing anything\r\n\r\n## Additional context\r\n@mannatsingh \n", "before_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import Dict\n\nimport torch\nfrom torch.cuda.amp import GradScaler as TorchGradScaler\nimport torch.distributed as dist\nfrom torch.optim import Optimizer\n\nfrom .oss import OSS\n\n\nclass GradScaler(TorchGradScaler):\n def _unscale_grads_(\n self, optimizer: Optimizer, inv_scale: torch.Tensor, found_inf: torch.Tensor, allow_fp16: bool\n ) -> Dict[torch.device, torch.Tensor]:\n return super()._unscale_grads_(optimizer, inv_scale, found_inf, True)\n\n\nclass ShardedGradScaler(TorchGradScaler):\n \"\"\"\n A shard-aware :class:`GradScaler<torch.cuda.amp.GradScaler>`, to be used in conjunction with\n :class:`OSS` and :class:`ShardedOptimizer`.\n\n Interface and usecases are not changed, more explanations can be found in the corresponding pytorch\n documentation https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.GradScaler\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n\n def unscale_(self, optimizer: Optimizer) -> None:\n assert isinstance(optimizer, OSS), \"ShardedGradScaler is to be used in combination with a sharded optimizer\"\n\n # Call the upstream unscale_ method which will only act on this rank's gradients\n super().unscale_(optimizer)\n\n # Synchronize the detected inf across the ranks\n optimizer_state = self._per_optimizer_states[id(optimizer)]\n handles = [dist.all_reduce(v, async_op=True) for v in optimizer_state[\"found_inf_per_device\"].values()]\n\n # Make sure that the calls are done before moving out\n _ = list(map(lambda x: x.wait(), handles))\n", "path": "fairscale/optim/grad_scaler.py"}], "after_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\nfrom typing import Dict\n\nimport torch\nfrom torch.cuda.amp import GradScaler as TorchGradScaler\nimport torch.distributed as dist\nfrom torch.optim import Optimizer\n\nfrom .oss import OSS\n\n\nclass GradScaler(TorchGradScaler):\n def _unscale_grads_(\n self, optimizer: Optimizer, inv_scale: torch.Tensor, found_inf: torch.Tensor, allow_fp16: bool\n ) -> Dict[torch.device, torch.Tensor]:\n return super()._unscale_grads_(optimizer, inv_scale, found_inf, True)\n\n\nclass ShardedGradScaler(TorchGradScaler):\n \"\"\"\n A shard-aware :class:`GradScaler<torch.cuda.amp.GradScaler>`, to be used in conjunction with\n :class:`OSS` and :class:`ShardedOptimizer`.\n\n Interface and usecases are not changed, more explanations can be found in the corresponding pytorch\n documentation https://pytorch.org/docs/stable/amp.html#torch.cuda.amp.GradScaler\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self.display_warning = True\n\n def unscale_(self, optimizer: Optimizer) -> None:\n # Could be a mistake, this scaler is supposed to work with ZeroRedundancyOptimizer only\n if self.display_warning and not isinstance(optimizer, OSS):\n logging.warning(\n \"ShardedGradScaler is to be used in combination with a sharded optimizer, this could not be checked\"\n )\n\n self.display_warning = False # Only warn once\n\n # Call the upstream unscale_ method which will only act on this rank's gradients\n super().unscale_(optimizer)\n\n # Synchronize the detected inf across the ranks\n optimizer_state = self._per_optimizer_states[id(optimizer)]\n handles = [dist.all_reduce(v, async_op=True) for v in optimizer_state[\"found_inf_per_device\"].values()]\n\n # Make sure that the calls are done before moving out\n _ = list(map(lambda x: x.wait(), handles))\n", "path": "fairscale/optim/grad_scaler.py"}]}
870
287
gh_patches_debug_29280
rasdani/github-patches
git_diff
lightly-ai__lightly-993
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- NNMemoryBank not working with DataParallel I have been using the NNMemoryBank as a component in my module and noticed that at each forward pass `NNMemoryBank.bank` is equal to `None`. This only occurs when my module is wrapped in `DataParallel`. As a result, throughout training my NN pairs are always random noise (surprisingly, this only hurt the contrastive learning performance by a few percentage point on linear probing??). Here is a simple test case that highlights the issue: ``` import torch from lightly.models.modules import NNMemoryBankModule memory_bank = NNMemoryBankModule(size=1000) print(memory_bank.bank) memory_bank(torch.randn((100, 512))) print(memory_bank.bank) memory_bank = NNMemoryBankModule(size=1000) memory_bank = torch.nn.DataParallel(memory_bank, device_ids=[0,1]) print(memory_bank.module.bank) memory_bank(torch.randn((100, 512))) print(memory_bank.module.bank) ``` The output of the first is `None` and a `torch.Tensor`, as expected. The output for the second is `None` for both. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `lightly/loss/memory_bank.py` Content: ``` 1 """ Memory Bank Wrapper """ 2 3 # Copyright (c) 2020. Lightly AG and its affiliates. 4 # All Rights Reserved 5 6 import torch 7 import functools 8 9 class MemoryBankModule(torch.nn.Module): 10 """Memory bank implementation 11 12 This is a parent class to all loss functions implemented by the lightly 13 Python package. This way, any loss can be used with a memory bank if 14 desired. 15 16 Attributes: 17 size: 18 Number of keys the memory bank can store. If set to 0, 19 memory bank is not used. 20 21 Examples: 22 >>> class MyLossFunction(MemoryBankModule): 23 >>> 24 >>> def __init__(self, memory_bank_size: int = 2 ** 16): 25 >>> super(MyLossFunction, self).__init__(memory_bank_size) 26 >>> 27 >>> def forward(self, output: torch.Tensor, 28 >>> labels: torch.Tensor = None): 29 >>> 30 >>> output, negatives = super( 31 >>> MyLossFunction, self).forward(output) 32 >>> 33 >>> if negatives is not None: 34 >>> # evaluate loss with negative samples 35 >>> else: 36 >>> # evaluate loss without negative samples 37 38 """ 39 40 def __init__(self, size: int = 2 ** 16): 41 42 super(MemoryBankModule, self).__init__() 43 44 if size < 0: 45 msg = f'Illegal memory bank size {size}, must be non-negative.' 46 raise ValueError(msg) 47 48 self.size = size 49 50 self.bank = None 51 self.bank_ptr = None 52 53 @torch.no_grad() 54 def _init_memory_bank(self, dim: int): 55 """Initialize the memory bank if it's empty 56 57 Args: 58 dim: 59 The dimension of the which are stored in the bank. 60 61 """ 62 # create memory bank 63 # we could use register buffers like in the moco repo 64 # https://github.com/facebookresearch/moco but we don't 65 # want to pollute our checkpoints 66 self.bank = torch.randn(dim, self.size) 67 self.bank = torch.nn.functional.normalize(self.bank, dim=0) 68 self.bank_ptr = torch.LongTensor([0]) 69 70 @torch.no_grad() 71 def _dequeue_and_enqueue(self, batch: torch.Tensor): 72 """Dequeue the oldest batch and add the latest one 73 74 Args: 75 batch: 76 The latest batch of keys to add to the memory bank. 77 78 """ 79 batch_size = batch.shape[0] 80 ptr = int(self.bank_ptr) 81 82 if ptr + batch_size >= self.size: 83 self.bank[:, ptr:] = batch[:self.size - ptr].T.detach() 84 self.bank_ptr[0] = 0 85 else: 86 self.bank[:, ptr:ptr + batch_size] = batch.T.detach() 87 self.bank_ptr[0] = ptr + batch_size 88 89 def forward(self, 90 output: torch.Tensor, 91 labels: torch.Tensor = None, 92 update: bool = False): 93 """Query memory bank for additional negative samples 94 95 Args: 96 output: 97 The output of the model. 98 labels: 99 Should always be None, will be ignored. 100 101 Returns: 102 The output if the memory bank is of size 0, otherwise the output 103 and the entries from the memory bank. 104 105 """ 106 107 # no memory bank, return the output 108 if self.size == 0: 109 return output, None 110 111 _, dim = output.shape 112 113 # initialize the memory bank if it is not already done 114 if self.bank is None: 115 self._init_memory_bank(dim) 116 117 # query and update memory bank 118 bank = self.bank.clone().detach() 119 120 # only update memory bank if we later do backward pass (gradient) 121 if update: 122 self._dequeue_and_enqueue(output) 123 124 return output, bank 125 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/lightly/loss/memory_bank.py b/lightly/loss/memory_bank.py --- a/lightly/loss/memory_bank.py +++ b/lightly/loss/memory_bank.py @@ -46,10 +46,9 @@ raise ValueError(msg) self.size = size + self.register_buffer("bank", tensor=torch.empty(0, dtype=torch.float), persistent=False) + self.register_buffer("bank_ptr", tensor=torch.empty(0, dtype=torch.long), persistent=False) - self.bank = None - self.bank_ptr = None - @torch.no_grad() def _init_memory_bank(self, dim: int): """Initialize the memory bank if it's empty @@ -63,9 +62,9 @@ # we could use register buffers like in the moco repo # https://github.com/facebookresearch/moco but we don't # want to pollute our checkpoints - self.bank = torch.randn(dim, self.size) - self.bank = torch.nn.functional.normalize(self.bank, dim=0) - self.bank_ptr = torch.LongTensor([0]) + self.bank = torch.randn(dim, self.size).type_as(self.bank) + torch.nn.functional.normalize(self.bank, dim=0) + self.bank_ptr = torch.zeros(1).type_as(self.bank_ptr) @torch.no_grad() def _dequeue_and_enqueue(self, batch: torch.Tensor): @@ -111,7 +110,7 @@ _, dim = output.shape # initialize the memory bank if it is not already done - if self.bank is None: + if self.bank.nelement() == 0: self._init_memory_bank(dim) # query and update memory bank
{"golden_diff": "diff --git a/lightly/loss/memory_bank.py b/lightly/loss/memory_bank.py\n--- a/lightly/loss/memory_bank.py\n+++ b/lightly/loss/memory_bank.py\n@@ -46,10 +46,9 @@\n raise ValueError(msg)\n \n self.size = size\n+ self.register_buffer(\"bank\", tensor=torch.empty(0, dtype=torch.float), persistent=False)\n+ self.register_buffer(\"bank_ptr\", tensor=torch.empty(0, dtype=torch.long), persistent=False)\n \n- self.bank = None\n- self.bank_ptr = None\n- \n @torch.no_grad()\n def _init_memory_bank(self, dim: int):\n \"\"\"Initialize the memory bank if it's empty\n@@ -63,9 +62,9 @@\n # we could use register buffers like in the moco repo\n # https://github.com/facebookresearch/moco but we don't\n # want to pollute our checkpoints\n- self.bank = torch.randn(dim, self.size)\n- self.bank = torch.nn.functional.normalize(self.bank, dim=0)\n- self.bank_ptr = torch.LongTensor([0])\n+ self.bank = torch.randn(dim, self.size).type_as(self.bank)\n+ torch.nn.functional.normalize(self.bank, dim=0)\n+ self.bank_ptr = torch.zeros(1).type_as(self.bank_ptr)\n \n @torch.no_grad()\n def _dequeue_and_enqueue(self, batch: torch.Tensor):\n@@ -111,7 +110,7 @@\n _, dim = output.shape\n \n # initialize the memory bank if it is not already done\n- if self.bank is None:\n+ if self.bank.nelement() == 0:\n self._init_memory_bank(dim)\n \n # query and update memory bank\n", "issue": "NNMemoryBank not working with DataParallel\nI have been using the NNMemoryBank as a component in my module and noticed that at each forward pass `NNMemoryBank.bank` is equal to `None`. This only occurs when my module is wrapped in `DataParallel`. As a result, throughout training my NN pairs are always random noise (surprisingly, this only hurt the contrastive learning performance by a few percentage point on linear probing??).\r\n\r\nHere is a simple test case that highlights the issue:\r\n```\r\nimport torch\r\nfrom lightly.models.modules import NNMemoryBankModule\r\nmemory_bank = NNMemoryBankModule(size=1000)\r\nprint(memory_bank.bank)\r\nmemory_bank(torch.randn((100, 512)))\r\nprint(memory_bank.bank)\r\n\r\nmemory_bank = NNMemoryBankModule(size=1000)\r\nmemory_bank = torch.nn.DataParallel(memory_bank, device_ids=[0,1])\r\nprint(memory_bank.module.bank)\r\nmemory_bank(torch.randn((100, 512)))\r\nprint(memory_bank.module.bank)\r\n```\r\n\r\nThe output of the first is `None` and a `torch.Tensor`, as expected. The output for the second is `None` for both.\n", "before_files": [{"content": "\"\"\" Memory Bank Wrapper \"\"\"\n\n# Copyright (c) 2020. Lightly AG and its affiliates.\n# All Rights Reserved\n\nimport torch\nimport functools\n\nclass MemoryBankModule(torch.nn.Module):\n \"\"\"Memory bank implementation\n\n This is a parent class to all loss functions implemented by the lightly\n Python package. This way, any loss can be used with a memory bank if \n desired.\n\n Attributes:\n size:\n Number of keys the memory bank can store. If set to 0,\n memory bank is not used.\n\n Examples:\n >>> class MyLossFunction(MemoryBankModule):\n >>>\n >>> def __init__(self, memory_bank_size: int = 2 ** 16):\n >>> super(MyLossFunction, self).__init__(memory_bank_size)\n >>>\n >>> def forward(self, output: torch.Tensor,\n >>> labels: torch.Tensor = None):\n >>>\n >>> output, negatives = super(\n >>> MyLossFunction, self).forward(output)\n >>>\n >>> if negatives is not None:\n >>> # evaluate loss with negative samples\n >>> else:\n >>> # evaluate loss without negative samples\n\n \"\"\"\n\n def __init__(self, size: int = 2 ** 16):\n\n super(MemoryBankModule, self).__init__()\n\n if size < 0:\n msg = f'Illegal memory bank size {size}, must be non-negative.'\n raise ValueError(msg)\n\n self.size = size\n\n self.bank = None\n self.bank_ptr = None\n \n @torch.no_grad()\n def _init_memory_bank(self, dim: int):\n \"\"\"Initialize the memory bank if it's empty\n\n Args:\n dim:\n The dimension of the which are stored in the bank.\n\n \"\"\"\n # create memory bank\n # we could use register buffers like in the moco repo\n # https://github.com/facebookresearch/moco but we don't\n # want to pollute our checkpoints\n self.bank = torch.randn(dim, self.size)\n self.bank = torch.nn.functional.normalize(self.bank, dim=0)\n self.bank_ptr = torch.LongTensor([0])\n\n @torch.no_grad()\n def _dequeue_and_enqueue(self, batch: torch.Tensor):\n \"\"\"Dequeue the oldest batch and add the latest one\n\n Args:\n batch:\n The latest batch of keys to add to the memory bank.\n\n \"\"\"\n batch_size = batch.shape[0]\n ptr = int(self.bank_ptr)\n\n if ptr + batch_size >= self.size:\n self.bank[:, ptr:] = batch[:self.size - ptr].T.detach()\n self.bank_ptr[0] = 0\n else:\n self.bank[:, ptr:ptr + batch_size] = batch.T.detach()\n self.bank_ptr[0] = ptr + batch_size\n\n def forward(self,\n output: torch.Tensor,\n labels: torch.Tensor = None,\n update: bool = False):\n \"\"\"Query memory bank for additional negative samples\n\n Args:\n output:\n The output of the model.\n labels:\n Should always be None, will be ignored.\n\n Returns:\n The output if the memory bank is of size 0, otherwise the output\n and the entries from the memory bank.\n\n \"\"\"\n\n # no memory bank, return the output\n if self.size == 0:\n return output, None\n\n _, dim = output.shape\n\n # initialize the memory bank if it is not already done\n if self.bank is None:\n self._init_memory_bank(dim)\n\n # query and update memory bank\n bank = self.bank.clone().detach()\n\n # only update memory bank if we later do backward pass (gradient)\n if update:\n self._dequeue_and_enqueue(output)\n\n return output, bank\n", "path": "lightly/loss/memory_bank.py"}], "after_files": [{"content": "\"\"\" Memory Bank Wrapper \"\"\"\n\n# Copyright (c) 2020. Lightly AG and its affiliates.\n# All Rights Reserved\n\nimport torch\nimport functools\n\nclass MemoryBankModule(torch.nn.Module):\n \"\"\"Memory bank implementation\n\n This is a parent class to all loss functions implemented by the lightly\n Python package. This way, any loss can be used with a memory bank if \n desired.\n\n Attributes:\n size:\n Number of keys the memory bank can store. If set to 0,\n memory bank is not used.\n\n Examples:\n >>> class MyLossFunction(MemoryBankModule):\n >>>\n >>> def __init__(self, memory_bank_size: int = 2 ** 16):\n >>> super(MyLossFunction, self).__init__(memory_bank_size)\n >>>\n >>> def forward(self, output: torch.Tensor,\n >>> labels: torch.Tensor = None):\n >>>\n >>> output, negatives = super(\n >>> MyLossFunction, self).forward(output)\n >>>\n >>> if negatives is not None:\n >>> # evaluate loss with negative samples\n >>> else:\n >>> # evaluate loss without negative samples\n\n \"\"\"\n\n def __init__(self, size: int = 2 ** 16):\n\n super(MemoryBankModule, self).__init__()\n\n if size < 0:\n msg = f'Illegal memory bank size {size}, must be non-negative.'\n raise ValueError(msg)\n\n self.size = size\n self.register_buffer(\"bank\", tensor=torch.empty(0, dtype=torch.float), persistent=False)\n self.register_buffer(\"bank_ptr\", tensor=torch.empty(0, dtype=torch.long), persistent=False)\n\n @torch.no_grad()\n def _init_memory_bank(self, dim: int):\n \"\"\"Initialize the memory bank if it's empty\n\n Args:\n dim:\n The dimension of the which are stored in the bank.\n\n \"\"\"\n # create memory bank\n # we could use register buffers like in the moco repo\n # https://github.com/facebookresearch/moco but we don't\n # want to pollute our checkpoints\n self.bank = torch.randn(dim, self.size).type_as(self.bank)\n torch.nn.functional.normalize(self.bank, dim=0)\n self.bank_ptr = torch.zeros(1).type_as(self.bank_ptr)\n\n @torch.no_grad()\n def _dequeue_and_enqueue(self, batch: torch.Tensor):\n \"\"\"Dequeue the oldest batch and add the latest one\n\n Args:\n batch:\n The latest batch of keys to add to the memory bank.\n\n \"\"\"\n batch_size = batch.shape[0]\n ptr = int(self.bank_ptr)\n\n if ptr + batch_size >= self.size:\n self.bank[:, ptr:] = batch[:self.size - ptr].T.detach()\n self.bank_ptr[0] = 0\n else:\n self.bank[:, ptr:ptr + batch_size] = batch.T.detach()\n self.bank_ptr[0] = ptr + batch_size\n\n def forward(self,\n output: torch.Tensor,\n labels: torch.Tensor = None,\n update: bool = False):\n \"\"\"Query memory bank for additional negative samples\n\n Args:\n output:\n The output of the model.\n labels:\n Should always be None, will be ignored.\n\n Returns:\n The output if the memory bank is of size 0, otherwise the output\n and the entries from the memory bank.\n\n \"\"\"\n\n # no memory bank, return the output\n if self.size == 0:\n return output, None\n\n _, dim = output.shape\n\n # initialize the memory bank if it is not already done\n if self.bank.nelement() == 0:\n self._init_memory_bank(dim)\n\n # query and update memory bank\n bank = self.bank.clone().detach()\n\n # only update memory bank if we later do backward pass (gradient)\n if update:\n self._dequeue_and_enqueue(output)\n\n return output, bank\n", "path": "lightly/loss/memory_bank.py"}]}
1,607
384
gh_patches_debug_9243
rasdani/github-patches
git_diff
getnikola__nikola-971
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Drafts are leaked in feeds Reported by @kayhayen in the mailing list. Proposed patch breaks tests, so checking things out a bit more carefully. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `nikola/plugins/task/rss.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 3 # Copyright © 2012-2014 Roberto Alsina and others. 4 5 # Permission is hereby granted, free of charge, to any 6 # person obtaining a copy of this software and associated 7 # documentation files (the "Software"), to deal in the 8 # Software without restriction, including without limitation 9 # the rights to use, copy, modify, merge, publish, 10 # distribute, sublicense, and/or sell copies of the 11 # Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice 15 # shall be included in all copies or substantial portions of 16 # the Software. 17 # 18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 21 # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 22 # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 23 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 24 # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 25 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 26 27 from __future__ import unicode_literals, print_function 28 import os 29 try: 30 from urlparse import urljoin 31 except ImportError: 32 from urllib.parse import urljoin # NOQA 33 34 from nikola import utils 35 from nikola.plugin_categories import Task 36 37 38 class GenerateRSS(Task): 39 """Generate RSS feeds.""" 40 41 name = "generate_rss" 42 43 def set_site(self, site): 44 site.register_path_handler('rss', self.rss_path) 45 return super(GenerateRSS, self).set_site(site) 46 47 def gen_tasks(self): 48 """Generate RSS feeds.""" 49 kw = { 50 "translations": self.site.config["TRANSLATIONS"], 51 "filters": self.site.config["FILTERS"], 52 "blog_title": self.site.config["BLOG_TITLE"], 53 "site_url": self.site.config["SITE_URL"], 54 "blog_description": self.site.config["BLOG_DESCRIPTION"], 55 "output_folder": self.site.config["OUTPUT_FOLDER"], 56 "rss_teasers": self.site.config["RSS_TEASERS"], 57 "hide_untranslated_posts": self.site.config['HIDE_UNTRANSLATED_POSTS'], 58 "feed_length": self.site.config['FEED_LENGTH'], 59 } 60 self.site.scan_posts() 61 yield self.group_task() 62 for lang in kw["translations"]: 63 output_name = os.path.join(kw['output_folder'], 64 self.site.path("rss", None, lang)) 65 deps = [] 66 if kw["hide_untranslated_posts"]: 67 posts = [x for x in self.site.timeline if x.use_in_feeds 68 and x.is_translation_available(lang)][:10] 69 else: 70 posts = [x for x in self.site.timeline if x.use_in_feeds][:10] 71 for post in posts: 72 deps += post.deps(lang) 73 74 feed_url = urljoin(self.site.config['BASE_URL'], self.site.link("rss", None, lang).lstrip('/')) 75 yield { 76 'basename': 'generate_rss', 77 'name': os.path.normpath(output_name), 78 'file_dep': deps, 79 'targets': [output_name], 80 'actions': [(utils.generic_rss_renderer, 81 (lang, kw["blog_title"], kw["site_url"], 82 kw["blog_description"], posts, output_name, 83 kw["rss_teasers"], kw['feed_length'], feed_url))], 84 'task_dep': ['render_posts'], 85 'clean': True, 86 'uptodate': [utils.config_changed(kw)], 87 } 88 89 def rss_path(self, name, lang): 90 return [_f for _f in [self.site.config['TRANSLATIONS'][lang], 91 self.site.config['RSS_PATH'], 'rss.xml'] if _f] 92 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/nikola/plugins/task/rss.py b/nikola/plugins/task/rss.py --- a/nikola/plugins/task/rss.py +++ b/nikola/plugins/task/rss.py @@ -58,6 +58,11 @@ "feed_length": self.site.config['FEED_LENGTH'], } self.site.scan_posts() + # Check for any changes in the state of use_in_feeds for any post. + # Issue #934 + kw['use_in_feeds_status'] = ''.join( + ['T' if x.use_in_feeds else 'F' for x in self.site.timeline] + ) yield self.group_task() for lang in kw["translations"]: output_name = os.path.join(kw['output_folder'],
{"golden_diff": "diff --git a/nikola/plugins/task/rss.py b/nikola/plugins/task/rss.py\n--- a/nikola/plugins/task/rss.py\n+++ b/nikola/plugins/task/rss.py\n@@ -58,6 +58,11 @@\n \"feed_length\": self.site.config['FEED_LENGTH'],\n }\n self.site.scan_posts()\n+ # Check for any changes in the state of use_in_feeds for any post.\n+ # Issue #934\n+ kw['use_in_feeds_status'] = ''.join(\n+ ['T' if x.use_in_feeds else 'F' for x in self.site.timeline]\n+ )\n yield self.group_task()\n for lang in kw[\"translations\"]:\n output_name = os.path.join(kw['output_folder'],\n", "issue": "Drafts are leaked in feeds\nReported by @kayhayen in the mailing list. Proposed patch breaks tests, so checking things out a bit more carefully.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import unicode_literals, print_function\nimport os\ntry:\n from urlparse import urljoin\nexcept ImportError:\n from urllib.parse import urljoin # NOQA\n\nfrom nikola import utils\nfrom nikola.plugin_categories import Task\n\n\nclass GenerateRSS(Task):\n \"\"\"Generate RSS feeds.\"\"\"\n\n name = \"generate_rss\"\n\n def set_site(self, site):\n site.register_path_handler('rss', self.rss_path)\n return super(GenerateRSS, self).set_site(site)\n\n def gen_tasks(self):\n \"\"\"Generate RSS feeds.\"\"\"\n kw = {\n \"translations\": self.site.config[\"TRANSLATIONS\"],\n \"filters\": self.site.config[\"FILTERS\"],\n \"blog_title\": self.site.config[\"BLOG_TITLE\"],\n \"site_url\": self.site.config[\"SITE_URL\"],\n \"blog_description\": self.site.config[\"BLOG_DESCRIPTION\"],\n \"output_folder\": self.site.config[\"OUTPUT_FOLDER\"],\n \"rss_teasers\": self.site.config[\"RSS_TEASERS\"],\n \"hide_untranslated_posts\": self.site.config['HIDE_UNTRANSLATED_POSTS'],\n \"feed_length\": self.site.config['FEED_LENGTH'],\n }\n self.site.scan_posts()\n yield self.group_task()\n for lang in kw[\"translations\"]:\n output_name = os.path.join(kw['output_folder'],\n self.site.path(\"rss\", None, lang))\n deps = []\n if kw[\"hide_untranslated_posts\"]:\n posts = [x for x in self.site.timeline if x.use_in_feeds\n and x.is_translation_available(lang)][:10]\n else:\n posts = [x for x in self.site.timeline if x.use_in_feeds][:10]\n for post in posts:\n deps += post.deps(lang)\n\n feed_url = urljoin(self.site.config['BASE_URL'], self.site.link(\"rss\", None, lang).lstrip('/'))\n yield {\n 'basename': 'generate_rss',\n 'name': os.path.normpath(output_name),\n 'file_dep': deps,\n 'targets': [output_name],\n 'actions': [(utils.generic_rss_renderer,\n (lang, kw[\"blog_title\"], kw[\"site_url\"],\n kw[\"blog_description\"], posts, output_name,\n kw[\"rss_teasers\"], kw['feed_length'], feed_url))],\n 'task_dep': ['render_posts'],\n 'clean': True,\n 'uptodate': [utils.config_changed(kw)],\n }\n\n def rss_path(self, name, lang):\n return [_f for _f in [self.site.config['TRANSLATIONS'][lang],\n self.site.config['RSS_PATH'], 'rss.xml'] if _f]\n", "path": "nikola/plugins/task/rss.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright \u00a9 2012-2014 Roberto Alsina and others.\n\n# Permission is hereby granted, free of charge, to any\n# person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the\n# Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the\n# Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice\n# shall be included in all copies or substantial portions of\n# the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\n# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import unicode_literals, print_function\nimport os\ntry:\n from urlparse import urljoin\nexcept ImportError:\n from urllib.parse import urljoin # NOQA\n\nfrom nikola import utils\nfrom nikola.plugin_categories import Task\n\n\nclass GenerateRSS(Task):\n \"\"\"Generate RSS feeds.\"\"\"\n\n name = \"generate_rss\"\n\n def set_site(self, site):\n site.register_path_handler('rss', self.rss_path)\n return super(GenerateRSS, self).set_site(site)\n\n def gen_tasks(self):\n \"\"\"Generate RSS feeds.\"\"\"\n kw = {\n \"translations\": self.site.config[\"TRANSLATIONS\"],\n \"filters\": self.site.config[\"FILTERS\"],\n \"blog_title\": self.site.config[\"BLOG_TITLE\"],\n \"site_url\": self.site.config[\"SITE_URL\"],\n \"blog_description\": self.site.config[\"BLOG_DESCRIPTION\"],\n \"output_folder\": self.site.config[\"OUTPUT_FOLDER\"],\n \"rss_teasers\": self.site.config[\"RSS_TEASERS\"],\n \"hide_untranslated_posts\": self.site.config['HIDE_UNTRANSLATED_POSTS'],\n \"feed_length\": self.site.config['FEED_LENGTH'],\n }\n self.site.scan_posts()\n # Check for any changes in the state of use_in_feeds for any post.\n # Issue #934\n kw['use_in_feeds_status'] = ''.join(\n ['T' if x.use_in_feeds else 'F' for x in self.site.timeline]\n )\n yield self.group_task()\n for lang in kw[\"translations\"]:\n output_name = os.path.join(kw['output_folder'],\n self.site.path(\"rss\", None, lang))\n deps = []\n if kw[\"hide_untranslated_posts\"]:\n posts = [x for x in self.site.timeline if x.use_in_feeds\n and x.is_translation_available(lang)][:10]\n else:\n posts = [x for x in self.site.timeline if x.use_in_feeds][:10]\n for post in posts:\n deps += post.deps(lang)\n\n feed_url = urljoin(self.site.config['BASE_URL'], self.site.link(\"rss\", None, lang).lstrip('/'))\n yield {\n 'basename': 'generate_rss',\n 'name': os.path.normpath(output_name),\n 'file_dep': deps,\n 'targets': [output_name],\n 'actions': [(utils.generic_rss_renderer,\n (lang, kw[\"blog_title\"], kw[\"site_url\"],\n kw[\"blog_description\"], posts, output_name,\n kw[\"rss_teasers\"], kw['feed_length'], feed_url))],\n 'task_dep': ['render_posts'],\n 'clean': True,\n 'uptodate': [utils.config_changed(kw)],\n }\n\n def rss_path(self, name, lang):\n return [_f for _f in [self.site.config['TRANSLATIONS'][lang],\n self.site.config['RSS_PATH'], 'rss.xml'] if _f]\n", "path": "nikola/plugins/task/rss.py"}]}
1,295
168
gh_patches_debug_20570
rasdani/github-patches
git_diff
nvaccess__nvda-13213
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- nvda is not reading the result of the accounts in the windows calculator history ### Steps to reproduce: open windows calculator do at least two operations walk with tabe until nvda advertise list, list item walk with the arrows below and sign up and see that nvda advertises only list item. ### Actual behavior: nvda announces only list item ### Expected behavior: the nvda must announce the realized accounts as well as the result of the account. this is a regression, I remember using this feature a long time ago and everything worked fine. the regression can be from nvda or windows ### System configuration #### NVDA installed/portable/running from source: instaled #### NVDA version: nvda.exe, NVDA alpha-21386,53cecfd7 #### Windows version: windows 10 19042.630 #### Name and version of other software in use when reproducing the issue: Calculator.exe, Microsoft.WindowsCalculator 10.2009.4.0 #### Other information about your system: ### Other questions #### Does the issue still occur after restarting your computer? yes #### Have you tried any other versions of NVDA? If so, please report their behaviors. yes #### If addons are disabled, is your problem still occuring? yes #### Did you try to run the COM registry fixing tool in NVDA menu / tools? no --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `source/appModules/calculator.py` Content: ``` 1 # A part of NonVisual Desktop Access (NVDA) 2 # Copyright (C) 2020-2021 NV Access Limited, Joseph Lee 3 # This file is covered by the GNU General Public License. 4 # See the file COPYING for more details. 5 6 """App module for Windows 10 Calculator""" 7 8 import appModuleHandler 9 import api 10 from NVDAObjects.UIA import UIA 11 import queueHandler 12 import ui 13 import scriptHandler 14 import braille 15 16 # #9428: do not announce current values until calculations are done in order to avoid repetitions. 17 noCalculatorEntryAnnouncements = [ 18 # Display field with Calculator set to full screen mode. 19 "CalculatorResults", 20 # In the middle of a calculation expression entry. 21 "CalculatorExpression", 22 # Results display with Calculator set to compact overlay i.e. always on top mode. 23 "CalculatorAlwaysOnTopResults", 24 # Calculator expressions with Calculator set to always on top mode. 25 "ExpressionContainer", 26 # Date range selector. 27 "ContentPresenter", 28 # Briefly shown when closing date calculation calendar. 29 "Light Dismiss", 30 # Unit conversion/convert from. 31 "Value1", 32 # Unit conversion/converts into. 33 "Value2", 34 ] 35 36 37 class AppModule(appModuleHandler.AppModule): 38 39 _shouldAnnounceResult = False 40 # Name change says the same thing multiple times for some items. 41 _resultsCache = "" 42 43 def event_nameChange(self, obj, nextHandler): 44 if not isinstance(obj, UIA): 45 return 46 # No, announce value changes immediately except for calculator results and expressions. 47 if ( 48 obj.UIAAutomationId in noCalculatorEntryAnnouncements 49 or obj.UIAElement.cachedClassName == "LandmarkTarget" 50 ): 51 self._shouldAnnounceResult = False 52 # For the rest: 53 elif ( 54 obj.UIAAutomationId not in noCalculatorEntryAnnouncements 55 and obj.name != self._resultsCache 56 ): 57 # For unit conversion, both name change and notification events are fired, 58 # although UIA notification event presents much better messages. 59 # For date calculation, live region change event is also fired for difference between dates. 60 if obj.UIAAutomationId != "DateDiffAllUnitsResultLabel": 61 ui.message(obj.name) 62 self._resultsCache = obj.name 63 if not self._shouldAnnounceResult: 64 return 65 self._shouldAnnounceResult = False 66 nextHandler() 67 68 def event_UIA_notification(self, obj, nextHandler, displayString=None, activityId=None, **kwargs): 69 # #12268: for "DisplayUpdated", announce display strings in braille and move on. 70 if activityId == "DisplayUpdated": 71 braille.handler.message(displayString) 72 try: 73 shouldAnnounceNotification = ( 74 obj.previous.UIAAutomationId in 75 ("numberPad", "UnitConverterRootGrid") 76 ) 77 except AttributeError: 78 resultElement = api.getForegroundObject().children[1].lastChild 79 # Redesigned in 2019 due to introduction of "always on top" i.e. compact overlay mode. 80 if resultElement.UIAElement.cachedClassName != "LandmarkTarget": 81 resultElement = resultElement.parent.children[1] 82 shouldAnnounceNotification = ( 83 resultElement 84 and resultElement.firstChild 85 and resultElement.firstChild.UIAAutomationId not in noCalculatorEntryAnnouncements 86 ) 87 # Display updated activity ID seen when entering calculations should be ignored 88 # as as it is redundant if speak typed characters is on. 89 if shouldAnnounceNotification or activityId != "DisplayUpdated": 90 nextHandler() 91 92 # A list of native commands to handle calculator result announcement. 93 _calculatorResultGestures = ( 94 "kb:enter", 95 "kb:numpadEnter", 96 "kb:escape", 97 "kb:delete", 98 "kb:numpadDelete" 99 ) 100 101 @scriptHandler.script(gestures=_calculatorResultGestures) 102 def script_calculatorResult(self, gesture): 103 # To prevent double focus announcement, check where we are. 104 focus = api.getFocusObject() 105 gesture.send() 106 # In redstone, calculator result keeps firing name change, 107 # so tell it to do so if and only if enter has been pressed. 108 self._shouldAnnounceResult = True 109 # Hack: only announce display text when an actual calculator button (usually equals button) is pressed. 110 # In redstone, pressing enter does not move focus to equals button. 111 if isinstance(focus, UIA): 112 if focus.UIAAutomationId in ("CalculatorResults", "CalculatorAlwaysOnTopResults"): 113 queueHandler.queueFunction(queueHandler.eventQueue, ui.message, focus.name) 114 else: 115 resultsScreen = api.getForegroundObject().children[1].lastChild 116 if isinstance(resultsScreen, UIA) and resultsScreen.UIAElement.cachedClassName == "LandmarkTarget": 117 # And no, do not allow focus to move. 118 queueHandler.queueFunction(queueHandler.eventQueue, ui.message, resultsScreen.firstChild.name) 119 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/source/appModules/calculator.py b/source/appModules/calculator.py --- a/source/appModules/calculator.py +++ b/source/appModules/calculator.py @@ -1,5 +1,5 @@ # A part of NonVisual Desktop Access (NVDA) -# Copyright (C) 2020-2021 NV Access Limited, Joseph Lee +# Copyright (C) 2020-2022 NV Access Limited, Joseph Lee # This file is covered by the GNU General Public License. # See the file COPYING for more details. @@ -40,6 +40,15 @@ # Name change says the same thing multiple times for some items. _resultsCache = "" + def event_NVDAObject_init(self, obj): + if not isinstance(obj, UIA): + return + # #11858: version 10.2009 introduces a regression where history and memory items have no names + # but can be fetched through its children. + # Resolved in version 10.2109 which is exclusive to Windows 11. + if not obj.name and obj.parent.UIAAutomationId in ("HistoryListView", "MemoryListView"): + obj.name = "".join([item.name for item in obj.children]) + def event_nameChange(self, obj, nextHandler): if not isinstance(obj, UIA): return
{"golden_diff": "diff --git a/source/appModules/calculator.py b/source/appModules/calculator.py\n--- a/source/appModules/calculator.py\n+++ b/source/appModules/calculator.py\n@@ -1,5 +1,5 @@\n # A part of NonVisual Desktop Access (NVDA)\n-# Copyright (C) 2020-2021 NV Access Limited, Joseph Lee\n+# Copyright (C) 2020-2022 NV Access Limited, Joseph Lee\n # This file is covered by the GNU General Public License.\n # See the file COPYING for more details.\n \n@@ -40,6 +40,15 @@\n \t# Name change says the same thing multiple times for some items.\n \t_resultsCache = \"\"\n \n+\tdef event_NVDAObject_init(self, obj):\n+\t\tif not isinstance(obj, UIA):\n+\t\t\treturn\n+\t\t# #11858: version 10.2009 introduces a regression where history and memory items have no names\n+\t\t# but can be fetched through its children.\n+\t\t# Resolved in version 10.2109 which is exclusive to Windows 11.\n+\t\tif not obj.name and obj.parent.UIAAutomationId in (\"HistoryListView\", \"MemoryListView\"):\n+\t\t\tobj.name = \"\".join([item.name for item in obj.children])\n+\n \tdef event_nameChange(self, obj, nextHandler):\n \t\tif not isinstance(obj, UIA):\n \t\t\treturn\n", "issue": "nvda is not reading the result of the accounts in the windows calculator history\n\r\n### Steps to reproduce:\r\nopen windows calculator\r\ndo at least two operations\r\nwalk with tabe until nvda advertise\r\nlist, list item\r\nwalk with the arrows below and sign up and see that nvda advertises only list item.\r\n### Actual behavior:\r\nnvda announces only list item\r\n### Expected behavior:\r\n\r\nthe nvda must announce the realized accounts as well as the result of the account.\r\nthis is a regression, I remember using this feature a long time ago and everything worked fine.\r\nthe regression can be from nvda or windows\r\n### System configuration\r\n#### NVDA installed/portable/running from source:\r\ninstaled\r\n#### NVDA version:\r\nnvda.exe, NVDA alpha-21386,53cecfd7\r\n\r\n\r\n#### Windows version:\r\nwindows 10 19042.630\r\n#### Name and version of other software in use when reproducing the issue:\r\nCalculator.exe, Microsoft.WindowsCalculator 10.2009.4.0\r\n\r\n#### Other information about your system:\r\n\r\n### Other questions\r\n#### Does the issue still occur after restarting your computer?\r\nyes\r\n#### Have you tried any other versions of NVDA? If so, please report their behaviors.\r\nyes\r\n#### If addons are disabled, is your problem still occuring?\r\nyes\r\n#### Did you try to run the COM registry fixing tool in NVDA menu / tools?\r\nno\n", "before_files": [{"content": "# A part of NonVisual Desktop Access (NVDA)\n# Copyright (C) 2020-2021 NV Access Limited, Joseph Lee\n# This file is covered by the GNU General Public License.\n# See the file COPYING for more details.\n\n\"\"\"App module for Windows 10 Calculator\"\"\"\n\nimport appModuleHandler\nimport api\nfrom NVDAObjects.UIA import UIA\nimport queueHandler\nimport ui\nimport scriptHandler\nimport braille\n\n# #9428: do not announce current values until calculations are done in order to avoid repetitions.\nnoCalculatorEntryAnnouncements = [\n\t# Display field with Calculator set to full screen mode.\n\t\"CalculatorResults\",\n\t# In the middle of a calculation expression entry.\n\t\"CalculatorExpression\",\n\t# Results display with Calculator set to compact overlay i.e. always on top mode.\n\t\"CalculatorAlwaysOnTopResults\",\n\t# Calculator expressions with Calculator set to always on top mode.\n\t\"ExpressionContainer\",\n\t# Date range selector.\n\t\"ContentPresenter\",\n\t# Briefly shown when closing date calculation calendar.\n\t\"Light Dismiss\",\n\t# Unit conversion/convert from.\n\t\"Value1\",\n\t# Unit conversion/converts into.\n\t\"Value2\",\n]\n\n\nclass AppModule(appModuleHandler.AppModule):\n\n\t_shouldAnnounceResult = False\n\t# Name change says the same thing multiple times for some items.\n\t_resultsCache = \"\"\n\n\tdef event_nameChange(self, obj, nextHandler):\n\t\tif not isinstance(obj, UIA):\n\t\t\treturn\n\t\t# No, announce value changes immediately except for calculator results and expressions.\n\t\tif (\n\t\t\tobj.UIAAutomationId in noCalculatorEntryAnnouncements\n\t\t\tor obj.UIAElement.cachedClassName == \"LandmarkTarget\"\n\t\t):\n\t\t\tself._shouldAnnounceResult = False\n\t\t# For the rest:\n\t\telif (\n\t\t\tobj.UIAAutomationId not in noCalculatorEntryAnnouncements\n\t\t\tand obj.name != self._resultsCache\n\t\t):\n\t\t\t# For unit conversion, both name change and notification events are fired,\n\t\t\t# although UIA notification event presents much better messages.\n\t\t\t# For date calculation, live region change event is also fired for difference between dates.\n\t\t\tif obj.UIAAutomationId != \"DateDiffAllUnitsResultLabel\":\n\t\t\t\tui.message(obj.name)\n\t\t\tself._resultsCache = obj.name\n\t\tif not self._shouldAnnounceResult:\n\t\t\treturn\n\t\tself._shouldAnnounceResult = False\n\t\tnextHandler()\n\n\tdef event_UIA_notification(self, obj, nextHandler, displayString=None, activityId=None, **kwargs):\n\t\t# #12268: for \"DisplayUpdated\", announce display strings in braille and move on.\n\t\tif activityId == \"DisplayUpdated\":\n\t\t\tbraille.handler.message(displayString)\n\t\ttry:\n\t\t\tshouldAnnounceNotification = (\n\t\t\t\tobj.previous.UIAAutomationId in\n\t\t\t\t(\"numberPad\", \"UnitConverterRootGrid\")\n\t\t\t)\n\t\texcept AttributeError:\n\t\t\tresultElement = api.getForegroundObject().children[1].lastChild\n\t\t\t# Redesigned in 2019 due to introduction of \"always on top\" i.e. compact overlay mode.\n\t\t\tif resultElement.UIAElement.cachedClassName != \"LandmarkTarget\":\n\t\t\t\tresultElement = resultElement.parent.children[1]\n\t\t\tshouldAnnounceNotification = (\n\t\t\t\tresultElement\n\t\t\t\tand resultElement.firstChild\n\t\t\t\tand resultElement.firstChild.UIAAutomationId not in noCalculatorEntryAnnouncements\n\t\t\t)\n\t\t# Display updated activity ID seen when entering calculations should be ignored\n\t\t# as as it is redundant if speak typed characters is on.\n\t\tif shouldAnnounceNotification or activityId != \"DisplayUpdated\":\n\t\t\tnextHandler()\n\n\t# A list of native commands to handle calculator result announcement.\n\t_calculatorResultGestures = (\n\t\t\"kb:enter\",\n\t\t\"kb:numpadEnter\",\n\t\t\"kb:escape\",\n\t\t\"kb:delete\",\n\t\t\"kb:numpadDelete\"\n\t)\n\n\[email protected](gestures=_calculatorResultGestures)\n\tdef script_calculatorResult(self, gesture):\n\t\t# To prevent double focus announcement, check where we are.\n\t\tfocus = api.getFocusObject()\n\t\tgesture.send()\n\t\t# In redstone, calculator result keeps firing name change,\n\t\t# so tell it to do so if and only if enter has been pressed.\n\t\tself._shouldAnnounceResult = True\n\t\t# Hack: only announce display text when an actual calculator button (usually equals button) is pressed.\n\t\t# In redstone, pressing enter does not move focus to equals button.\n\t\tif isinstance(focus, UIA):\n\t\t\tif focus.UIAAutomationId in (\"CalculatorResults\", \"CalculatorAlwaysOnTopResults\"):\n\t\t\t\tqueueHandler.queueFunction(queueHandler.eventQueue, ui.message, focus.name)\n\t\t\telse:\n\t\t\t\tresultsScreen = api.getForegroundObject().children[1].lastChild\n\t\t\t\tif isinstance(resultsScreen, UIA) and resultsScreen.UIAElement.cachedClassName == \"LandmarkTarget\":\n\t\t\t\t\t# And no, do not allow focus to move.\n\t\t\t\t\tqueueHandler.queueFunction(queueHandler.eventQueue, ui.message, resultsScreen.firstChild.name)\n", "path": "source/appModules/calculator.py"}], "after_files": [{"content": "# A part of NonVisual Desktop Access (NVDA)\n# Copyright (C) 2020-2022 NV Access Limited, Joseph Lee\n# This file is covered by the GNU General Public License.\n# See the file COPYING for more details.\n\n\"\"\"App module for Windows 10 Calculator\"\"\"\n\nimport appModuleHandler\nimport api\nfrom NVDAObjects.UIA import UIA\nimport queueHandler\nimport ui\nimport scriptHandler\nimport braille\n\n# #9428: do not announce current values until calculations are done in order to avoid repetitions.\nnoCalculatorEntryAnnouncements = [\n\t# Display field with Calculator set to full screen mode.\n\t\"CalculatorResults\",\n\t# In the middle of a calculation expression entry.\n\t\"CalculatorExpression\",\n\t# Results display with Calculator set to compact overlay i.e. always on top mode.\n\t\"CalculatorAlwaysOnTopResults\",\n\t# Calculator expressions with Calculator set to always on top mode.\n\t\"ExpressionContainer\",\n\t# Date range selector.\n\t\"ContentPresenter\",\n\t# Briefly shown when closing date calculation calendar.\n\t\"Light Dismiss\",\n\t# Unit conversion/convert from.\n\t\"Value1\",\n\t# Unit conversion/converts into.\n\t\"Value2\",\n]\n\n\nclass AppModule(appModuleHandler.AppModule):\n\n\t_shouldAnnounceResult = False\n\t# Name change says the same thing multiple times for some items.\n\t_resultsCache = \"\"\n\n\tdef event_NVDAObject_init(self, obj):\n\t\tif not isinstance(obj, UIA):\n\t\t\treturn\n\t\t# #11858: version 10.2009 introduces a regression where history and memory items have no names\n\t\t# but can be fetched through its children.\n\t\t# Resolved in version 10.2109 which is exclusive to Windows 11.\n\t\tif not obj.name and obj.parent.UIAAutomationId in (\"HistoryListView\", \"MemoryListView\"):\n\t\t\tobj.name = \"\".join([item.name for item in obj.children])\n\n\tdef event_nameChange(self, obj, nextHandler):\n\t\tif not isinstance(obj, UIA):\n\t\t\treturn\n\t\t# No, announce value changes immediately except for calculator results and expressions.\n\t\tif (\n\t\t\tobj.UIAAutomationId in noCalculatorEntryAnnouncements\n\t\t\tor obj.UIAElement.cachedClassName == \"LandmarkTarget\"\n\t\t):\n\t\t\tself._shouldAnnounceResult = False\n\t\t# For the rest:\n\t\telif (\n\t\t\tobj.UIAAutomationId not in noCalculatorEntryAnnouncements\n\t\t\tand obj.name != self._resultsCache\n\t\t):\n\t\t\t# For unit conversion, both name change and notification events are fired,\n\t\t\t# although UIA notification event presents much better messages.\n\t\t\t# For date calculation, live region change event is also fired for difference between dates.\n\t\t\tif obj.UIAAutomationId != \"DateDiffAllUnitsResultLabel\":\n\t\t\t\tui.message(obj.name)\n\t\t\tself._resultsCache = obj.name\n\t\tif not self._shouldAnnounceResult:\n\t\t\treturn\n\t\tself._shouldAnnounceResult = False\n\t\tnextHandler()\n\n\tdef event_UIA_notification(self, obj, nextHandler, displayString=None, activityId=None, **kwargs):\n\t\t# #12268: for \"DisplayUpdated\", announce display strings in braille and move on.\n\t\tif activityId == \"DisplayUpdated\":\n\t\t\tbraille.handler.message(displayString)\n\t\ttry:\n\t\t\tshouldAnnounceNotification = (\n\t\t\t\tobj.previous.UIAAutomationId in\n\t\t\t\t(\"numberPad\", \"UnitConverterRootGrid\")\n\t\t\t)\n\t\texcept AttributeError:\n\t\t\tresultElement = api.getForegroundObject().children[1].lastChild\n\t\t\t# Redesigned in 2019 due to introduction of \"always on top\" i.e. compact overlay mode.\n\t\t\tif resultElement.UIAElement.cachedClassName != \"LandmarkTarget\":\n\t\t\t\tresultElement = resultElement.parent.children[1]\n\t\t\tshouldAnnounceNotification = (\n\t\t\t\tresultElement\n\t\t\t\tand resultElement.firstChild\n\t\t\t\tand resultElement.firstChild.UIAAutomationId not in noCalculatorEntryAnnouncements\n\t\t\t)\n\t\t# Display updated activity ID seen when entering calculations should be ignored\n\t\t# as as it is redundant if speak typed characters is on.\n\t\tif shouldAnnounceNotification or activityId != \"DisplayUpdated\":\n\t\t\tnextHandler()\n\n\t# A list of native commands to handle calculator result announcement.\n\t_calculatorResultGestures = (\n\t\t\"kb:enter\",\n\t\t\"kb:numpadEnter\",\n\t\t\"kb:escape\",\n\t\t\"kb:delete\",\n\t\t\"kb:numpadDelete\"\n\t)\n\n\[email protected](gestures=_calculatorResultGestures)\n\tdef script_calculatorResult(self, gesture):\n\t\t# To prevent double focus announcement, check where we are.\n\t\tfocus = api.getFocusObject()\n\t\tgesture.send()\n\t\t# In redstone, calculator result keeps firing name change,\n\t\t# so tell it to do so if and only if enter has been pressed.\n\t\tself._shouldAnnounceResult = True\n\t\t# Hack: only announce display text when an actual calculator button (usually equals button) is pressed.\n\t\t# In redstone, pressing enter does not move focus to equals button.\n\t\tif isinstance(focus, UIA):\n\t\t\tif focus.UIAAutomationId in (\"CalculatorResults\", \"CalculatorAlwaysOnTopResults\"):\n\t\t\t\tqueueHandler.queueFunction(queueHandler.eventQueue, ui.message, focus.name)\n\t\t\telse:\n\t\t\t\tresultsScreen = api.getForegroundObject().children[1].lastChild\n\t\t\t\tif isinstance(resultsScreen, UIA) and resultsScreen.UIAElement.cachedClassName == \"LandmarkTarget\":\n\t\t\t\t\t# And no, do not allow focus to move.\n\t\t\t\t\tqueueHandler.queueFunction(queueHandler.eventQueue, ui.message, resultsScreen.firstChild.name)\n", "path": "source/appModules/calculator.py"}]}
1,943
317
gh_patches_debug_21516
rasdani/github-patches
git_diff
python-telegram-bot__python-telegram-bot-3514
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Don't allow more than 2 dimensional input for `Inline/ReplyKeyboardMarkup` ### What kind of feature are you missing? Where do you notice a shortcoming of PTB? When a user passes their list to `Inline/ReplyKeyboardMarkup`, we currently check if their input is valid (exactly 2 dimensional input is valid), i.e. * the input is a sequence, not just a single button * it's not just a simple sequence (sequence of buttons) However it doesn't check if it's more than 2D, i.e. `[[[KeyboardButton(...)], [...], ]]` is invalid. ### Describe the solution you'd like Modify `tg._utils.markup.check_keyboard_type` to return `False` if we find another sequence. ### Describe alternatives you've considered _No response_ ### Additional context _No response_ --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `telegram/_utils/markup.py` Content: ``` 1 #!/usr/bin/env python 2 # 3 # A library that provides a Python interface to the Telegram Bot API 4 # Copyright (C) 2015-2023 5 # Leandro Toledo de Souza <[email protected]> 6 # 7 # This program is free software: you can redistribute it and/or modify 8 # it under the terms of the GNU Lesser Public License as published by 9 # the Free Software Foundation, either version 3 of the License, or 10 # (at your option) any later version. 11 # 12 # This program is distributed in the hope that it will be useful, 13 # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 # GNU Lesser Public License for more details. 16 # 17 # You should have received a copy of the GNU Lesser Public License 18 # along with this program. If not, see [http://www.gnu.org/licenses/]. 19 """This module contains a helper function for Telegram's ReplyMarkups 20 21 .. versionchanged:: 20.0 22 Previously, the contents of this module were available through the (no longer existing) 23 class ``telegram.ReplyMarkup``. 24 25 Warning: 26 Contents of this module are intended to be used internally by the library and *not* by the 27 user. Changes to this module are not considered breaking changes and may not be documented in 28 the changelog. 29 """ 30 from collections.abc import Sequence 31 32 33 def check_keyboard_type(keyboard: object) -> bool: 34 """Checks if the keyboard provided is of the correct type - A list of lists. 35 Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup` 36 """ 37 # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button 38 # would contain a single character. But that use case should be discouraged and we don't 39 # allow it here. 40 if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)): 41 return False 42 for row in keyboard: 43 if not isinstance(row, Sequence) or isinstance(row, (str, bytes)): 44 return False 45 return True 46 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/telegram/_utils/markup.py b/telegram/_utils/markup.py --- a/telegram/_utils/markup.py +++ b/telegram/_utils/markup.py @@ -31,7 +31,7 @@ def check_keyboard_type(keyboard: object) -> bool: - """Checks if the keyboard provided is of the correct type - A list of lists. + """Checks if the keyboard provided is of the correct type - A sequence of sequences. Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup` """ # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button @@ -39,7 +39,11 @@ # allow it here. if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)): return False + for row in keyboard: if not isinstance(row, Sequence) or isinstance(row, (str, bytes)): return False + for inner in row: + if isinstance(inner, Sequence) and not isinstance(inner, str): + return False return True
{"golden_diff": "diff --git a/telegram/_utils/markup.py b/telegram/_utils/markup.py\n--- a/telegram/_utils/markup.py\n+++ b/telegram/_utils/markup.py\n@@ -31,7 +31,7 @@\n \n \n def check_keyboard_type(keyboard: object) -> bool:\n- \"\"\"Checks if the keyboard provided is of the correct type - A list of lists.\n+ \"\"\"Checks if the keyboard provided is of the correct type - A sequence of sequences.\n Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup`\n \"\"\"\n # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button\n@@ -39,7 +39,11 @@\n # allow it here.\n if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)):\n return False\n+\n for row in keyboard:\n if not isinstance(row, Sequence) or isinstance(row, (str, bytes)):\n return False\n+ for inner in row:\n+ if isinstance(inner, Sequence) and not isinstance(inner, str):\n+ return False\n return True\n", "issue": "Don't allow more than 2 dimensional input for `Inline/ReplyKeyboardMarkup`\n### What kind of feature are you missing? Where do you notice a shortcoming of PTB?\n\nWhen a user passes their list to `Inline/ReplyKeyboardMarkup`, we currently check if their input is valid (exactly 2 dimensional input is valid), i.e. \r\n\r\n* the input is a sequence, not just a single button\r\n* it's not just a simple sequence (sequence of buttons)\r\n\r\nHowever it doesn't check if it's more than 2D, i.e. `[[[KeyboardButton(...)], [...], ]]` is invalid.\n\n### Describe the solution you'd like\n\nModify `tg._utils.markup.check_keyboard_type` to return `False` if we find another sequence.\n\n### Describe alternatives you've considered\n\n_No response_\n\n### Additional context\n\n_No response_\n", "before_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2023\n# Leandro Toledo de Souza <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains a helper function for Telegram's ReplyMarkups\n\n.. versionchanged:: 20.0\n Previously, the contents of this module were available through the (no longer existing)\n class ``telegram.ReplyMarkup``.\n\nWarning:\n Contents of this module are intended to be used internally by the library and *not* by the\n user. Changes to this module are not considered breaking changes and may not be documented in\n the changelog.\n\"\"\"\nfrom collections.abc import Sequence\n\n\ndef check_keyboard_type(keyboard: object) -> bool:\n \"\"\"Checks if the keyboard provided is of the correct type - A list of lists.\n Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup`\n \"\"\"\n # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button\n # would contain a single character. But that use case should be discouraged and we don't\n # allow it here.\n if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)):\n return False\n for row in keyboard:\n if not isinstance(row, Sequence) or isinstance(row, (str, bytes)):\n return False\n return True\n", "path": "telegram/_utils/markup.py"}], "after_files": [{"content": "#!/usr/bin/env python\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2023\n# Leandro Toledo de Souza <[email protected]>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program. If not, see [http://www.gnu.org/licenses/].\n\"\"\"This module contains a helper function for Telegram's ReplyMarkups\n\n.. versionchanged:: 20.0\n Previously, the contents of this module were available through the (no longer existing)\n class ``telegram.ReplyMarkup``.\n\nWarning:\n Contents of this module are intended to be used internally by the library and *not* by the\n user. Changes to this module are not considered breaking changes and may not be documented in\n the changelog.\n\"\"\"\nfrom collections.abc import Sequence\n\n\ndef check_keyboard_type(keyboard: object) -> bool:\n \"\"\"Checks if the keyboard provided is of the correct type - A sequence of sequences.\n Implicitly tested in the init-tests of `{Inline, Reply}KeyboardMarkup`\n \"\"\"\n # string and bytes may actually be used for ReplyKeyboardMarkup in which case each button\n # would contain a single character. But that use case should be discouraged and we don't\n # allow it here.\n if not isinstance(keyboard, Sequence) or isinstance(keyboard, (str, bytes)):\n return False\n\n for row in keyboard:\n if not isinstance(row, Sequence) or isinstance(row, (str, bytes)):\n return False\n for inner in row:\n if isinstance(inner, Sequence) and not isinstance(inner, str):\n return False\n return True\n", "path": "telegram/_utils/markup.py"}]}
973
242
gh_patches_debug_6602
rasdani/github-patches
git_diff
encode__starlette-1410
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- ETag checksum fails on FIPS-enabled systems when using MD5 ### Checklist <!-- Please make sure you check all these items before submitting your bug report. --> - [x] The bug is reproducible against the latest release and/or `master`. - [x] There are no similar issues or pull requests to fix it yet. ### Describe the bug The ETag checksum fails when using MD5. This is causing Starlette to not work at all under Red Hat Enterprise Linux when FIPS mode is enabled. ### Debugging material Here's the exception that's thrown: ``` INFO: 10.42.1.7:34422 - "GET /app/static/foo.html HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 373, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__ await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__ await self.middleware_stack(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__ raise exc File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__ raise exc File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__ await self.app(scope, receive, sender) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 656, in __call__ await route.handle(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 408, in handle await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py", line 97, in __call__ response = await self.get_response(path, scope) File "/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py", line 118, in get_response return self.file_response(full_path, stat_result, scope) File "/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py", line 173, in file_response response = FileResponse( File "/usr/local/lib/python3.8/site-packages/starlette/responses.py", line 267, in __init__ self.set_stat_headers(stat_result) File "/usr/local/lib/python3.8/site-packages/starlette/responses.py", line 273, in set_stat_headers etag = hashlib.md5(etag_base.encode()).hexdigest() ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS ``` ### Environment - OS: Red Hat Enterprise Linux 8 in FIPS mode - Python version: 3.8.8 - Starlette version: 0.16.0 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `starlette/_compat.py` Content: ``` 1 import hashlib 2 3 # Compat wrapper to always include the `usedforsecurity=...` parameter, 4 # which is only added from Python 3.9 onwards. 5 # We use this flag to indicate that we use `md5` hashes only for non-security 6 # cases (our ETag checksums). 7 # If we don't indicate that we're using MD5 for non-security related reasons, 8 # then attempting to use this function will raise an error when used 9 # environments which enable a strict "FIPs mode". 10 # 11 # See issue: https://github.com/encode/starlette/issues/1365 12 try: 13 14 hashlib.md5(b"data", usedforsecurity=True) # type: ignore[call-arg] 15 16 def md5_hexdigest( 17 data: bytes, *, usedforsecurity: bool = True 18 ) -> str: # pragma: no cover 19 return hashlib.md5( # type: ignore[call-arg] 20 data, usedforsecurity=usedforsecurity 21 ).hexdigest() 22 23 except TypeError: # pragma: no cover 24 25 def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str: 26 return hashlib.md5(data).hexdigest() 27 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/starlette/_compat.py b/starlette/_compat.py --- a/starlette/_compat.py +++ b/starlette/_compat.py @@ -11,7 +11,10 @@ # See issue: https://github.com/encode/starlette/issues/1365 try: - hashlib.md5(b"data", usedforsecurity=True) # type: ignore[call-arg] + # check if the Python version supports the parameter + # using usedforsecurity=False to avoid an exception on FIPS systems + # that reject usedforsecurity=True + hashlib.md5(b"data", usedforsecurity=False) # type: ignore[call-arg] def md5_hexdigest( data: bytes, *, usedforsecurity: bool = True
{"golden_diff": "diff --git a/starlette/_compat.py b/starlette/_compat.py\n--- a/starlette/_compat.py\n+++ b/starlette/_compat.py\n@@ -11,7 +11,10 @@\n # See issue: https://github.com/encode/starlette/issues/1365\n try:\n \n- hashlib.md5(b\"data\", usedforsecurity=True) # type: ignore[call-arg]\n+ # check if the Python version supports the parameter\n+ # using usedforsecurity=False to avoid an exception on FIPS systems\n+ # that reject usedforsecurity=True\n+ hashlib.md5(b\"data\", usedforsecurity=False) # type: ignore[call-arg]\n \n def md5_hexdigest(\n data: bytes, *, usedforsecurity: bool = True\n", "issue": "ETag checksum fails on FIPS-enabled systems when using MD5\n### Checklist\r\n\r\n<!-- Please make sure you check all these items before submitting your bug report. -->\r\n\r\n- [x] The bug is reproducible against the latest release and/or `master`.\r\n- [x] There are no similar issues or pull requests to fix it yet.\r\n\r\n### Describe the bug\r\n\r\nThe ETag checksum fails when using MD5. This is causing Starlette to not work at all under Red Hat Enterprise Linux when FIPS mode is enabled.\r\n\r\n### Debugging material\r\n\r\nHere's the exception that's thrown:\r\n\r\n```\r\nINFO: 10.42.1.7:34422 - \"GET /app/static/foo.html HTTP/1.1\" 500 Internal Server Error\r\nERROR: Exception in ASGI application\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py\", line 373, in run_asgi\r\n result = await app(self.scope, self.receive, self.send)\r\n File \"/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py\", line 75, in __call__\r\n return await self.app(scope, receive, send)\r\n File \"/usr/local/lib/python3.8/site-packages/fastapi/applications.py\", line 208, in __call__\r\n await super().__call__(scope, receive, send)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/applications.py\", line 112, in __call__\r\n await self.middleware_stack(scope, receive, send)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py\", line 181, in __call__\r\n raise exc\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py\", line 159, in __call__\r\n await self.app(scope, receive, _send)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/exceptions.py\", line 82, in __call__\r\n raise exc\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/exceptions.py\", line 71, in __call__\r\n await self.app(scope, receive, sender)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/routing.py\", line 656, in __call__\r\n await route.handle(scope, receive, send)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/routing.py\", line 408, in handle\r\n await self.app(scope, receive, send)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py\", line 97, in __call__\r\n response = await self.get_response(path, scope)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py\", line 118, in get_response\r\n return self.file_response(full_path, stat_result, scope)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/staticfiles.py\", line 173, in file_response\r\n response = FileResponse(\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/responses.py\", line 267, in __init__\r\n self.set_stat_headers(stat_result)\r\n File \"/usr/local/lib/python3.8/site-packages/starlette/responses.py\", line 273, in set_stat_headers\r\n etag = hashlib.md5(etag_base.encode()).hexdigest()\r\nValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS\r\n```\r\n\r\n### Environment\r\n\r\n- OS: Red Hat Enterprise Linux 8 in FIPS mode\r\n- Python version: 3.8.8\r\n- Starlette version: 0.16.0\r\n\r\n\n", "before_files": [{"content": "import hashlib\n\n# Compat wrapper to always include the `usedforsecurity=...` parameter,\n# which is only added from Python 3.9 onwards.\n# We use this flag to indicate that we use `md5` hashes only for non-security\n# cases (our ETag checksums).\n# If we don't indicate that we're using MD5 for non-security related reasons,\n# then attempting to use this function will raise an error when used\n# environments which enable a strict \"FIPs mode\".\n#\n# See issue: https://github.com/encode/starlette/issues/1365\ntry:\n\n hashlib.md5(b\"data\", usedforsecurity=True) # type: ignore[call-arg]\n\n def md5_hexdigest(\n data: bytes, *, usedforsecurity: bool = True\n ) -> str: # pragma: no cover\n return hashlib.md5( # type: ignore[call-arg]\n data, usedforsecurity=usedforsecurity\n ).hexdigest()\n\nexcept TypeError: # pragma: no cover\n\n def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str:\n return hashlib.md5(data).hexdigest()\n", "path": "starlette/_compat.py"}], "after_files": [{"content": "import hashlib\n\n# Compat wrapper to always include the `usedforsecurity=...` parameter,\n# which is only added from Python 3.9 onwards.\n# We use this flag to indicate that we use `md5` hashes only for non-security\n# cases (our ETag checksums).\n# If we don't indicate that we're using MD5 for non-security related reasons,\n# then attempting to use this function will raise an error when used\n# environments which enable a strict \"FIPs mode\".\n#\n# See issue: https://github.com/encode/starlette/issues/1365\ntry:\n\n # check if the Python version supports the parameter\n # using usedforsecurity=False to avoid an exception on FIPS systems\n # that reject usedforsecurity=True\n hashlib.md5(b\"data\", usedforsecurity=False) # type: ignore[call-arg]\n\n def md5_hexdigest(\n data: bytes, *, usedforsecurity: bool = True\n ) -> str: # pragma: no cover\n return hashlib.md5( # type: ignore[call-arg]\n data, usedforsecurity=usedforsecurity\n ).hexdigest()\n\nexcept TypeError: # pragma: no cover\n\n def md5_hexdigest(data: bytes, *, usedforsecurity: bool = True) -> str:\n return hashlib.md5(data).hexdigest()\n", "path": "starlette/_compat.py"}]}
1,385
174
gh_patches_debug_43922
rasdani/github-patches
git_diff
certbot__certbot-5329
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Install Python3 via EPEL on CentOS6 with letsencrypt-auto? CentOS 6 ships with Python 2.6 by default, which isn't 100% stably supported by letsencrypt, and which the Python community at large is trying to drop support for. But there's good news! CentOS has support for Software Collections which make it possible to install Python 2.7 in parallel: https://www.softwarecollections.org/en/scls/rhscl/python27/ Would it make sense for `letsencrypt-auto` to just install a Python 2.7, in addition to all the other packages it provides, in order to a) ensure users always get a fully functional environment, b) help encourage folks to move to Python 2.7 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `letsencrypt-auto-source/pieces/fetch.py` Content: ``` 1 """Do downloading and JSON parsing without additional dependencies. :: 2 3 # Print latest released version of LE to stdout: 4 python fetch.py --latest-version 5 6 # Download letsencrypt-auto script from git tag v1.2.3 into the folder I'm 7 # in, and make sure its signature verifies: 8 python fetch.py --le-auto-script v1.2.3 9 10 On failure, return non-zero. 11 12 """ 13 14 from __future__ import print_function 15 16 from distutils.version import LooseVersion 17 from json import loads 18 from os import devnull, environ 19 from os.path import dirname, join 20 import re 21 from subprocess import check_call, CalledProcessError 22 from sys import argv, exit 23 from urllib2 import build_opener, HTTPHandler, HTTPSHandler 24 from urllib2 import HTTPError, URLError 25 26 PUBLIC_KEY = environ.get('LE_AUTO_PUBLIC_KEY', """-----BEGIN PUBLIC KEY----- 27 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6MR8W/galdxnpGqBsYbq 28 OzQb2eyW15YFjDDEMI0ZOzt8f504obNs920lDnpPD2/KqgsfjOgw2K7xWDJIj/18 29 xUvWPk3LDkrnokNiRkA3KOx3W6fHycKL+zID7zy+xZYBuh2fLyQtWV1VGQ45iNRp 30 9+Zo7rH86cdfgkdnWTlNSHyTLW9NbXvyv/E12bppPcEvgCTAQXgnDVJ0/sqmeiij 31 n9tTFh03aM+R2V/21h8aTraAS24qiPCz6gkmYGC8yr6mglcnNoYbsLNYZ69zF1XH 32 cXPduCPdPdfLlzVlKK1/U7hkA28eG3BIAMh6uJYBRJTpiGgaGdPd7YekUB8S6cy+ 33 CQIDAQAB 34 -----END PUBLIC KEY----- 35 """) 36 37 class ExpectedError(Exception): 38 """A novice-readable exception that also carries the original exception for 39 debugging""" 40 41 42 class HttpsGetter(object): 43 def __init__(self): 44 """Build an HTTPS opener.""" 45 # Based on pip 1.4.1's URLOpener 46 # This verifies certs on only Python >=2.7.9. 47 self._opener = build_opener(HTTPSHandler()) 48 # Strip out HTTPHandler to prevent MITM spoof: 49 for handler in self._opener.handlers: 50 if isinstance(handler, HTTPHandler): 51 self._opener.handlers.remove(handler) 52 53 def get(self, url): 54 """Return the document contents pointed to by an HTTPS URL. 55 56 If something goes wrong (404, timeout, etc.), raise ExpectedError. 57 58 """ 59 try: 60 # socket module docs say default timeout is None: that is, no 61 # timeout 62 return self._opener.open(url, timeout=30).read() 63 except (HTTPError, IOError) as exc: 64 raise ExpectedError("Couldn't download %s." % url, exc) 65 66 67 def write(contents, dir, filename): 68 """Write something to a file in a certain directory.""" 69 with open(join(dir, filename), 'w') as file: 70 file.write(contents) 71 72 73 def latest_stable_version(get): 74 """Return the latest stable release of letsencrypt.""" 75 metadata = loads(get( 76 environ.get('LE_AUTO_JSON_URL', 77 'https://pypi.python.org/pypi/certbot/json'))) 78 # metadata['info']['version'] actually returns the latest of any kind of 79 # release release, contrary to https://wiki.python.org/moin/PyPIJSON. 80 # The regex is a sufficient regex for picking out prereleases for most 81 # packages, LE included. 82 return str(max(LooseVersion(r) for r 83 in metadata['releases'].iterkeys() 84 if re.match('^[0-9.]+$', r))) 85 86 87 def verified_new_le_auto(get, tag, temp_dir): 88 """Return the path to a verified, up-to-date letsencrypt-auto script. 89 90 If the download's signature does not verify or something else goes wrong 91 with the verification process, raise ExpectedError. 92 93 """ 94 le_auto_dir = environ.get( 95 'LE_AUTO_DIR_TEMPLATE', 96 'https://raw.githubusercontent.com/certbot/certbot/%s/' 97 'letsencrypt-auto-source/') % tag 98 write(get(le_auto_dir + 'letsencrypt-auto'), temp_dir, 'letsencrypt-auto') 99 write(get(le_auto_dir + 'letsencrypt-auto.sig'), temp_dir, 'letsencrypt-auto.sig') 100 write(PUBLIC_KEY, temp_dir, 'public_key.pem') 101 try: 102 with open(devnull, 'w') as dev_null: 103 check_call(['openssl', 'dgst', '-sha256', '-verify', 104 join(temp_dir, 'public_key.pem'), 105 '-signature', 106 join(temp_dir, 'letsencrypt-auto.sig'), 107 join(temp_dir, 'letsencrypt-auto')], 108 stdout=dev_null, 109 stderr=dev_null) 110 except CalledProcessError as exc: 111 raise ExpectedError("Couldn't verify signature of downloaded " 112 "certbot-auto.", exc) 113 114 115 def main(): 116 get = HttpsGetter().get 117 flag = argv[1] 118 try: 119 if flag == '--latest-version': 120 print(latest_stable_version(get)) 121 elif flag == '--le-auto-script': 122 tag = argv[2] 123 verified_new_le_auto(get, tag, dirname(argv[0])) 124 except ExpectedError as exc: 125 print(exc.args[0], exc.args[1]) 126 return 1 127 else: 128 return 0 129 130 131 if __name__ == '__main__': 132 exit(main()) 133 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/letsencrypt-auto-source/pieces/fetch.py b/letsencrypt-auto-source/pieces/fetch.py --- a/letsencrypt-auto-source/pieces/fetch.py +++ b/letsencrypt-auto-source/pieces/fetch.py @@ -11,17 +11,22 @@ """ -from __future__ import print_function +from __future__ import print_function, unicode_literals from distutils.version import LooseVersion from json import loads from os import devnull, environ from os.path import dirname, join import re +import ssl from subprocess import check_call, CalledProcessError from sys import argv, exit -from urllib2 import build_opener, HTTPHandler, HTTPSHandler -from urllib2 import HTTPError, URLError +try: + from urllib2 import build_opener, HTTPHandler, HTTPSHandler + from urllib2 import HTTPError, URLError +except ImportError: + from urllib.request import build_opener, HTTPHandler, HTTPSHandler + from urllib.error import HTTPError, URLError PUBLIC_KEY = environ.get('LE_AUTO_PUBLIC_KEY', """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6MR8W/galdxnpGqBsYbq @@ -43,8 +48,11 @@ def __init__(self): """Build an HTTPS opener.""" # Based on pip 1.4.1's URLOpener - # This verifies certs on only Python >=2.7.9. - self._opener = build_opener(HTTPSHandler()) + # This verifies certs on only Python >=2.7.9, and when NO_CERT_VERIFY isn't set. + if environ.get('NO_CERT_VERIFY') == '1' and hasattr(ssl, 'SSLContext'): + self._opener = build_opener(HTTPSHandler(context=create_CERT_NONE_context())) + else: + self._opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to prevent MITM spoof: for handler in self._opener.handlers: if isinstance(handler, HTTPHandler): @@ -66,7 +74,7 @@ def write(contents, dir, filename): """Write something to a file in a certain directory.""" - with open(join(dir, filename), 'w') as file: + with open(join(dir, filename), 'wb') as file: file.write(contents) @@ -74,13 +82,13 @@ """Return the latest stable release of letsencrypt.""" metadata = loads(get( environ.get('LE_AUTO_JSON_URL', - 'https://pypi.python.org/pypi/certbot/json'))) + 'https://pypi.python.org/pypi/certbot/json')).decode('UTF-8')) # metadata['info']['version'] actually returns the latest of any kind of # release release, contrary to https://wiki.python.org/moin/PyPIJSON. # The regex is a sufficient regex for picking out prereleases for most # packages, LE included. return str(max(LooseVersion(r) for r - in metadata['releases'].iterkeys() + in iter(metadata['releases'].keys()) if re.match('^[0-9.]+$', r))) @@ -97,7 +105,7 @@ 'letsencrypt-auto-source/') % tag write(get(le_auto_dir + 'letsencrypt-auto'), temp_dir, 'letsencrypt-auto') write(get(le_auto_dir + 'letsencrypt-auto.sig'), temp_dir, 'letsencrypt-auto.sig') - write(PUBLIC_KEY, temp_dir, 'public_key.pem') + write(PUBLIC_KEY.encode('UTF-8'), temp_dir, 'public_key.pem') try: with open(devnull, 'w') as dev_null: check_call(['openssl', 'dgst', '-sha256', '-verify', @@ -112,6 +120,14 @@ "certbot-auto.", exc) +def create_CERT_NONE_context(): + """Create a SSLContext object to not check hostname.""" + # PROTOCOL_TLS isn't available before 2.7.13 but this code is for 2.7.9+, so use this. + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.verify_mode = ssl.CERT_NONE + return context + + def main(): get = HttpsGetter().get flag = argv[1]
{"golden_diff": "diff --git a/letsencrypt-auto-source/pieces/fetch.py b/letsencrypt-auto-source/pieces/fetch.py\n--- a/letsencrypt-auto-source/pieces/fetch.py\n+++ b/letsencrypt-auto-source/pieces/fetch.py\n@@ -11,17 +11,22 @@\n \n \"\"\"\n \n-from __future__ import print_function\n+from __future__ import print_function, unicode_literals\n \n from distutils.version import LooseVersion\n from json import loads\n from os import devnull, environ\n from os.path import dirname, join\n import re\n+import ssl\n from subprocess import check_call, CalledProcessError\n from sys import argv, exit\n-from urllib2 import build_opener, HTTPHandler, HTTPSHandler\n-from urllib2 import HTTPError, URLError\n+try:\n+ from urllib2 import build_opener, HTTPHandler, HTTPSHandler\n+ from urllib2 import HTTPError, URLError\n+except ImportError:\n+ from urllib.request import build_opener, HTTPHandler, HTTPSHandler\n+ from urllib.error import HTTPError, URLError\n \n PUBLIC_KEY = environ.get('LE_AUTO_PUBLIC_KEY', \"\"\"-----BEGIN PUBLIC KEY-----\n MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6MR8W/galdxnpGqBsYbq\n@@ -43,8 +48,11 @@\n def __init__(self):\n \"\"\"Build an HTTPS opener.\"\"\"\n # Based on pip 1.4.1's URLOpener\n- # This verifies certs on only Python >=2.7.9.\n- self._opener = build_opener(HTTPSHandler())\n+ # This verifies certs on only Python >=2.7.9, and when NO_CERT_VERIFY isn't set.\n+ if environ.get('NO_CERT_VERIFY') == '1' and hasattr(ssl, 'SSLContext'):\n+ self._opener = build_opener(HTTPSHandler(context=create_CERT_NONE_context()))\n+ else:\n+ self._opener = build_opener(HTTPSHandler())\n # Strip out HTTPHandler to prevent MITM spoof:\n for handler in self._opener.handlers:\n if isinstance(handler, HTTPHandler):\n@@ -66,7 +74,7 @@\n \n def write(contents, dir, filename):\n \"\"\"Write something to a file in a certain directory.\"\"\"\n- with open(join(dir, filename), 'w') as file:\n+ with open(join(dir, filename), 'wb') as file:\n file.write(contents)\n \n \n@@ -74,13 +82,13 @@\n \"\"\"Return the latest stable release of letsencrypt.\"\"\"\n metadata = loads(get(\n environ.get('LE_AUTO_JSON_URL',\n- 'https://pypi.python.org/pypi/certbot/json')))\n+ 'https://pypi.python.org/pypi/certbot/json')).decode('UTF-8'))\n # metadata['info']['version'] actually returns the latest of any kind of\n # release release, contrary to https://wiki.python.org/moin/PyPIJSON.\n # The regex is a sufficient regex for picking out prereleases for most\n # packages, LE included.\n return str(max(LooseVersion(r) for r\n- in metadata['releases'].iterkeys()\n+ in iter(metadata['releases'].keys())\n if re.match('^[0-9.]+$', r)))\n \n \n@@ -97,7 +105,7 @@\n 'letsencrypt-auto-source/') % tag\n write(get(le_auto_dir + 'letsencrypt-auto'), temp_dir, 'letsencrypt-auto')\n write(get(le_auto_dir + 'letsencrypt-auto.sig'), temp_dir, 'letsencrypt-auto.sig')\n- write(PUBLIC_KEY, temp_dir, 'public_key.pem')\n+ write(PUBLIC_KEY.encode('UTF-8'), temp_dir, 'public_key.pem')\n try:\n with open(devnull, 'w') as dev_null:\n check_call(['openssl', 'dgst', '-sha256', '-verify',\n@@ -112,6 +120,14 @@\n \"certbot-auto.\", exc)\n \n \n+def create_CERT_NONE_context():\n+ \"\"\"Create a SSLContext object to not check hostname.\"\"\"\n+ # PROTOCOL_TLS isn't available before 2.7.13 but this code is for 2.7.9+, so use this.\n+ context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n+ context.verify_mode = ssl.CERT_NONE\n+ return context\n+\n+\n def main():\n get = HttpsGetter().get\n flag = argv[1]\n", "issue": "Install Python3 via EPEL on CentOS6 with letsencrypt-auto?\nCentOS 6 ships with Python 2.6 by default, which isn't 100% stably supported by letsencrypt, and which the Python community at large is trying to drop support for. But there's good news! CentOS has support for Software Collections which make it possible to install Python 2.7 in parallel: https://www.softwarecollections.org/en/scls/rhscl/python27/\n\nWould it make sense for `letsencrypt-auto` to just install a Python 2.7, in addition to all the other packages it provides, in order to a) ensure users always get a fully functional environment, b) help encourage folks to move to Python 2.7\n\n", "before_files": [{"content": "\"\"\"Do downloading and JSON parsing without additional dependencies. ::\n\n # Print latest released version of LE to stdout:\n python fetch.py --latest-version\n\n # Download letsencrypt-auto script from git tag v1.2.3 into the folder I'm\n # in, and make sure its signature verifies:\n python fetch.py --le-auto-script v1.2.3\n\nOn failure, return non-zero.\n\n\"\"\"\n\nfrom __future__ import print_function\n\nfrom distutils.version import LooseVersion\nfrom json import loads\nfrom os import devnull, environ\nfrom os.path import dirname, join\nimport re\nfrom subprocess import check_call, CalledProcessError\nfrom sys import argv, exit\nfrom urllib2 import build_opener, HTTPHandler, HTTPSHandler\nfrom urllib2 import HTTPError, URLError\n\nPUBLIC_KEY = environ.get('LE_AUTO_PUBLIC_KEY', \"\"\"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6MR8W/galdxnpGqBsYbq\nOzQb2eyW15YFjDDEMI0ZOzt8f504obNs920lDnpPD2/KqgsfjOgw2K7xWDJIj/18\nxUvWPk3LDkrnokNiRkA3KOx3W6fHycKL+zID7zy+xZYBuh2fLyQtWV1VGQ45iNRp\n9+Zo7rH86cdfgkdnWTlNSHyTLW9NbXvyv/E12bppPcEvgCTAQXgnDVJ0/sqmeiij\nn9tTFh03aM+R2V/21h8aTraAS24qiPCz6gkmYGC8yr6mglcnNoYbsLNYZ69zF1XH\ncXPduCPdPdfLlzVlKK1/U7hkA28eG3BIAMh6uJYBRJTpiGgaGdPd7YekUB8S6cy+\nCQIDAQAB\n-----END PUBLIC KEY-----\n\"\"\")\n\nclass ExpectedError(Exception):\n \"\"\"A novice-readable exception that also carries the original exception for\n debugging\"\"\"\n\n\nclass HttpsGetter(object):\n def __init__(self):\n \"\"\"Build an HTTPS opener.\"\"\"\n # Based on pip 1.4.1's URLOpener\n # This verifies certs on only Python >=2.7.9.\n self._opener = build_opener(HTTPSHandler())\n # Strip out HTTPHandler to prevent MITM spoof:\n for handler in self._opener.handlers:\n if isinstance(handler, HTTPHandler):\n self._opener.handlers.remove(handler)\n\n def get(self, url):\n \"\"\"Return the document contents pointed to by an HTTPS URL.\n\n If something goes wrong (404, timeout, etc.), raise ExpectedError.\n\n \"\"\"\n try:\n # socket module docs say default timeout is None: that is, no\n # timeout\n return self._opener.open(url, timeout=30).read()\n except (HTTPError, IOError) as exc:\n raise ExpectedError(\"Couldn't download %s.\" % url, exc)\n\n\ndef write(contents, dir, filename):\n \"\"\"Write something to a file in a certain directory.\"\"\"\n with open(join(dir, filename), 'w') as file:\n file.write(contents)\n\n\ndef latest_stable_version(get):\n \"\"\"Return the latest stable release of letsencrypt.\"\"\"\n metadata = loads(get(\n environ.get('LE_AUTO_JSON_URL',\n 'https://pypi.python.org/pypi/certbot/json')))\n # metadata['info']['version'] actually returns the latest of any kind of\n # release release, contrary to https://wiki.python.org/moin/PyPIJSON.\n # The regex is a sufficient regex for picking out prereleases for most\n # packages, LE included.\n return str(max(LooseVersion(r) for r\n in metadata['releases'].iterkeys()\n if re.match('^[0-9.]+$', r)))\n\n\ndef verified_new_le_auto(get, tag, temp_dir):\n \"\"\"Return the path to a verified, up-to-date letsencrypt-auto script.\n\n If the download's signature does not verify or something else goes wrong\n with the verification process, raise ExpectedError.\n\n \"\"\"\n le_auto_dir = environ.get(\n 'LE_AUTO_DIR_TEMPLATE',\n 'https://raw.githubusercontent.com/certbot/certbot/%s/'\n 'letsencrypt-auto-source/') % tag\n write(get(le_auto_dir + 'letsencrypt-auto'), temp_dir, 'letsencrypt-auto')\n write(get(le_auto_dir + 'letsencrypt-auto.sig'), temp_dir, 'letsencrypt-auto.sig')\n write(PUBLIC_KEY, temp_dir, 'public_key.pem')\n try:\n with open(devnull, 'w') as dev_null:\n check_call(['openssl', 'dgst', '-sha256', '-verify',\n join(temp_dir, 'public_key.pem'),\n '-signature',\n join(temp_dir, 'letsencrypt-auto.sig'),\n join(temp_dir, 'letsencrypt-auto')],\n stdout=dev_null,\n stderr=dev_null)\n except CalledProcessError as exc:\n raise ExpectedError(\"Couldn't verify signature of downloaded \"\n \"certbot-auto.\", exc)\n\n\ndef main():\n get = HttpsGetter().get\n flag = argv[1]\n try:\n if flag == '--latest-version':\n print(latest_stable_version(get))\n elif flag == '--le-auto-script':\n tag = argv[2]\n verified_new_le_auto(get, tag, dirname(argv[0]))\n except ExpectedError as exc:\n print(exc.args[0], exc.args[1])\n return 1\n else:\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n", "path": "letsencrypt-auto-source/pieces/fetch.py"}], "after_files": [{"content": "\"\"\"Do downloading and JSON parsing without additional dependencies. ::\n\n # Print latest released version of LE to stdout:\n python fetch.py --latest-version\n\n # Download letsencrypt-auto script from git tag v1.2.3 into the folder I'm\n # in, and make sure its signature verifies:\n python fetch.py --le-auto-script v1.2.3\n\nOn failure, return non-zero.\n\n\"\"\"\n\nfrom __future__ import print_function, unicode_literals\n\nfrom distutils.version import LooseVersion\nfrom json import loads\nfrom os import devnull, environ\nfrom os.path import dirname, join\nimport re\nimport ssl\nfrom subprocess import check_call, CalledProcessError\nfrom sys import argv, exit\ntry:\n from urllib2 import build_opener, HTTPHandler, HTTPSHandler\n from urllib2 import HTTPError, URLError\nexcept ImportError:\n from urllib.request import build_opener, HTTPHandler, HTTPSHandler\n from urllib.error import HTTPError, URLError\n\nPUBLIC_KEY = environ.get('LE_AUTO_PUBLIC_KEY', \"\"\"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6MR8W/galdxnpGqBsYbq\nOzQb2eyW15YFjDDEMI0ZOzt8f504obNs920lDnpPD2/KqgsfjOgw2K7xWDJIj/18\nxUvWPk3LDkrnokNiRkA3KOx3W6fHycKL+zID7zy+xZYBuh2fLyQtWV1VGQ45iNRp\n9+Zo7rH86cdfgkdnWTlNSHyTLW9NbXvyv/E12bppPcEvgCTAQXgnDVJ0/sqmeiij\nn9tTFh03aM+R2V/21h8aTraAS24qiPCz6gkmYGC8yr6mglcnNoYbsLNYZ69zF1XH\ncXPduCPdPdfLlzVlKK1/U7hkA28eG3BIAMh6uJYBRJTpiGgaGdPd7YekUB8S6cy+\nCQIDAQAB\n-----END PUBLIC KEY-----\n\"\"\")\n\nclass ExpectedError(Exception):\n \"\"\"A novice-readable exception that also carries the original exception for\n debugging\"\"\"\n\n\nclass HttpsGetter(object):\n def __init__(self):\n \"\"\"Build an HTTPS opener.\"\"\"\n # Based on pip 1.4.1's URLOpener\n # This verifies certs on only Python >=2.7.9, and when NO_CERT_VERIFY isn't set.\n if environ.get('NO_CERT_VERIFY') == '1' and hasattr(ssl, 'SSLContext'):\n self._opener = build_opener(HTTPSHandler(context=create_CERT_NONE_context()))\n else:\n self._opener = build_opener(HTTPSHandler())\n # Strip out HTTPHandler to prevent MITM spoof:\n for handler in self._opener.handlers:\n if isinstance(handler, HTTPHandler):\n self._opener.handlers.remove(handler)\n\n def get(self, url):\n \"\"\"Return the document contents pointed to by an HTTPS URL.\n\n If something goes wrong (404, timeout, etc.), raise ExpectedError.\n\n \"\"\"\n try:\n # socket module docs say default timeout is None: that is, no\n # timeout\n return self._opener.open(url, timeout=30).read()\n except (HTTPError, IOError) as exc:\n raise ExpectedError(\"Couldn't download %s.\" % url, exc)\n\n\ndef write(contents, dir, filename):\n \"\"\"Write something to a file in a certain directory.\"\"\"\n with open(join(dir, filename), 'wb') as file:\n file.write(contents)\n\n\ndef latest_stable_version(get):\n \"\"\"Return the latest stable release of letsencrypt.\"\"\"\n metadata = loads(get(\n environ.get('LE_AUTO_JSON_URL',\n 'https://pypi.python.org/pypi/certbot/json')).decode('UTF-8'))\n # metadata['info']['version'] actually returns the latest of any kind of\n # release release, contrary to https://wiki.python.org/moin/PyPIJSON.\n # The regex is a sufficient regex for picking out prereleases for most\n # packages, LE included.\n return str(max(LooseVersion(r) for r\n in iter(metadata['releases'].keys())\n if re.match('^[0-9.]+$', r)))\n\n\ndef verified_new_le_auto(get, tag, temp_dir):\n \"\"\"Return the path to a verified, up-to-date letsencrypt-auto script.\n\n If the download's signature does not verify or something else goes wrong\n with the verification process, raise ExpectedError.\n\n \"\"\"\n le_auto_dir = environ.get(\n 'LE_AUTO_DIR_TEMPLATE',\n 'https://raw.githubusercontent.com/certbot/certbot/%s/'\n 'letsencrypt-auto-source/') % tag\n write(get(le_auto_dir + 'letsencrypt-auto'), temp_dir, 'letsencrypt-auto')\n write(get(le_auto_dir + 'letsencrypt-auto.sig'), temp_dir, 'letsencrypt-auto.sig')\n write(PUBLIC_KEY.encode('UTF-8'), temp_dir, 'public_key.pem')\n try:\n with open(devnull, 'w') as dev_null:\n check_call(['openssl', 'dgst', '-sha256', '-verify',\n join(temp_dir, 'public_key.pem'),\n '-signature',\n join(temp_dir, 'letsencrypt-auto.sig'),\n join(temp_dir, 'letsencrypt-auto')],\n stdout=dev_null,\n stderr=dev_null)\n except CalledProcessError as exc:\n raise ExpectedError(\"Couldn't verify signature of downloaded \"\n \"certbot-auto.\", exc)\n\n\ndef create_CERT_NONE_context():\n \"\"\"Create a SSLContext object to not check hostname.\"\"\"\n # PROTOCOL_TLS isn't available before 2.7.13 but this code is for 2.7.9+, so use this.\n context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n context.verify_mode = ssl.CERT_NONE\n return context\n\n\ndef main():\n get = HttpsGetter().get\n flag = argv[1]\n try:\n if flag == '--latest-version':\n print(latest_stable_version(get))\n elif flag == '--le-auto-script':\n tag = argv[2]\n verified_new_le_auto(get, tag, dirname(argv[0]))\n except ExpectedError as exc:\n print(exc.args[0], exc.args[1])\n return 1\n else:\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n", "path": "letsencrypt-auto-source/pieces/fetch.py"}]}
2,008
999
gh_patches_debug_8956
rasdani/github-patches
git_diff
keras-team__keras-11147
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Sync naming convention and style in NLP datasets Also fixes a possible bug with np.load()/f.close() pair not being exception-safe. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `keras/datasets/boston_housing.py` Content: ``` 1 """Boston housing price regression dataset. 2 """ 3 from __future__ import absolute_import 4 from __future__ import division 5 from __future__ import print_function 6 7 from ..utils.data_utils import get_file 8 import numpy as np 9 10 11 def load_data(path='boston_housing.npz', test_split=0.2, seed=113): 12 """Loads the Boston Housing dataset. 13 14 # Arguments 15 path: path where to cache the dataset locally 16 (relative to ~/.keras/datasets). 17 test_split: fraction of the data to reserve as test set. 18 seed: Random seed for shuffling the data 19 before computing the test split. 20 21 # Returns 22 Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. 23 """ 24 assert 0 <= test_split < 1 25 path = get_file(path, 26 origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz', 27 file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5') 28 f = np.load(path) 29 x = f['x'] 30 y = f['y'] 31 f.close() 32 33 np.random.seed(seed) 34 indices = np.arange(len(x)) 35 np.random.shuffle(indices) 36 x = x[indices] 37 y = y[indices] 38 39 x_train = np.array(x[:int(len(x) * (1 - test_split))]) 40 y_train = np.array(y[:int(len(x) * (1 - test_split))]) 41 x_test = np.array(x[int(len(x) * (1 - test_split)):]) 42 y_test = np.array(y[int(len(x) * (1 - test_split)):]) 43 return (x_train, y_train), (x_test, y_test) 44 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/keras/datasets/boston_housing.py b/keras/datasets/boston_housing.py --- a/keras/datasets/boston_housing.py +++ b/keras/datasets/boston_housing.py @@ -25,10 +25,9 @@ path = get_file(path, origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz', file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5') - f = np.load(path) - x = f['x'] - y = f['y'] - f.close() + with np.load(path) as f: + x = f['x'] + y = f['y'] np.random.seed(seed) indices = np.arange(len(x))
{"golden_diff": "diff --git a/keras/datasets/boston_housing.py b/keras/datasets/boston_housing.py\n--- a/keras/datasets/boston_housing.py\n+++ b/keras/datasets/boston_housing.py\n@@ -25,10 +25,9 @@\n path = get_file(path,\n origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz',\n file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5')\n- f = np.load(path)\n- x = f['x']\n- y = f['y']\n- f.close()\n+ with np.load(path) as f:\n+ x = f['x']\n+ y = f['y']\n \n np.random.seed(seed)\n indices = np.arange(len(x))\n", "issue": "Sync naming convention and style in NLP datasets\nAlso fixes a possible bug with np.load()/f.close() pair not being exception-safe.\n", "before_files": [{"content": "\"\"\"Boston housing price regression dataset.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom ..utils.data_utils import get_file\nimport numpy as np\n\n\ndef load_data(path='boston_housing.npz', test_split=0.2, seed=113):\n \"\"\"Loads the Boston Housing dataset.\n\n # Arguments\n path: path where to cache the dataset locally\n (relative to ~/.keras/datasets).\n test_split: fraction of the data to reserve as test set.\n seed: Random seed for shuffling the data\n before computing the test split.\n\n # Returns\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n assert 0 <= test_split < 1\n path = get_file(path,\n origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz',\n file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5')\n f = np.load(path)\n x = f['x']\n y = f['y']\n f.close()\n\n np.random.seed(seed)\n indices = np.arange(len(x))\n np.random.shuffle(indices)\n x = x[indices]\n y = y[indices]\n\n x_train = np.array(x[:int(len(x) * (1 - test_split))])\n y_train = np.array(y[:int(len(x) * (1 - test_split))])\n x_test = np.array(x[int(len(x) * (1 - test_split)):])\n y_test = np.array(y[int(len(x) * (1 - test_split)):])\n return (x_train, y_train), (x_test, y_test)\n", "path": "keras/datasets/boston_housing.py"}], "after_files": [{"content": "\"\"\"Boston housing price regression dataset.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom ..utils.data_utils import get_file\nimport numpy as np\n\n\ndef load_data(path='boston_housing.npz', test_split=0.2, seed=113):\n \"\"\"Loads the Boston Housing dataset.\n\n # Arguments\n path: path where to cache the dataset locally\n (relative to ~/.keras/datasets).\n test_split: fraction of the data to reserve as test set.\n seed: Random seed for shuffling the data\n before computing the test split.\n\n # Returns\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n \"\"\"\n assert 0 <= test_split < 1\n path = get_file(path,\n origin='https://s3.amazonaws.com/keras-datasets/boston_housing.npz',\n file_hash='f553886a1f8d56431e820c5b82552d9d95cfcb96d1e678153f8839538947dff5')\n with np.load(path) as f:\n x = f['x']\n y = f['y']\n\n np.random.seed(seed)\n indices = np.arange(len(x))\n np.random.shuffle(indices)\n x = x[indices]\n y = y[indices]\n\n x_train = np.array(x[:int(len(x) * (1 - test_split))])\n y_train = np.array(y[:int(len(x) * (1 - test_split))])\n x_test = np.array(x[int(len(x) * (1 - test_split)):])\n y_test = np.array(y[int(len(x) * (1 - test_split)):])\n return (x_train, y_train), (x_test, y_test)\n", "path": "keras/datasets/boston_housing.py"}]}
797
228
gh_patches_debug_159
rasdani/github-patches
git_diff
uccser__cs-unplugged-54
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add Bootstrap 4 SCSS --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `csunplugged/config/settings.py` Content: ``` 1 """ 2 Django settings for csunplugged project. 3 4 Generated by 'django-admin startproject' using Django 1.10.3. 5 6 For more information on this file, see 7 https://docs.djangoproject.com/en/1.10/topics/settings/ 8 9 For the full list of settings and their values, see 10 https://docs.djangoproject.com/en/1.10/ref/settings/ 11 """ 12 13 import os 14 from config.settings_secret import * 15 16 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 17 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 19 # nasty hard coding 20 SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) 21 22 23 # Quick-start development settings - unsuitable for production 24 # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 25 26 # SECURITY WARNING: keep the secret key used in production secret! 27 SECRET_KEY = 'l@@)w&&%&u37+sjz^lsx^+29y_333oid3ygxzucar^8o(axo*f' 28 29 # SECURITY WARNING: don't run with debug turned on in production! 30 DEBUG = True 31 32 ALLOWED_HOSTS = [] 33 34 35 # Application definition 36 37 INSTALLED_APPS = [ 38 'general.apps.GeneralConfig', 39 'topics.apps.TopicsConfig', 40 'resources.apps.ResourcesConfig', 41 'django.contrib.admin', 42 'django.contrib.auth', 43 'django.contrib.contenttypes', 44 'django.contrib.sessions', 45 'django.contrib.messages', 46 'django.contrib.staticfiles', 47 ] 48 49 MIDDLEWARE = [ 50 'django.middleware.security.SecurityMiddleware', 51 'django.contrib.sessions.middleware.SessionMiddleware', 52 'django.middleware.locale.LocaleMiddleware', 53 'django.middleware.common.CommonMiddleware', 54 'django.middleware.csrf.CsrfViewMiddleware', 55 'django.contrib.auth.middleware.AuthenticationMiddleware', 56 'django.contrib.messages.middleware.MessageMiddleware', 57 'django.middleware.clickjacking.XFrameOptionsMiddleware', 58 ] 59 60 ROOT_URLCONF = 'config.urls' 61 62 TEMPLATES = [ 63 { 64 'BACKEND': 'django.template.backends.django.DjangoTemplates', 65 'DIRS': [ 66 os.path.join(SETTINGS_PATH, 'templates'), 67 os.path.join(SETTINGS_PATH, 'resources/content/') 68 ], 69 'APP_DIRS': True, 70 'OPTIONS': { 71 'context_processors': [ 72 'django.template.context_processors.debug', 73 'django.template.context_processors.request', 74 'django.contrib.auth.context_processors.auth', 75 'django.contrib.messages.context_processors.messages', 76 ], 77 }, 78 }, 79 ] 80 81 WSGI_APPLICATION = 'config.wsgi.application' 82 83 84 # Database 85 # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 86 # Database values are stored in `settings_secret.py` 87 # A template of this file is available as `settings_secret_template.py` 88 89 90 # Password validation 91 # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 92 93 AUTH_PASSWORD_VALIDATORS = [ 94 { 95 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 96 }, 97 { 98 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 99 }, 100 { 101 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 102 }, 103 { 104 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 105 }, 106 ] 107 108 109 # Internationalization 110 # https://docs.djangoproject.com/en/1.10/topics/i18n/ 111 112 LANGUAGE_CODE = 'en-us' 113 114 TIME_ZONE = 'UTC' 115 116 USE_I18N = True 117 118 USE_L10N = True 119 120 USE_TZ = True 121 122 LOCALE_PATHS = ['locale'] 123 124 # Static files (CSS, JavaScript, Images) 125 # https://docs.djangoproject.com/en/1.10/howto/static-files/ 126 127 STATIC_URL = '/static/' 128 STATICFILES_DIRS = ( 129 os.path.join(BASE_DIR, 'static'), 130 ) 131 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/csunplugged/config/settings.py b/csunplugged/config/settings.py --- a/csunplugged/config/settings.py +++ b/csunplugged/config/settings.py @@ -126,5 +126,5 @@ STATIC_URL = '/static/' STATICFILES_DIRS = ( - os.path.join(BASE_DIR, 'static'), + os.path.join(BASE_DIR, 'build'), )
{"golden_diff": "diff --git a/csunplugged/config/settings.py b/csunplugged/config/settings.py\n--- a/csunplugged/config/settings.py\n+++ b/csunplugged/config/settings.py\n@@ -126,5 +126,5 @@\n \n STATIC_URL = '/static/'\n STATICFILES_DIRS = (\n- os.path.join(BASE_DIR, 'static'),\n+ os.path.join(BASE_DIR, 'build'),\n )\n", "issue": "Add Bootstrap 4 SCSS\n\n", "before_files": [{"content": "\"\"\"\nDjango settings for csunplugged project.\n\nGenerated by 'django-admin startproject' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\nfrom config.settings_secret import *\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# nasty hard coding\nSETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'l@@)w&&%&u37+sjz^lsx^+29y_333oid3ygxzucar^8o(axo*f'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'general.apps.GeneralConfig',\n 'topics.apps.TopicsConfig',\n 'resources.apps.ResourcesConfig',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'config.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(SETTINGS_PATH, 'templates'),\n os.path.join(SETTINGS_PATH, 'resources/content/')\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'config.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n# Database values are stored in `settings_secret.py`\n# A template of this file is available as `settings_secret_template.py`\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nLOCALE_PATHS = ['locale']\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n )\n", "path": "csunplugged/config/settings.py"}], "after_files": [{"content": "\"\"\"\nDjango settings for csunplugged project.\n\nGenerated by 'django-admin startproject' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\nfrom config.settings_secret import *\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# nasty hard coding\nSETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'l@@)w&&%&u37+sjz^lsx^+29y_333oid3ygxzucar^8o(axo*f'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'general.apps.GeneralConfig',\n 'topics.apps.TopicsConfig',\n 'resources.apps.ResourcesConfig',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'config.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(SETTINGS_PATH, 'templates'),\n os.path.join(SETTINGS_PATH, 'resources/content/')\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'config.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n# Database values are stored in `settings_secret.py`\n# A template of this file is available as `settings_secret_template.py`\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nLOCALE_PATHS = ['locale']\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'build'),\n )\n", "path": "csunplugged/config/settings.py"}]}
1,380
90
gh_patches_debug_20201
rasdani/github-patches
git_diff
translate__pootle-4492
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add test if TP uses a proper checker This commit https://github.com/translate/pootle/commit/1d6ef1c987f2ee421b678fb9ac36e16175e4f364 fixed very hidden bug, let's add a test for it. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pytest_pootle/fixtures/models/translation_project.py` Content: ``` 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # 4 # Copyright (C) Pootle contributors. 5 # 6 # This file is a part of the Pootle project. It is distributed under the GPL3 7 # or later license. See the LICENSE file for a copy of the license and the 8 # AUTHORS file for copyright and authorship information. 9 10 import pytest 11 12 13 def _require_tp(language, project): 14 """Helper to get/create a new translation project.""" 15 from pootle_translationproject.models import create_translation_project 16 17 return create_translation_project(language, project) 18 19 20 def _require_tp_with_obsolete_dir(language, project): 21 """Helper to get/create a translation project in obsolete state.""" 22 from pootle_translationproject.models import create_translation_project 23 24 tp = create_translation_project(language, project) 25 tp.directory.makeobsolete() 26 27 return tp 28 29 30 @pytest.fixture 31 def afrikaans_tutorial(afrikaans, tutorial): 32 """Require Afrikaans Tutorial.""" 33 return _require_tp(afrikaans, tutorial) 34 35 36 @pytest.fixture 37 def arabic_tutorial_obsolete(arabic, tutorial): 38 """Require Arabic Tutorial in obsolete state.""" 39 return _require_tp_with_obsolete_dir(arabic, tutorial) 40 41 42 @pytest.fixture 43 def english_tutorial(english, tutorial): 44 """Require English Tutorial.""" 45 return _require_tp(english, tutorial) 46 47 48 @pytest.fixture 49 def french_tutorial(french, tutorial): 50 """Require French Tutorial.""" 51 return _require_tp(french, tutorial) 52 53 54 @pytest.fixture 55 def spanish_tutorial(spanish, tutorial): 56 """Require Spanish Tutorial.""" 57 return _require_tp(spanish, tutorial) 58 59 60 @pytest.fixture 61 def italian_tutorial(italian, tutorial): 62 """Require Italian Tutorial.""" 63 return _require_tp(italian, tutorial) 64 65 66 @pytest.fixture 67 def russian_tutorial(russian, tutorial): 68 """Require Russian Tutorial.""" 69 return _require_tp(russian, tutorial) 70 71 72 @pytest.fixture 73 def afrikaans_vfolder_test(afrikaans, vfolder_test): 74 """Require Afrikaans Virtual Folder Test.""" 75 return _require_tp(afrikaans, vfolder_test) 76 77 78 @pytest.fixture 79 def templates_tutorial(templates, tutorial): 80 """Require Template Tutorial.""" 81 return _require_tp(templates, tutorial) 82 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pytest_pootle/fixtures/models/translation_project.py b/pytest_pootle/fixtures/models/translation_project.py --- a/pytest_pootle/fixtures/models/translation_project.py +++ b/pytest_pootle/fixtures/models/translation_project.py @@ -7,6 +7,8 @@ # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. +import shutil + import pytest @@ -79,3 +81,25 @@ def templates_tutorial(templates, tutorial): """Require Template Tutorial.""" return _require_tp(templates, tutorial) + + +def get_project_checkers(): + from translate.filters import checks + + return ['standard'] + list(checks.projectcheckers.keys()) + + [email protected](params=get_project_checkers()) +def tp_checker_tests(request, english): + from pytest_pootle.factories import ProjectFactory + + checker_name = request.param + project = ProjectFactory( + checkstyle=checker_name, + source_language=english) + + def _remove_project_directory(): + shutil.rmtree(project.get_real_path()) + request.addfinalizer(_remove_project_directory) + + return (checker_name, project)
{"golden_diff": "diff --git a/pytest_pootle/fixtures/models/translation_project.py b/pytest_pootle/fixtures/models/translation_project.py\n--- a/pytest_pootle/fixtures/models/translation_project.py\n+++ b/pytest_pootle/fixtures/models/translation_project.py\n@@ -7,6 +7,8 @@\n # or later license. See the LICENSE file for a copy of the license and the\n # AUTHORS file for copyright and authorship information.\n \n+import shutil\n+\n import pytest\n \n \n@@ -79,3 +81,25 @@\n def templates_tutorial(templates, tutorial):\n \"\"\"Require Template Tutorial.\"\"\"\n return _require_tp(templates, tutorial)\n+\n+\n+def get_project_checkers():\n+ from translate.filters import checks\n+\n+ return ['standard'] + list(checks.projectcheckers.keys())\n+\n+\[email protected](params=get_project_checkers())\n+def tp_checker_tests(request, english):\n+ from pytest_pootle.factories import ProjectFactory\n+\n+ checker_name = request.param\n+ project = ProjectFactory(\n+ checkstyle=checker_name,\n+ source_language=english)\n+\n+ def _remove_project_directory():\n+ shutil.rmtree(project.get_real_path())\n+ request.addfinalizer(_remove_project_directory)\n+\n+ return (checker_name, project)\n", "issue": "Add test if TP uses a proper checker\nThis commit https://github.com/translate/pootle/commit/1d6ef1c987f2ee421b678fb9ac36e16175e4f364 fixed very hidden bug, let's add a test for it.\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport pytest\n\n\ndef _require_tp(language, project):\n \"\"\"Helper to get/create a new translation project.\"\"\"\n from pootle_translationproject.models import create_translation_project\n\n return create_translation_project(language, project)\n\n\ndef _require_tp_with_obsolete_dir(language, project):\n \"\"\"Helper to get/create a translation project in obsolete state.\"\"\"\n from pootle_translationproject.models import create_translation_project\n\n tp = create_translation_project(language, project)\n tp.directory.makeobsolete()\n\n return tp\n\n\[email protected]\ndef afrikaans_tutorial(afrikaans, tutorial):\n \"\"\"Require Afrikaans Tutorial.\"\"\"\n return _require_tp(afrikaans, tutorial)\n\n\[email protected]\ndef arabic_tutorial_obsolete(arabic, tutorial):\n \"\"\"Require Arabic Tutorial in obsolete state.\"\"\"\n return _require_tp_with_obsolete_dir(arabic, tutorial)\n\n\[email protected]\ndef english_tutorial(english, tutorial):\n \"\"\"Require English Tutorial.\"\"\"\n return _require_tp(english, tutorial)\n\n\[email protected]\ndef french_tutorial(french, tutorial):\n \"\"\"Require French Tutorial.\"\"\"\n return _require_tp(french, tutorial)\n\n\[email protected]\ndef spanish_tutorial(spanish, tutorial):\n \"\"\"Require Spanish Tutorial.\"\"\"\n return _require_tp(spanish, tutorial)\n\n\[email protected]\ndef italian_tutorial(italian, tutorial):\n \"\"\"Require Italian Tutorial.\"\"\"\n return _require_tp(italian, tutorial)\n\n\[email protected]\ndef russian_tutorial(russian, tutorial):\n \"\"\"Require Russian Tutorial.\"\"\"\n return _require_tp(russian, tutorial)\n\n\[email protected]\ndef afrikaans_vfolder_test(afrikaans, vfolder_test):\n \"\"\"Require Afrikaans Virtual Folder Test.\"\"\"\n return _require_tp(afrikaans, vfolder_test)\n\n\[email protected]\ndef templates_tutorial(templates, tutorial):\n \"\"\"Require Template Tutorial.\"\"\"\n return _require_tp(templates, tutorial)\n", "path": "pytest_pootle/fixtures/models/translation_project.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) Pootle contributors.\n#\n# This file is a part of the Pootle project. It is distributed under the GPL3\n# or later license. See the LICENSE file for a copy of the license and the\n# AUTHORS file for copyright and authorship information.\n\nimport shutil\n\nimport pytest\n\n\ndef _require_tp(language, project):\n \"\"\"Helper to get/create a new translation project.\"\"\"\n from pootle_translationproject.models import create_translation_project\n\n return create_translation_project(language, project)\n\n\ndef _require_tp_with_obsolete_dir(language, project):\n \"\"\"Helper to get/create a translation project in obsolete state.\"\"\"\n from pootle_translationproject.models import create_translation_project\n\n tp = create_translation_project(language, project)\n tp.directory.makeobsolete()\n\n return tp\n\n\[email protected]\ndef afrikaans_tutorial(afrikaans, tutorial):\n \"\"\"Require Afrikaans Tutorial.\"\"\"\n return _require_tp(afrikaans, tutorial)\n\n\[email protected]\ndef arabic_tutorial_obsolete(arabic, tutorial):\n \"\"\"Require Arabic Tutorial in obsolete state.\"\"\"\n return _require_tp_with_obsolete_dir(arabic, tutorial)\n\n\[email protected]\ndef english_tutorial(english, tutorial):\n \"\"\"Require English Tutorial.\"\"\"\n return _require_tp(english, tutorial)\n\n\[email protected]\ndef french_tutorial(french, tutorial):\n \"\"\"Require French Tutorial.\"\"\"\n return _require_tp(french, tutorial)\n\n\[email protected]\ndef spanish_tutorial(spanish, tutorial):\n \"\"\"Require Spanish Tutorial.\"\"\"\n return _require_tp(spanish, tutorial)\n\n\[email protected]\ndef italian_tutorial(italian, tutorial):\n \"\"\"Require Italian Tutorial.\"\"\"\n return _require_tp(italian, tutorial)\n\n\[email protected]\ndef russian_tutorial(russian, tutorial):\n \"\"\"Require Russian Tutorial.\"\"\"\n return _require_tp(russian, tutorial)\n\n\[email protected]\ndef afrikaans_vfolder_test(afrikaans, vfolder_test):\n \"\"\"Require Afrikaans Virtual Folder Test.\"\"\"\n return _require_tp(afrikaans, vfolder_test)\n\n\[email protected]\ndef templates_tutorial(templates, tutorial):\n \"\"\"Require Template Tutorial.\"\"\"\n return _require_tp(templates, tutorial)\n\n\ndef get_project_checkers():\n from translate.filters import checks\n\n return ['standard'] + list(checks.projectcheckers.keys())\n\n\[email protected](params=get_project_checkers())\ndef tp_checker_tests(request, english):\n from pytest_pootle.factories import ProjectFactory\n\n checker_name = request.param\n project = ProjectFactory(\n checkstyle=checker_name,\n source_language=english)\n\n def _remove_project_directory():\n shutil.rmtree(project.get_real_path())\n request.addfinalizer(_remove_project_directory)\n\n return (checker_name, project)\n", "path": "pytest_pootle/fixtures/models/translation_project.py"}]}
991
279
gh_patches_debug_24147
rasdani/github-patches
git_diff
UTNkar__moore-310
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Raw HTML content type <!-- Do you want to ask a question? Are you looking for support? The system administrator can help you: [email protected] --> ### Description There is currently no content type for raw HTML that can be used for the Jexpo. A special content type could be created for Jexpo as it works right now but since the way Jexpo is initialized can change (according to themselves), they recommend using a raw HTML. There should be a content type for raw HTML. <!-- Please select the appropriate "topic category"/blue and "issue type"/yellow label --> Forms are missing form introduction. ### Description Creating a new form in Wagtail lets you specify an introduction to the form, which isn't displayed. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/home/models/web_page.py` Content: ``` 1 from __future__ import absolute_import, unicode_literals 2 from django.db import models 3 from django.utils.translation import ugettext_lazy as _ 4 from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, \ 5 TabbedInterface, ObjectList 6 from wagtail.core.fields import StreamField 7 from wagtail.core.models import Page 8 from blocks.models import WAGTAIL_STATIC_BLOCKTYPES 9 from google.models import GoogleFormBlock, GoogleDriveBlock, \ 10 GoogleCalendarBlock 11 from news.models import LatestNewsBlock 12 from utils.translation import TranslatedField 13 14 15 class WebPage(Page): 16 # ---- General Page information ------ 17 18 title_sv = models.CharField(max_length=255) 19 translated_title = TranslatedField('title', 'title_sv') 20 21 body_en = StreamField( 22 WAGTAIL_STATIC_BLOCKTYPES + [ 23 ('google_calendar', GoogleCalendarBlock()), 24 ('google_drive', GoogleDriveBlock()), 25 ('google_form', GoogleFormBlock()), 26 ('news', LatestNewsBlock()), 27 ], 28 blank=True, 29 ) 30 body_sv = StreamField( 31 WAGTAIL_STATIC_BLOCKTYPES + [ 32 ('google_calendar', GoogleCalendarBlock()), 33 ('google_drive', GoogleDriveBlock()), 34 ('google_form', GoogleFormBlock()), 35 ('news', LatestNewsBlock()), 36 ], 37 blank=True, 38 ) 39 body = TranslatedField('body_en', 'body_sv') 40 41 content_panels_en = Page.content_panels + [ 42 StreamFieldPanel('body_en'), 43 ] 44 45 content_panels_sv = [ 46 FieldPanel('title_sv', classname="full title"), 47 StreamFieldPanel('body_sv'), 48 ] 49 50 edit_handler = TabbedInterface([ 51 ObjectList(content_panels_en, heading=_('English')), 52 ObjectList(content_panels_sv, heading=_('Swedish')), 53 ObjectList(Page.promote_panels, heading=_('Promote')), 54 ObjectList(Page.settings_panels, heading=_('Settings')), 55 ]) 56 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/home/models/web_page.py b/src/home/models/web_page.py --- a/src/home/models/web_page.py +++ b/src/home/models/web_page.py @@ -5,6 +5,7 @@ TabbedInterface, ObjectList from wagtail.core.fields import StreamField from wagtail.core.models import Page +from wagtail.core.blocks import RawHTMLBlock from blocks.models import WAGTAIL_STATIC_BLOCKTYPES from google.models import GoogleFormBlock, GoogleDriveBlock, \ GoogleCalendarBlock @@ -24,6 +25,7 @@ ('google_drive', GoogleDriveBlock()), ('google_form', GoogleFormBlock()), ('news', LatestNewsBlock()), + ('html', RawHTMLBlock(group="Basic")), ], blank=True, ) @@ -33,6 +35,7 @@ ('google_drive', GoogleDriveBlock()), ('google_form', GoogleFormBlock()), ('news', LatestNewsBlock()), + ('html', RawHTMLBlock(group="Basic")), ], blank=True, )
{"golden_diff": "diff --git a/src/home/models/web_page.py b/src/home/models/web_page.py\n--- a/src/home/models/web_page.py\n+++ b/src/home/models/web_page.py\n@@ -5,6 +5,7 @@\n TabbedInterface, ObjectList\n from wagtail.core.fields import StreamField\n from wagtail.core.models import Page\n+from wagtail.core.blocks import RawHTMLBlock\n from blocks.models import WAGTAIL_STATIC_BLOCKTYPES\n from google.models import GoogleFormBlock, GoogleDriveBlock, \\\n GoogleCalendarBlock\n@@ -24,6 +25,7 @@\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n+ ('html', RawHTMLBlock(group=\"Basic\")),\n ],\n blank=True,\n )\n@@ -33,6 +35,7 @@\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n+ ('html', RawHTMLBlock(group=\"Basic\")),\n ],\n blank=True,\n )\n", "issue": "Raw HTML content type\n<!-- Do you want to ask a question? Are you looking for support? The system administrator can help you: [email protected] -->\r\n\r\n### Description\r\nThere is currently no content type for raw HTML that can be used for the Jexpo. A special content type could be created for Jexpo as it works right now but since the way Jexpo is initialized can change (according to themselves), they recommend using a raw HTML. \r\n\r\nThere should be a content type for raw HTML.\r\n\r\n<!-- Please select the appropriate \"topic category\"/blue and \"issue type\"/yellow label -->\r\n\nForms are missing form introduction.\n### Description\r\n\r\nCreating a new form in Wagtail lets you specify an introduction to the form, which isn't displayed.\r\n\n", "before_files": [{"content": "from __future__ import absolute_import, unicode_literals\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, \\\n TabbedInterface, ObjectList\nfrom wagtail.core.fields import StreamField\nfrom wagtail.core.models import Page\nfrom blocks.models import WAGTAIL_STATIC_BLOCKTYPES\nfrom google.models import GoogleFormBlock, GoogleDriveBlock, \\\n GoogleCalendarBlock\nfrom news.models import LatestNewsBlock\nfrom utils.translation import TranslatedField\n\n\nclass WebPage(Page):\n # ---- General Page information ------\n\n title_sv = models.CharField(max_length=255)\n translated_title = TranslatedField('title', 'title_sv')\n\n body_en = StreamField(\n WAGTAIL_STATIC_BLOCKTYPES + [\n ('google_calendar', GoogleCalendarBlock()),\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n ],\n blank=True,\n )\n body_sv = StreamField(\n WAGTAIL_STATIC_BLOCKTYPES + [\n ('google_calendar', GoogleCalendarBlock()),\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n ],\n blank=True,\n )\n body = TranslatedField('body_en', 'body_sv')\n\n content_panels_en = Page.content_panels + [\n StreamFieldPanel('body_en'),\n ]\n\n content_panels_sv = [\n FieldPanel('title_sv', classname=\"full title\"),\n StreamFieldPanel('body_sv'),\n ]\n\n edit_handler = TabbedInterface([\n ObjectList(content_panels_en, heading=_('English')),\n ObjectList(content_panels_sv, heading=_('Swedish')),\n ObjectList(Page.promote_panels, heading=_('Promote')),\n ObjectList(Page.settings_panels, heading=_('Settings')),\n ])\n", "path": "src/home/models/web_page.py"}], "after_files": [{"content": "from __future__ import absolute_import, unicode_literals\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, \\\n TabbedInterface, ObjectList\nfrom wagtail.core.fields import StreamField\nfrom wagtail.core.models import Page\nfrom wagtail.core.blocks import RawHTMLBlock\nfrom blocks.models import WAGTAIL_STATIC_BLOCKTYPES\nfrom google.models import GoogleFormBlock, GoogleDriveBlock, \\\n GoogleCalendarBlock\nfrom news.models import LatestNewsBlock\nfrom utils.translation import TranslatedField\n\n\nclass WebPage(Page):\n # ---- General Page information ------\n\n title_sv = models.CharField(max_length=255)\n translated_title = TranslatedField('title', 'title_sv')\n\n body_en = StreamField(\n WAGTAIL_STATIC_BLOCKTYPES + [\n ('google_calendar', GoogleCalendarBlock()),\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n ('html', RawHTMLBlock(group=\"Basic\")),\n ],\n blank=True,\n )\n body_sv = StreamField(\n WAGTAIL_STATIC_BLOCKTYPES + [\n ('google_calendar', GoogleCalendarBlock()),\n ('google_drive', GoogleDriveBlock()),\n ('google_form', GoogleFormBlock()),\n ('news', LatestNewsBlock()),\n ('html', RawHTMLBlock(group=\"Basic\")),\n ],\n blank=True,\n )\n body = TranslatedField('body_en', 'body_sv')\n\n content_panels_en = Page.content_panels + [\n StreamFieldPanel('body_en'),\n ]\n\n content_panels_sv = [\n FieldPanel('title_sv', classname=\"full title\"),\n StreamFieldPanel('body_sv'),\n ]\n\n edit_handler = TabbedInterface([\n ObjectList(content_panels_en, heading=_('English')),\n ObjectList(content_panels_sv, heading=_('Swedish')),\n ObjectList(Page.promote_panels, heading=_('Promote')),\n ObjectList(Page.settings_panels, heading=_('Settings')),\n ])\n", "path": "src/home/models/web_page.py"}]}
919
227
gh_patches_debug_17224
rasdani/github-patches
git_diff
cobbler__cobbler-626
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- 'get-loader' needs syslinux updating. I've confirmed that the version of syslinux (3.61) currently in get-loader will not let you deploy vmware 5.1 on random machine. It errors with "fatal error: 10 (out of resources)" when loading tools.t00. Using the pxelinux.0 and menu.c32 binaries from the syslinux-3.86.tar.gz build on kernel.org fixes it, and lets it work. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `cobbler/action_dlcontent.py` Content: ``` 1 """ 2 Downloads bootloader content for all arches for when the user doesn't want to supply their own. 3 4 Copyright 2009, Red Hat, Inc and Others 5 Michael DeHaan <michael.dehaan AT gmail> 6 7 This program is free software; you can redistribute it and/or modify 8 it under the terms of the GNU General Public License as published by 9 the Free Software Foundation; either version 2 of the License, or 10 (at your option) any later version. 11 12 This program is distributed in the hope that it will be useful, 13 but WITHOUT ANY WARRANTY; without even the implied warranty of 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License 18 along with this program; if not, write to the Free Software 19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 20 02110-1301 USA 21 """ 22 23 import os 24 import urlgrabber 25 import clogger 26 27 class ContentDownloader: 28 29 def __init__(self,config,logger=None): 30 """ 31 Constructor 32 """ 33 self.config = config 34 self.settings = config.settings() 35 if logger is None: 36 logger = clogger.Logger() 37 self.logger = logger 38 39 40 def run(self,force=False): 41 """ 42 Download bootloader content for all of the latest bootloaders, since the user 43 has chosen to not supply their own. You may ask "why not get this from yum", though 44 Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and 45 further do not want folks to have to install a cross compiler. For those that don't like this approach 46 they can still source their cross-arch bootloader content manually. 47 """ 48 49 content_server = "http://www.cobblerd.org/loaders" 50 dest = "/var/lib/cobbler/loaders" 51 52 files = ( 53 ( "%s/README" % content_server, "%s/README" % dest ), 54 ( "%s/COPYING.elilo" % content_server, "%s/COPYING.elilo" % dest ), 55 ( "%s/COPYING.yaboot" % content_server, "%s/COPYING.yaboot" % dest), 56 ( "%s/COPYING.syslinux" % content_server, "%s/COPYING.syslinux" % dest), 57 ( "%s/elilo-3.8-ia64.efi" % content_server, "%s/elilo-ia64.efi" % dest ), 58 ( "%s/yaboot-1.3.14-12" % content_server, "%s/yaboot" % dest), 59 ( "%s/pxelinux.0-4.02" % content_server, "%s/pxelinux.0" % dest), 60 ( "%s/menu.c32-4.02" % content_server, "%s/menu.c32" % dest), 61 ( "%s/grub-0.97-x86.efi" % content_server, "%s/grub-x86.efi" % dest), 62 ( "%s/grub-0.97-x86_64.efi" % content_server, "%s/grub-x86_64.efi" % dest), 63 ) 64 65 proxies = {} 66 if os.environ.has_key("HTTP_PROXY"): 67 proxies['http'] = os.environ["HTTP_PROXY"] 68 69 if os.environ.has_key("HTTPS_PROXY"): 70 proxies['https'] = os.environ["HTTPS_PROXY"] 71 72 if os.environ.has_key("FTP_PROXY"): 73 proxies['ftp'] = os.environ["FTP_PROXY"] 74 75 if len(proxies) == 0: 76 proxies = None 77 78 for src,dst in files: 79 if os.path.exists(dst) and not force: 80 self.logger.info("path %s already exists, not overwriting existing content, use --force if you wish to update" % dst) 81 continue 82 self.logger.info("downloading %s to %s" % (src,dst)) 83 urlgrabber.grabber.urlgrab(src, filename=dst, proxies=proxies) 84 85 return True 86 87 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/cobbler/action_dlcontent.py b/cobbler/action_dlcontent.py --- a/cobbler/action_dlcontent.py +++ b/cobbler/action_dlcontent.py @@ -56,8 +56,8 @@ ( "%s/COPYING.syslinux" % content_server, "%s/COPYING.syslinux" % dest), ( "%s/elilo-3.8-ia64.efi" % content_server, "%s/elilo-ia64.efi" % dest ), ( "%s/yaboot-1.3.14-12" % content_server, "%s/yaboot" % dest), - ( "%s/pxelinux.0-4.02" % content_server, "%s/pxelinux.0" % dest), - ( "%s/menu.c32-4.02" % content_server, "%s/menu.c32" % dest), + ( "%s/pxelinux.0-3.86" % content_server, "%s/pxelinux.0" % dest), + ( "%s/menu.c32-3.86" % content_server, "%s/menu.c32" % dest), ( "%s/grub-0.97-x86.efi" % content_server, "%s/grub-x86.efi" % dest), ( "%s/grub-0.97-x86_64.efi" % content_server, "%s/grub-x86_64.efi" % dest), )
{"golden_diff": "diff --git a/cobbler/action_dlcontent.py b/cobbler/action_dlcontent.py\n--- a/cobbler/action_dlcontent.py\n+++ b/cobbler/action_dlcontent.py\n@@ -56,8 +56,8 @@\n ( \"%s/COPYING.syslinux\" % content_server, \"%s/COPYING.syslinux\" % dest),\n ( \"%s/elilo-3.8-ia64.efi\" % content_server, \"%s/elilo-ia64.efi\" % dest ),\n ( \"%s/yaboot-1.3.14-12\" % content_server, \"%s/yaboot\" % dest),\n- ( \"%s/pxelinux.0-4.02\" % content_server, \"%s/pxelinux.0\" % dest),\n- ( \"%s/menu.c32-4.02\" % content_server, \"%s/menu.c32\" % dest),\n+ ( \"%s/pxelinux.0-3.86\" % content_server, \"%s/pxelinux.0\" % dest),\n+ ( \"%s/menu.c32-3.86\" % content_server, \"%s/menu.c32\" % dest),\n ( \"%s/grub-0.97-x86.efi\" % content_server, \"%s/grub-x86.efi\" % dest),\n ( \"%s/grub-0.97-x86_64.efi\" % content_server, \"%s/grub-x86_64.efi\" % dest),\n )\n", "issue": "'get-loader' needs syslinux updating.\nI've confirmed that the version of syslinux (3.61) currently in get-loader will not let you deploy vmware 5.1 on random machine. \n\nIt errors with \"fatal error: 10 (out of resources)\" when loading tools.t00.\n\nUsing the pxelinux.0 and menu.c32 binaries from the syslinux-3.86.tar.gz build on kernel.org fixes it, and lets it work. \n\n", "before_files": [{"content": "\"\"\"\nDownloads bootloader content for all arches for when the user doesn't want to supply their own.\n\nCopyright 2009, Red Hat, Inc and Others\nMichael DeHaan <michael.dehaan AT gmail>\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n02110-1301 USA\n\"\"\"\n\nimport os\nimport urlgrabber\nimport clogger\n\nclass ContentDownloader:\n\n def __init__(self,config,logger=None):\n \"\"\"\n Constructor\n \"\"\"\n self.config = config\n self.settings = config.settings()\n if logger is None:\n logger = clogger.Logger()\n self.logger = logger\n\n\n def run(self,force=False):\n \"\"\"\n Download bootloader content for all of the latest bootloaders, since the user\n has chosen to not supply their own. You may ask \"why not get this from yum\", though\n Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and\n further do not want folks to have to install a cross compiler. For those that don't like this approach\n they can still source their cross-arch bootloader content manually.\n \"\"\"\n\n content_server = \"http://www.cobblerd.org/loaders\"\n dest = \"/var/lib/cobbler/loaders\"\n\n files = (\n ( \"%s/README\" % content_server, \"%s/README\" % dest ),\n ( \"%s/COPYING.elilo\" % content_server, \"%s/COPYING.elilo\" % dest ),\n ( \"%s/COPYING.yaboot\" % content_server, \"%s/COPYING.yaboot\" % dest),\n ( \"%s/COPYING.syslinux\" % content_server, \"%s/COPYING.syslinux\" % dest),\n ( \"%s/elilo-3.8-ia64.efi\" % content_server, \"%s/elilo-ia64.efi\" % dest ),\n ( \"%s/yaboot-1.3.14-12\" % content_server, \"%s/yaboot\" % dest),\n ( \"%s/pxelinux.0-4.02\" % content_server, \"%s/pxelinux.0\" % dest),\n ( \"%s/menu.c32-4.02\" % content_server, \"%s/menu.c32\" % dest),\n ( \"%s/grub-0.97-x86.efi\" % content_server, \"%s/grub-x86.efi\" % dest),\n ( \"%s/grub-0.97-x86_64.efi\" % content_server, \"%s/grub-x86_64.efi\" % dest),\n )\n\n proxies = {}\n if os.environ.has_key(\"HTTP_PROXY\"):\n proxies['http'] = os.environ[\"HTTP_PROXY\"]\n\n if os.environ.has_key(\"HTTPS_PROXY\"):\n proxies['https'] = os.environ[\"HTTPS_PROXY\"]\n\n if os.environ.has_key(\"FTP_PROXY\"):\n proxies['ftp'] = os.environ[\"FTP_PROXY\"]\n\n if len(proxies) == 0:\n proxies = None\n\n for src,dst in files:\n if os.path.exists(dst) and not force:\n self.logger.info(\"path %s already exists, not overwriting existing content, use --force if you wish to update\" % dst)\n continue\n self.logger.info(\"downloading %s to %s\" % (src,dst))\n urlgrabber.grabber.urlgrab(src, filename=dst, proxies=proxies)\n\n return True\n\n", "path": "cobbler/action_dlcontent.py"}], "after_files": [{"content": "\"\"\"\nDownloads bootloader content for all arches for when the user doesn't want to supply their own.\n\nCopyright 2009, Red Hat, Inc and Others\nMichael DeHaan <michael.dehaan AT gmail>\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n02110-1301 USA\n\"\"\"\n\nimport os\nimport urlgrabber\nimport clogger\n\nclass ContentDownloader:\n\n def __init__(self,config,logger=None):\n \"\"\"\n Constructor\n \"\"\"\n self.config = config\n self.settings = config.settings()\n if logger is None:\n logger = clogger.Logger()\n self.logger = logger\n\n\n def run(self,force=False):\n \"\"\"\n Download bootloader content for all of the latest bootloaders, since the user\n has chosen to not supply their own. You may ask \"why not get this from yum\", though\n Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and\n further do not want folks to have to install a cross compiler. For those that don't like this approach\n they can still source their cross-arch bootloader content manually.\n \"\"\"\n\n content_server = \"http://www.cobblerd.org/loaders\"\n dest = \"/var/lib/cobbler/loaders\"\n\n files = (\n ( \"%s/README\" % content_server, \"%s/README\" % dest ),\n ( \"%s/COPYING.elilo\" % content_server, \"%s/COPYING.elilo\" % dest ),\n ( \"%s/COPYING.yaboot\" % content_server, \"%s/COPYING.yaboot\" % dest),\n ( \"%s/COPYING.syslinux\" % content_server, \"%s/COPYING.syslinux\" % dest),\n ( \"%s/elilo-3.8-ia64.efi\" % content_server, \"%s/elilo-ia64.efi\" % dest ),\n ( \"%s/yaboot-1.3.14-12\" % content_server, \"%s/yaboot\" % dest),\n ( \"%s/pxelinux.0-3.86\" % content_server, \"%s/pxelinux.0\" % dest),\n ( \"%s/menu.c32-3.86\" % content_server, \"%s/menu.c32\" % dest),\n ( \"%s/grub-0.97-x86.efi\" % content_server, \"%s/grub-x86.efi\" % dest),\n ( \"%s/grub-0.97-x86_64.efi\" % content_server, \"%s/grub-x86_64.efi\" % dest),\n )\n\n proxies = {}\n if os.environ.has_key(\"HTTP_PROXY\"):\n proxies['http'] = os.environ[\"HTTP_PROXY\"]\n\n if os.environ.has_key(\"HTTPS_PROXY\"):\n proxies['https'] = os.environ[\"HTTPS_PROXY\"]\n\n if os.environ.has_key(\"FTP_PROXY\"):\n proxies['ftp'] = os.environ[\"FTP_PROXY\"]\n\n if len(proxies) == 0:\n proxies = None\n\n for src,dst in files:\n if os.path.exists(dst) and not force:\n self.logger.info(\"path %s already exists, not overwriting existing content, use --force if you wish to update\" % dst)\n continue\n self.logger.info(\"downloading %s to %s\" % (src,dst))\n urlgrabber.grabber.urlgrab(src, filename=dst, proxies=proxies)\n\n return True\n\n", "path": "cobbler/action_dlcontent.py"}]}
1,444
343
gh_patches_debug_11180
rasdani/github-patches
git_diff
scrapy__scrapy-4761
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Have tests generate a certificate on-the-fly Unless we want to be doing https://github.com/scrapy/scrapy/pull/4650 every year, we should look into making tests generate a fresh certificate at run time. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `conftest.py` Content: ``` 1 from pathlib import Path 2 3 import pytest 4 5 6 def _py_files(folder): 7 return (str(p) for p in Path(folder).rglob('*.py')) 8 9 10 collect_ignore = [ 11 # not a test, but looks like a test 12 "scrapy/utils/testsite.py", 13 # contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess 14 *_py_files("tests/CrawlerProcess"), 15 # contains scripts to be run by tests/test_crawler.py::CrawlerRunnerSubprocess 16 *_py_files("tests/CrawlerRunner"), 17 # Py36-only parts of respective tests 18 *_py_files("tests/py36"), 19 ] 20 21 for line in open('tests/ignores.txt'): 22 file_path = line.strip() 23 if file_path and file_path[0] != '#': 24 collect_ignore.append(file_path) 25 26 27 @pytest.fixture() 28 def chdir(tmpdir): 29 """Change to pytest-provided temporary directory""" 30 tmpdir.chdir() 31 32 33 def pytest_collection_modifyitems(session, config, items): 34 # Avoid executing tests when executing `--flake8` flag (pytest-flake8) 35 try: 36 from pytest_flake8 import Flake8Item 37 if config.getoption('--flake8'): 38 items[:] = [item for item in items if isinstance(item, Flake8Item)] 39 except ImportError: 40 pass 41 42 43 @pytest.fixture(scope='class') 44 def reactor_pytest(request): 45 if not request.cls: 46 # doctests 47 return 48 request.cls.reactor_pytest = request.config.getoption("--reactor") 49 return request.cls.reactor_pytest 50 51 52 @pytest.fixture(autouse=True) 53 def only_asyncio(request, reactor_pytest): 54 if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio': 55 pytest.skip('This test is only run with --reactor=asyncio') 56 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/conftest.py b/conftest.py --- a/conftest.py +++ b/conftest.py @@ -2,6 +2,8 @@ import pytest +from tests.keys import generate_keys + def _py_files(folder): return (str(p) for p in Path(folder).rglob('*.py')) @@ -53,3 +55,7 @@ def only_asyncio(request, reactor_pytest): if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio': pytest.skip('This test is only run with --reactor=asyncio') + + +# Generate localhost certificate files, needed by some tests +generate_keys()
{"golden_diff": "diff --git a/conftest.py b/conftest.py\n--- a/conftest.py\n+++ b/conftest.py\n@@ -2,6 +2,8 @@\n \n import pytest\n \n+from tests.keys import generate_keys\n+\n \n def _py_files(folder):\n return (str(p) for p in Path(folder).rglob('*.py'))\n@@ -53,3 +55,7 @@\n def only_asyncio(request, reactor_pytest):\n if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio':\n pytest.skip('This test is only run with --reactor=asyncio')\n+\n+\n+# Generate localhost certificate files, needed by some tests\n+generate_keys()\n", "issue": "Have tests generate a certificate on-the-fly\nUnless we want to be doing https://github.com/scrapy/scrapy/pull/4650 every year, we should look into making tests generate a fresh certificate at run time.\n", "before_files": [{"content": "from pathlib import Path\n\nimport pytest\n\n\ndef _py_files(folder):\n return (str(p) for p in Path(folder).rglob('*.py'))\n\n\ncollect_ignore = [\n # not a test, but looks like a test\n \"scrapy/utils/testsite.py\",\n # contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess\n *_py_files(\"tests/CrawlerProcess\"),\n # contains scripts to be run by tests/test_crawler.py::CrawlerRunnerSubprocess\n *_py_files(\"tests/CrawlerRunner\"),\n # Py36-only parts of respective tests\n *_py_files(\"tests/py36\"),\n]\n\nfor line in open('tests/ignores.txt'):\n file_path = line.strip()\n if file_path and file_path[0] != '#':\n collect_ignore.append(file_path)\n\n\[email protected]()\ndef chdir(tmpdir):\n \"\"\"Change to pytest-provided temporary directory\"\"\"\n tmpdir.chdir()\n\n\ndef pytest_collection_modifyitems(session, config, items):\n # Avoid executing tests when executing `--flake8` flag (pytest-flake8)\n try:\n from pytest_flake8 import Flake8Item\n if config.getoption('--flake8'):\n items[:] = [item for item in items if isinstance(item, Flake8Item)]\n except ImportError:\n pass\n\n\[email protected](scope='class')\ndef reactor_pytest(request):\n if not request.cls:\n # doctests\n return\n request.cls.reactor_pytest = request.config.getoption(\"--reactor\")\n return request.cls.reactor_pytest\n\n\[email protected](autouse=True)\ndef only_asyncio(request, reactor_pytest):\n if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio':\n pytest.skip('This test is only run with --reactor=asyncio')\n", "path": "conftest.py"}], "after_files": [{"content": "from pathlib import Path\n\nimport pytest\n\nfrom tests.keys import generate_keys\n\n\ndef _py_files(folder):\n return (str(p) for p in Path(folder).rglob('*.py'))\n\n\ncollect_ignore = [\n # not a test, but looks like a test\n \"scrapy/utils/testsite.py\",\n # contains scripts to be run by tests/test_crawler.py::CrawlerProcessSubprocess\n *_py_files(\"tests/CrawlerProcess\"),\n # contains scripts to be run by tests/test_crawler.py::CrawlerRunnerSubprocess\n *_py_files(\"tests/CrawlerRunner\"),\n # Py36-only parts of respective tests\n *_py_files(\"tests/py36\"),\n]\n\nfor line in open('tests/ignores.txt'):\n file_path = line.strip()\n if file_path and file_path[0] != '#':\n collect_ignore.append(file_path)\n\n\[email protected]()\ndef chdir(tmpdir):\n \"\"\"Change to pytest-provided temporary directory\"\"\"\n tmpdir.chdir()\n\n\ndef pytest_collection_modifyitems(session, config, items):\n # Avoid executing tests when executing `--flake8` flag (pytest-flake8)\n try:\n from pytest_flake8 import Flake8Item\n if config.getoption('--flake8'):\n items[:] = [item for item in items if isinstance(item, Flake8Item)]\n except ImportError:\n pass\n\n\[email protected](scope='class')\ndef reactor_pytest(request):\n if not request.cls:\n # doctests\n return\n request.cls.reactor_pytest = request.config.getoption(\"--reactor\")\n return request.cls.reactor_pytest\n\n\[email protected](autouse=True)\ndef only_asyncio(request, reactor_pytest):\n if request.node.get_closest_marker('only_asyncio') and reactor_pytest != 'asyncio':\n pytest.skip('This test is only run with --reactor=asyncio')\n\n\n# Generate localhost certificate files, needed by some tests\ngenerate_keys()\n", "path": "conftest.py"}]}
812
154
gh_patches_debug_25712
rasdani/github-patches
git_diff
cisagov__manage.get.gov-829
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add field for tribe locality on Tribal Goverment Question Page ### Story As a Registrant Applicant I want a way to specify the locality of my tribe so that I can give analysts more specific information to complete their review of my request ![tribalgovernment](https://github.com/cisagov/getgov/assets/107440934/48d1a8a2-e074-4ad2-9440-838eaa3e382a) ### Acceptance Criteria - [x] Content is drafted for the question - [x] Content is approved - [x] Design prototype demonstrates the look and feel for approval - [x] Implement the field in the registrar A new field is added to the page that allows the user to specify the locality of their tribe ### Additional Context _No response_ ### Issue Links _No response_ --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/registrar/templatetags/custom_filters.py` Content: ``` 1 from django import template 2 import re 3 4 register = template.Library() 5 6 7 @register.filter(name="extract_value") 8 def extract_value(html_input): 9 match = re.search(r'value="([^"]*)"', html_input) 10 if match: 11 return match.group(1) 12 return "" 13 14 15 @register.filter 16 def extract_a_text(value): 17 # Use regex to extract the text within the <a> tag 18 pattern = r"<a\b[^>]*>(.*?)</a>" 19 match = re.search(pattern, value) 20 if match: 21 extracted_text = match.group(1) 22 else: 23 extracted_text = "" 24 25 return extracted_text 26 ``` Path: `src/registrar/views/utility/mixins.py` Content: ``` 1 """Permissions-related mixin classes.""" 2 3 from django.contrib.auth.mixins import PermissionRequiredMixin 4 5 from registrar.models import UserDomainRole, DomainApplication, DomainInvitation 6 7 8 class PermissionsLoginMixin(PermissionRequiredMixin): 9 10 """Mixin that redirects to login page if not logged in, otherwise 403.""" 11 12 def handle_no_permission(self): 13 self.raise_exception = self.request.user.is_authenticated 14 return super().handle_no_permission() 15 16 17 class DomainPermission(PermissionsLoginMixin): 18 19 """Does the logged-in user have access to this domain?""" 20 21 def has_permission(self): 22 """Check if this user has access to this domain. 23 24 The user is in self.request.user and the domain needs to be looked 25 up from the domain's primary key in self.kwargs["pk"] 26 """ 27 if not self.request.user.is_authenticated: 28 return False 29 30 # user needs to have a role on the domain 31 if not UserDomainRole.objects.filter( 32 user=self.request.user, domain__id=self.kwargs["pk"] 33 ).exists(): 34 return False 35 36 # if we need to check more about the nature of role, do it here. 37 return True 38 39 40 class DomainApplicationPermission(PermissionsLoginMixin): 41 42 """Does the logged-in user have access to this domain application?""" 43 44 def has_permission(self): 45 """Check if this user has access to this domain application. 46 47 The user is in self.request.user and the domain needs to be looked 48 up from the domain's primary key in self.kwargs["pk"] 49 """ 50 if not self.request.user.is_authenticated: 51 return False 52 53 # user needs to be the creator of the application 54 # this query is empty if there isn't a domain application with this 55 # id and this user as creator 56 if not DomainApplication.objects.filter( 57 creator=self.request.user, id=self.kwargs["pk"] 58 ).exists(): 59 return False 60 61 return True 62 63 64 class DomainInvitationPermission(PermissionsLoginMixin): 65 66 """Does the logged-in user have access to this domain invitation? 67 68 A user has access to a domain invitation if they have a role on the 69 associated domain. 70 """ 71 72 def has_permission(self): 73 """Check if this user has a role on the domain of this invitation.""" 74 if not self.request.user.is_authenticated: 75 return False 76 77 if not DomainInvitation.objects.filter( 78 id=self.kwargs["pk"], domain__permissions__user=self.request.user 79 ).exists(): 80 return False 81 82 return True 83 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/registrar/templatetags/custom_filters.py b/src/registrar/templatetags/custom_filters.py --- a/src/registrar/templatetags/custom_filters.py +++ b/src/registrar/templatetags/custom_filters.py @@ -23,3 +23,20 @@ extracted_text = "" return extracted_text + + [email protected] +def find_index(haystack, needle): + try: + return haystack.index(needle) + except ValueError: + return -1 + + [email protected] +def slice_after(value, substring): + index = value.find(substring) + if index != -1: + result = value[index + len(substring) :] + return result + return value diff --git a/src/registrar/views/utility/mixins.py b/src/registrar/views/utility/mixins.py --- a/src/registrar/views/utility/mixins.py +++ b/src/registrar/views/utility/mixins.py @@ -24,6 +24,12 @@ The user is in self.request.user and the domain needs to be looked up from the domain's primary key in self.kwargs["pk"] """ + + # ticket 806 + # if self.request.user is staff or admin and + # domain.application__status = 'approved' or 'rejected' or 'action needed' + # return True + if not self.request.user.is_authenticated: return False @@ -33,6 +39,10 @@ ).exists(): return False + # ticket 796 + # if domain.application__status != 'approved' + # return false + # if we need to check more about the nature of role, do it here. return True
{"golden_diff": "diff --git a/src/registrar/templatetags/custom_filters.py b/src/registrar/templatetags/custom_filters.py\n--- a/src/registrar/templatetags/custom_filters.py\n+++ b/src/registrar/templatetags/custom_filters.py\n@@ -23,3 +23,20 @@\n extracted_text = \"\"\n \n return extracted_text\n+\n+\[email protected]\n+def find_index(haystack, needle):\n+ try:\n+ return haystack.index(needle)\n+ except ValueError:\n+ return -1\n+\n+\[email protected]\n+def slice_after(value, substring):\n+ index = value.find(substring)\n+ if index != -1:\n+ result = value[index + len(substring) :]\n+ return result\n+ return value\ndiff --git a/src/registrar/views/utility/mixins.py b/src/registrar/views/utility/mixins.py\n--- a/src/registrar/views/utility/mixins.py\n+++ b/src/registrar/views/utility/mixins.py\n@@ -24,6 +24,12 @@\n The user is in self.request.user and the domain needs to be looked\n up from the domain's primary key in self.kwargs[\"pk\"]\n \"\"\"\n+\n+ # ticket 806\n+ # if self.request.user is staff or admin and\n+ # domain.application__status = 'approved' or 'rejected' or 'action needed'\n+ # return True\n+\n if not self.request.user.is_authenticated:\n return False\n \n@@ -33,6 +39,10 @@\n ).exists():\n return False\n \n+ # ticket 796\n+ # if domain.application__status != 'approved'\n+ # return false\n+\n # if we need to check more about the nature of role, do it here.\n return True\n", "issue": "Add field for tribe locality on Tribal Goverment Question Page \n### Story\r\n\r\nAs a Registrant Applicant I want a way to specify the locality of my tribe so that I can give analysts more specific information to complete their review of my request\r\n\r\n![tribalgovernment](https://github.com/cisagov/getgov/assets/107440934/48d1a8a2-e074-4ad2-9440-838eaa3e382a)\r\n\r\n\r\n### Acceptance Criteria\r\n\r\n- [x] Content is drafted for the question\r\n- [x] Content is approved\r\n- [x] Design prototype demonstrates the look and feel for approval\r\n- [x] Implement the field in the registrar\r\n\r\nA new field is added to the page that allows the user to specify the locality of their tribe\r\n\r\n### Additional Context\r\n\r\n_No response_\r\n\r\n### Issue Links\r\n\r\n_No response_\n", "before_files": [{"content": "from django import template\nimport re\n\nregister = template.Library()\n\n\[email protected](name=\"extract_value\")\ndef extract_value(html_input):\n match = re.search(r'value=\"([^\"]*)\"', html_input)\n if match:\n return match.group(1)\n return \"\"\n\n\[email protected]\ndef extract_a_text(value):\n # Use regex to extract the text within the <a> tag\n pattern = r\"<a\\b[^>]*>(.*?)</a>\"\n match = re.search(pattern, value)\n if match:\n extracted_text = match.group(1)\n else:\n extracted_text = \"\"\n\n return extracted_text\n", "path": "src/registrar/templatetags/custom_filters.py"}, {"content": "\"\"\"Permissions-related mixin classes.\"\"\"\n\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\n\nfrom registrar.models import UserDomainRole, DomainApplication, DomainInvitation\n\n\nclass PermissionsLoginMixin(PermissionRequiredMixin):\n\n \"\"\"Mixin that redirects to login page if not logged in, otherwise 403.\"\"\"\n\n def handle_no_permission(self):\n self.raise_exception = self.request.user.is_authenticated\n return super().handle_no_permission()\n\n\nclass DomainPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain?\"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has access to this domain.\n\n The user is in self.request.user and the domain needs to be looked\n up from the domain's primary key in self.kwargs[\"pk\"]\n \"\"\"\n if not self.request.user.is_authenticated:\n return False\n\n # user needs to have a role on the domain\n if not UserDomainRole.objects.filter(\n user=self.request.user, domain__id=self.kwargs[\"pk\"]\n ).exists():\n return False\n\n # if we need to check more about the nature of role, do it here.\n return True\n\n\nclass DomainApplicationPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain application?\"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has access to this domain application.\n\n The user is in self.request.user and the domain needs to be looked\n up from the domain's primary key in self.kwargs[\"pk\"]\n \"\"\"\n if not self.request.user.is_authenticated:\n return False\n\n # user needs to be the creator of the application\n # this query is empty if there isn't a domain application with this\n # id and this user as creator\n if not DomainApplication.objects.filter(\n creator=self.request.user, id=self.kwargs[\"pk\"]\n ).exists():\n return False\n\n return True\n\n\nclass DomainInvitationPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain invitation?\n\n A user has access to a domain invitation if they have a role on the\n associated domain.\n \"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has a role on the domain of this invitation.\"\"\"\n if not self.request.user.is_authenticated:\n return False\n\n if not DomainInvitation.objects.filter(\n id=self.kwargs[\"pk\"], domain__permissions__user=self.request.user\n ).exists():\n return False\n\n return True\n", "path": "src/registrar/views/utility/mixins.py"}], "after_files": [{"content": "from django import template\nimport re\n\nregister = template.Library()\n\n\[email protected](name=\"extract_value\")\ndef extract_value(html_input):\n match = re.search(r'value=\"([^\"]*)\"', html_input)\n if match:\n return match.group(1)\n return \"\"\n\n\[email protected]\ndef extract_a_text(value):\n # Use regex to extract the text within the <a> tag\n pattern = r\"<a\\b[^>]*>(.*?)</a>\"\n match = re.search(pattern, value)\n if match:\n extracted_text = match.group(1)\n else:\n extracted_text = \"\"\n\n return extracted_text\n\n\[email protected]\ndef find_index(haystack, needle):\n try:\n return haystack.index(needle)\n except ValueError:\n return -1\n\n\[email protected]\ndef slice_after(value, substring):\n index = value.find(substring)\n if index != -1:\n result = value[index + len(substring) :]\n return result\n return value\n", "path": "src/registrar/templatetags/custom_filters.py"}, {"content": "\"\"\"Permissions-related mixin classes.\"\"\"\n\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\n\nfrom registrar.models import UserDomainRole, DomainApplication, DomainInvitation\n\n\nclass PermissionsLoginMixin(PermissionRequiredMixin):\n\n \"\"\"Mixin that redirects to login page if not logged in, otherwise 403.\"\"\"\n\n def handle_no_permission(self):\n self.raise_exception = self.request.user.is_authenticated\n return super().handle_no_permission()\n\n\nclass DomainPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain?\"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has access to this domain.\n\n The user is in self.request.user and the domain needs to be looked\n up from the domain's primary key in self.kwargs[\"pk\"]\n \"\"\"\n\n # ticket 806\n # if self.request.user is staff or admin and\n # domain.application__status = 'approved' or 'rejected' or 'action needed'\n # return True\n\n if not self.request.user.is_authenticated:\n return False\n\n # user needs to have a role on the domain\n if not UserDomainRole.objects.filter(\n user=self.request.user, domain__id=self.kwargs[\"pk\"]\n ).exists():\n return False\n\n # ticket 796\n # if domain.application__status != 'approved'\n # return false\n\n # if we need to check more about the nature of role, do it here.\n return True\n\n\nclass DomainApplicationPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain application?\"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has access to this domain application.\n\n The user is in self.request.user and the domain needs to be looked\n up from the domain's primary key in self.kwargs[\"pk\"]\n \"\"\"\n if not self.request.user.is_authenticated:\n return False\n\n # user needs to be the creator of the application\n # this query is empty if there isn't a domain application with this\n # id and this user as creator\n if not DomainApplication.objects.filter(\n creator=self.request.user, id=self.kwargs[\"pk\"]\n ).exists():\n return False\n\n return True\n\n\nclass DomainInvitationPermission(PermissionsLoginMixin):\n\n \"\"\"Does the logged-in user have access to this domain invitation?\n\n A user has access to a domain invitation if they have a role on the\n associated domain.\n \"\"\"\n\n def has_permission(self):\n \"\"\"Check if this user has a role on the domain of this invitation.\"\"\"\n if not self.request.user.is_authenticated:\n return False\n\n if not DomainInvitation.objects.filter(\n id=self.kwargs[\"pk\"], domain__permissions__user=self.request.user\n ).exists():\n return False\n\n return True\n", "path": "src/registrar/views/utility/mixins.py"}]}
1,351
403
gh_patches_debug_12955
rasdani/github-patches
git_diff
sopel-irc__sopel-2052
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- find_updates: Unexpected error (local variable 'info' referenced before assignment) ### Description An error is logged, errors shouldn't happen. ### Reproduction steps Seen in log channel, unknown, run the bot for long enough??? ### Expected behavior No error ### Logs ``` [2021-03-31 22:00:24,531] sopel.tools.jobs ERROR - Error while processing job: local variable 'info' referenced before assignment [2021-03-31 22:00:24,538] sopel.bot ERROR - Unexpected error (local variable 'info' referenced before assignment) Traceback (most recent call last): File "/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/tools/jobs.py", line 191, in _call job.execute(self.manager) File "/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/tools/jobs.py", line 463, in execute return self._handler(manager) File "/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/modules/find_updates.py", line 86, in check_version latest = info['version'] UnboundLocalError: local variable 'info' referenced before assignment ``` ### Environment - Sopel `.version`: https://github.com/sopel-irc/sopel/commit/96c55aff852bf40bca56de49b2bc30378bf1c819 - Sopel installed via: pip/wheel - Python version: 3.7.3 - Operating system: Debian 10.9 - IRCd `/version`: freenode - Relevant plugins: find_updates --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `sopel/modules/find_updates.py` Content: ``` 1 # coding=utf-8 2 """ 3 find_updates.py - Sopel Update Check Plugin 4 This is separated from version.py, so that it can be easily overridden by 5 distribution packagers, and they can check their repositories rather than the 6 Sopel website. 7 Copyright 2014, Elsie Powell, embolalia.com 8 Licensed under the Eiffel Forum License 2. 9 10 https://sopel.chat 11 """ 12 from __future__ import absolute_import, division, print_function, unicode_literals 13 14 import requests 15 16 from sopel import ( 17 __version__ as current_version, 18 _version_info, 19 plugin, 20 tools, 21 version_info, 22 ) 23 24 25 wait_time = 24 * 60 * 60 # check once per day 26 version_url = 'https://sopel.chat/latest.json' 27 stable_message = ( 28 'A new Sopel version, {}, is available; I am running {}. Please update ' 29 'me. Full release notes at {}' 30 ) 31 unstable_message = ( 32 'A new pre-release version, {}, is available; I am running {}. Please ' 33 'update me.{}' 34 ) 35 36 37 @plugin.event(tools.events.RPL_LUSERCLIENT) 38 def startup_version_check(bot, trigger): 39 if not bot.memory.get('update_startup_check_run', False): 40 bot.memory['update_startup_check_run'] = True 41 check_version(bot) 42 43 44 def _check_succeeded(bot): 45 bot.memory['update_failures'] = 0 46 47 48 def _check_failed(bot): 49 bot.memory['update_failures'] = 1 + bot.memory.get('update_failures', 0) 50 51 52 @plugin.interval(wait_time) 53 def check_version(bot): 54 version = version_info 55 success = False 56 57 try: 58 r = requests.get(version_url, timeout=(5, 5)) 59 except requests.exceptions.RequestException: 60 _check_failed(bot) 61 else: 62 success = True 63 64 try: 65 if success: 66 info = r.json() 67 except ValueError: 68 # TODO: use JSONDecodeError when dropping Pythons < 3.5 69 _check_failed(bot) 70 71 if not success and bot.memory.get('update_failures', 0) > 4: 72 bot.say( 73 "[update] I haven't been able to check for updates in a while. " 74 "Please verify that {} is working and I can reach it." 75 .format(version_url), bot.config.core.owner) 76 bot.say( 77 "[update] If this issue persists, please alert the Sopel dev team " 78 "in #sopel on freenode, or open a GitHub issue: " 79 "https://github.com/sopel-irc/sopel/issues", 80 bot.config.core.owner) 81 return 82 83 _check_succeeded(bot) 84 85 if version.releaselevel == 'final': 86 latest = info['version'] 87 notes = info['release_notes'] 88 message = stable_message 89 else: 90 latest = info['unstable'] 91 notes = info.get('unstable_notes', '') 92 if notes: 93 notes = ' Full release notes at ' + notes 94 message = unstable_message 95 latest_version = _version_info(latest) 96 97 if version < latest_version: 98 msg = message.format(latest, current_version, notes) 99 bot.say('[update] ' + msg, bot.config.core.owner) 100 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/sopel/modules/find_updates.py b/sopel/modules/find_updates.py --- a/sopel/modules/find_updates.py +++ b/sopel/modules/find_updates.py @@ -67,8 +67,14 @@ except ValueError: # TODO: use JSONDecodeError when dropping Pythons < 3.5 _check_failed(bot) + success = False - if not success and bot.memory.get('update_failures', 0) > 4: + if not success: + if bot.memory.get('update_failures', 0) <= 4: + # not enough failures to worry; silently ignore this one + return + + # too many failures to ignore; notify owner bot.say( "[update] I haven't been able to check for updates in a while. " "Please verify that {} is working and I can reach it."
{"golden_diff": "diff --git a/sopel/modules/find_updates.py b/sopel/modules/find_updates.py\n--- a/sopel/modules/find_updates.py\n+++ b/sopel/modules/find_updates.py\n@@ -67,8 +67,14 @@\n except ValueError:\n # TODO: use JSONDecodeError when dropping Pythons < 3.5\n _check_failed(bot)\n+ success = False\n \n- if not success and bot.memory.get('update_failures', 0) > 4:\n+ if not success:\n+ if bot.memory.get('update_failures', 0) <= 4:\n+ # not enough failures to worry; silently ignore this one\n+ return\n+\n+ # too many failures to ignore; notify owner\n bot.say(\n \"[update] I haven't been able to check for updates in a while. \"\n \"Please verify that {} is working and I can reach it.\"\n", "issue": "find_updates: Unexpected error (local variable 'info' referenced before assignment)\n### Description\r\nAn error is logged, errors shouldn't happen.\r\n\r\n### Reproduction steps\r\nSeen in log channel, unknown, run the bot for long enough???\r\n\r\n### Expected behavior\r\nNo error\r\n\r\n### Logs\r\n```\r\n[2021-03-31 22:00:24,531] sopel.tools.jobs ERROR - Error while processing job: local variable 'info' referenced before assignment\r\n[2021-03-31 22:00:24,538] sopel.bot ERROR - Unexpected error (local variable 'info' referenced before assignment)\r\nTraceback (most recent call last):\r\n File \"/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/tools/jobs.py\", line 191, in _call\r\n job.execute(self.manager)\r\n File \"/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/tools/jobs.py\", line 463, in execute\r\n return self._handler(manager)\r\n File \"/srv/sopelbots/devvenv/lib/python3.7/site-packages/sopel/modules/find_updates.py\", line 86, in check_version\r\n latest = info['version']\r\nUnboundLocalError: local variable 'info' referenced before assignment\r\n\r\n```\r\n\r\n### Environment\r\n- Sopel `.version`: https://github.com/sopel-irc/sopel/commit/96c55aff852bf40bca56de49b2bc30378bf1c819\r\n- Sopel installed via: pip/wheel\r\n- Python version: 3.7.3\r\n- Operating system: Debian 10.9\r\n- IRCd `/version`: freenode\r\n- Relevant plugins: find_updates\r\n\n", "before_files": [{"content": "# coding=utf-8\n\"\"\"\nfind_updates.py - Sopel Update Check Plugin\nThis is separated from version.py, so that it can be easily overridden by\ndistribution packagers, and they can check their repositories rather than the\nSopel website.\nCopyright 2014, Elsie Powell, embolalia.com\nLicensed under the Eiffel Forum License 2.\n\nhttps://sopel.chat\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport requests\n\nfrom sopel import (\n __version__ as current_version,\n _version_info,\n plugin,\n tools,\n version_info,\n)\n\n\nwait_time = 24 * 60 * 60 # check once per day\nversion_url = 'https://sopel.chat/latest.json'\nstable_message = (\n 'A new Sopel version, {}, is available; I am running {}. Please update '\n 'me. Full release notes at {}'\n)\nunstable_message = (\n 'A new pre-release version, {}, is available; I am running {}. Please '\n 'update me.{}'\n)\n\n\[email protected](tools.events.RPL_LUSERCLIENT)\ndef startup_version_check(bot, trigger):\n if not bot.memory.get('update_startup_check_run', False):\n bot.memory['update_startup_check_run'] = True\n check_version(bot)\n\n\ndef _check_succeeded(bot):\n bot.memory['update_failures'] = 0\n\n\ndef _check_failed(bot):\n bot.memory['update_failures'] = 1 + bot.memory.get('update_failures', 0)\n\n\[email protected](wait_time)\ndef check_version(bot):\n version = version_info\n success = False\n\n try:\n r = requests.get(version_url, timeout=(5, 5))\n except requests.exceptions.RequestException:\n _check_failed(bot)\n else:\n success = True\n\n try:\n if success:\n info = r.json()\n except ValueError:\n # TODO: use JSONDecodeError when dropping Pythons < 3.5\n _check_failed(bot)\n\n if not success and bot.memory.get('update_failures', 0) > 4:\n bot.say(\n \"[update] I haven't been able to check for updates in a while. \"\n \"Please verify that {} is working and I can reach it.\"\n .format(version_url), bot.config.core.owner)\n bot.say(\n \"[update] If this issue persists, please alert the Sopel dev team \"\n \"in #sopel on freenode, or open a GitHub issue: \"\n \"https://github.com/sopel-irc/sopel/issues\",\n bot.config.core.owner)\n return\n\n _check_succeeded(bot)\n\n if version.releaselevel == 'final':\n latest = info['version']\n notes = info['release_notes']\n message = stable_message\n else:\n latest = info['unstable']\n notes = info.get('unstable_notes', '')\n if notes:\n notes = ' Full release notes at ' + notes\n message = unstable_message\n latest_version = _version_info(latest)\n\n if version < latest_version:\n msg = message.format(latest, current_version, notes)\n bot.say('[update] ' + msg, bot.config.core.owner)\n", "path": "sopel/modules/find_updates.py"}], "after_files": [{"content": "# coding=utf-8\n\"\"\"\nfind_updates.py - Sopel Update Check Plugin\nThis is separated from version.py, so that it can be easily overridden by\ndistribution packagers, and they can check their repositories rather than the\nSopel website.\nCopyright 2014, Elsie Powell, embolalia.com\nLicensed under the Eiffel Forum License 2.\n\nhttps://sopel.chat\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport requests\n\nfrom sopel import (\n __version__ as current_version,\n _version_info,\n plugin,\n tools,\n version_info,\n)\n\n\nwait_time = 24 * 60 * 60 # check once per day\nversion_url = 'https://sopel.chat/latest.json'\nstable_message = (\n 'A new Sopel version, {}, is available; I am running {}. Please update '\n 'me. Full release notes at {}'\n)\nunstable_message = (\n 'A new pre-release version, {}, is available; I am running {}. Please '\n 'update me.{}'\n)\n\n\[email protected](tools.events.RPL_LUSERCLIENT)\ndef startup_version_check(bot, trigger):\n if not bot.memory.get('update_startup_check_run', False):\n bot.memory['update_startup_check_run'] = True\n check_version(bot)\n\n\ndef _check_succeeded(bot):\n bot.memory['update_failures'] = 0\n\n\ndef _check_failed(bot):\n bot.memory['update_failures'] = 1 + bot.memory.get('update_failures', 0)\n\n\[email protected](wait_time)\ndef check_version(bot):\n version = version_info\n success = False\n\n try:\n r = requests.get(version_url, timeout=(5, 5))\n except requests.exceptions.RequestException:\n _check_failed(bot)\n else:\n success = True\n\n try:\n if success:\n info = r.json()\n except ValueError:\n # TODO: use JSONDecodeError when dropping Pythons < 3.5\n _check_failed(bot)\n success = False\n\n if not success:\n if bot.memory.get('update_failures', 0) <= 4:\n # not enough failures to worry; silently ignore this one\n return\n\n # too many failures to ignore; notify owner\n bot.say(\n \"[update] I haven't been able to check for updates in a while. \"\n \"Please verify that {} is working and I can reach it.\"\n .format(version_url), bot.config.core.owner)\n bot.say(\n \"[update] If this issue persists, please alert the Sopel dev team \"\n \"in #sopel on freenode, or open a GitHub issue: \"\n \"https://github.com/sopel-irc/sopel/issues\",\n bot.config.core.owner)\n return\n\n _check_succeeded(bot)\n\n if version.releaselevel == 'final':\n latest = info['version']\n notes = info['release_notes']\n message = stable_message\n else:\n latest = info['unstable']\n notes = info.get('unstable_notes', '')\n if notes:\n notes = ' Full release notes at ' + notes\n message = unstable_message\n latest_version = _version_info(latest)\n\n if version < latest_version:\n msg = message.format(latest, current_version, notes)\n bot.say('[update] ' + msg, bot.config.core.owner)\n", "path": "sopel/modules/find_updates.py"}]}
1,579
200
gh_patches_debug_32345
rasdani/github-patches
git_diff
optuna__optuna-1103
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `plot_intermediate_values` example code does not contain intermediate values. The example code snippet embedded in the documentation for [`plot_intermediate_values`](https://github.com/optuna/optuna/blob/master/optuna/visualization/intermediate_values.py) doesn't call `Trial.report` and thus does not contain intermediate values. The example should be updated. See also https://github.com/optuna/optuna/pull/1003#issuecomment-599359742. Current documentation with empty plot: https://optuna.readthedocs.io/en/latest/reference/visualization.html#optuna.visualization.plot_intermediate_values --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `optuna/visualization/intermediate_values.py` Content: ``` 1 from optuna.logging import get_logger 2 from optuna.trial import TrialState 3 from optuna import type_checking 4 from optuna.visualization.utils import _check_plotly_availability 5 from optuna.visualization.utils import is_available 6 7 if type_checking.TYPE_CHECKING: 8 from optuna.study import Study # NOQA 9 10 if is_available(): 11 from optuna.visualization.plotly_imports import go 12 13 logger = get_logger(__name__) 14 15 16 def plot_intermediate_values(study): 17 # type: (Study) -> go.Figure 18 """Plot intermediate values of all trials in a study. 19 20 Example: 21 22 The following code snippet shows how to plot intermediate values. 23 24 .. testcode:: 25 26 import optuna 27 28 def objective(trial): 29 x = trial.suggest_uniform('x', -100, 100) 30 y = trial.suggest_categorical('y', [-1, 0, 1]) 31 return x ** 2 + y 32 33 study = optuna.create_study() 34 study.optimize(objective, n_trials=10) 35 36 optuna.visualization.plot_intermediate_values(study) 37 38 .. raw:: html 39 40 <iframe src="../_static/plot_intermediate_values.html" 41 width="100%" height="500px" frameborder="0"> 42 </iframe> 43 44 Args: 45 study: 46 A :class:`~optuna.study.Study` object whose trials are plotted for their intermediate 47 values. 48 49 Returns: 50 A :class:`plotly.graph_objs.Figure` object. 51 """ 52 53 _check_plotly_availability() 54 return _get_intermediate_plot(study) 55 56 57 def _get_intermediate_plot(study): 58 # type: (Study) -> go.Figure 59 60 layout = go.Layout( 61 title="Intermediate Values Plot", 62 xaxis={"title": "Step"}, 63 yaxis={"title": "Intermediate Value"}, 64 showlegend=False, 65 ) 66 67 target_state = [TrialState.PRUNED, TrialState.COMPLETE, TrialState.RUNNING] 68 trials = [trial for trial in study.trials if trial.state in target_state] 69 70 if len(trials) == 0: 71 logger.warning("Study instance does not contain trials.") 72 return go.Figure(data=[], layout=layout) 73 74 traces = [] 75 for trial in trials: 76 if trial.intermediate_values: 77 sorted_intermediate_values = sorted(trial.intermediate_values.items()) 78 trace = go.Scatter( 79 x=tuple((x for x, _ in sorted_intermediate_values)), 80 y=tuple((y for _, y in sorted_intermediate_values)), 81 mode="lines+markers", 82 marker={"maxdisplayed": 10}, 83 name="Trial{}".format(trial.number), 84 ) 85 traces.append(trace) 86 87 if not traces: 88 logger.warning( 89 "You need to set up the pruning feature to utilize `plot_intermediate_values()`" 90 ) 91 return go.Figure(data=[], layout=layout) 92 93 figure = go.Figure(data=traces, layout=layout) 94 95 return figure 96 ``` Path: `docs/source/scripts/plot_intermediate_values.py` Content: ``` 1 import os 2 3 import plotly 4 5 import optuna 6 7 8 def objective(trial): 9 x = trial.suggest_uniform("x", -100, 100) 10 y = trial.suggest_categorical("y", [-1, 0, 1]) 11 return x ** 2 + y 12 13 14 def main(): 15 sampler = optuna.samplers.TPESampler(seed=10) 16 study = optuna.create_study(sampler=sampler) 17 study.optimize(objective, n_trials=10) 18 19 fig = optuna.visualization.plot_intermediate_values(study) 20 fig_html = plotly.offline.plot(fig, output_type="div", include_plotlyjs="cdn", auto_open=False) 21 22 fig_dir = "../plotly_figures" 23 os.makedirs(fig_dir, exist_ok=True) 24 with open(os.path.join(fig_dir, "plot_intermediate_values.html"), "w") as f: 25 f.write(fig_html) 26 27 28 if __name__ == "__main__": 29 main() 30 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/docs/source/scripts/plot_intermediate_values.py b/docs/source/scripts/plot_intermediate_values.py --- a/docs/source/scripts/plot_intermediate_values.py +++ b/docs/source/scripts/plot_intermediate_values.py @@ -5,16 +5,35 @@ import optuna +def f(x): + return (x - 2) ** 2 + + +def df(x): + return 2 * x - 4 + + def objective(trial): - x = trial.suggest_uniform("x", -100, 100) - y = trial.suggest_categorical("y", [-1, 0, 1]) - return x ** 2 + y + lr = trial.suggest_loguniform("lr", 1e-5, 1e-1) + + x = 3 + for step in range(128): + y = f(x) + + trial.report(y, step=step) + if trial.should_prune(): + raise optuna.exceptions.TrialPruned() + + gy = df(x) + x -= gy * lr + + return y def main(): sampler = optuna.samplers.TPESampler(seed=10) study = optuna.create_study(sampler=sampler) - study.optimize(objective, n_trials=10) + study.optimize(objective, n_trials=16) fig = optuna.visualization.plot_intermediate_values(study) fig_html = plotly.offline.plot(fig, output_type="div", include_plotlyjs="cdn", auto_open=False) diff --git a/optuna/visualization/intermediate_values.py b/optuna/visualization/intermediate_values.py --- a/optuna/visualization/intermediate_values.py +++ b/optuna/visualization/intermediate_values.py @@ -25,13 +25,30 @@ import optuna + def f(x): + return (x - 2) ** 2 + + def df(x): + return 2 * x - 4 + def objective(trial): - x = trial.suggest_uniform('x', -100, 100) - y = trial.suggest_categorical('y', [-1, 0, 1]) - return x ** 2 + y + lr = trial.suggest_loguniform("lr", 1e-5, 1e-1) + + x = 3 + for step in range(128): + y = f(x) + + trial.report(y, step=step) + if trial.should_prune(): + raise optuna.exceptions.TrialPruned() + + gy = df(x) + x -= gy * lr + + return y study = optuna.create_study() - study.optimize(objective, n_trials=10) + study.optimize(objective, n_trials=16) optuna.visualization.plot_intermediate_values(study)
{"golden_diff": "diff --git a/docs/source/scripts/plot_intermediate_values.py b/docs/source/scripts/plot_intermediate_values.py\n--- a/docs/source/scripts/plot_intermediate_values.py\n+++ b/docs/source/scripts/plot_intermediate_values.py\n@@ -5,16 +5,35 @@\n import optuna\n \n \n+def f(x):\n+ return (x - 2) ** 2\n+\n+\n+def df(x):\n+ return 2 * x - 4\n+\n+\n def objective(trial):\n- x = trial.suggest_uniform(\"x\", -100, 100)\n- y = trial.suggest_categorical(\"y\", [-1, 0, 1])\n- return x ** 2 + y\n+ lr = trial.suggest_loguniform(\"lr\", 1e-5, 1e-1)\n+\n+ x = 3\n+ for step in range(128):\n+ y = f(x)\n+\n+ trial.report(y, step=step)\n+ if trial.should_prune():\n+ raise optuna.exceptions.TrialPruned()\n+\n+ gy = df(x)\n+ x -= gy * lr\n+\n+ return y\n \n \n def main():\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n- study.optimize(objective, n_trials=10)\n+ study.optimize(objective, n_trials=16)\n \n fig = optuna.visualization.plot_intermediate_values(study)\n fig_html = plotly.offline.plot(fig, output_type=\"div\", include_plotlyjs=\"cdn\", auto_open=False)\ndiff --git a/optuna/visualization/intermediate_values.py b/optuna/visualization/intermediate_values.py\n--- a/optuna/visualization/intermediate_values.py\n+++ b/optuna/visualization/intermediate_values.py\n@@ -25,13 +25,30 @@\n \n import optuna\n \n+ def f(x):\n+ return (x - 2) ** 2\n+\n+ def df(x):\n+ return 2 * x - 4\n+\n def objective(trial):\n- x = trial.suggest_uniform('x', -100, 100)\n- y = trial.suggest_categorical('y', [-1, 0, 1])\n- return x ** 2 + y\n+ lr = trial.suggest_loguniform(\"lr\", 1e-5, 1e-1)\n+\n+ x = 3\n+ for step in range(128):\n+ y = f(x)\n+\n+ trial.report(y, step=step)\n+ if trial.should_prune():\n+ raise optuna.exceptions.TrialPruned()\n+\n+ gy = df(x)\n+ x -= gy * lr\n+\n+ return y\n \n study = optuna.create_study()\n- study.optimize(objective, n_trials=10)\n+ study.optimize(objective, n_trials=16)\n \n optuna.visualization.plot_intermediate_values(study)\n", "issue": "`plot_intermediate_values` example code does not contain intermediate values.\nThe example code snippet embedded in the documentation for [`plot_intermediate_values`](https://github.com/optuna/optuna/blob/master/optuna/visualization/intermediate_values.py) doesn't call `Trial.report` and thus does not contain intermediate values. The example should be updated. See also https://github.com/optuna/optuna/pull/1003#issuecomment-599359742. \r\n\r\nCurrent documentation with empty plot: https://optuna.readthedocs.io/en/latest/reference/visualization.html#optuna.visualization.plot_intermediate_values\n", "before_files": [{"content": "from optuna.logging import get_logger\nfrom optuna.trial import TrialState\nfrom optuna import type_checking\nfrom optuna.visualization.utils import _check_plotly_availability\nfrom optuna.visualization.utils import is_available\n\nif type_checking.TYPE_CHECKING:\n from optuna.study import Study # NOQA\n\nif is_available():\n from optuna.visualization.plotly_imports import go\n\nlogger = get_logger(__name__)\n\n\ndef plot_intermediate_values(study):\n # type: (Study) -> go.Figure\n \"\"\"Plot intermediate values of all trials in a study.\n\n Example:\n\n The following code snippet shows how to plot intermediate values.\n\n .. testcode::\n\n import optuna\n\n def objective(trial):\n x = trial.suggest_uniform('x', -100, 100)\n y = trial.suggest_categorical('y', [-1, 0, 1])\n return x ** 2 + y\n\n study = optuna.create_study()\n study.optimize(objective, n_trials=10)\n\n optuna.visualization.plot_intermediate_values(study)\n\n .. raw:: html\n\n <iframe src=\"../_static/plot_intermediate_values.html\"\n width=\"100%\" height=\"500px\" frameborder=\"0\">\n </iframe>\n\n Args:\n study:\n A :class:`~optuna.study.Study` object whose trials are plotted for their intermediate\n values.\n\n Returns:\n A :class:`plotly.graph_objs.Figure` object.\n \"\"\"\n\n _check_plotly_availability()\n return _get_intermediate_plot(study)\n\n\ndef _get_intermediate_plot(study):\n # type: (Study) -> go.Figure\n\n layout = go.Layout(\n title=\"Intermediate Values Plot\",\n xaxis={\"title\": \"Step\"},\n yaxis={\"title\": \"Intermediate Value\"},\n showlegend=False,\n )\n\n target_state = [TrialState.PRUNED, TrialState.COMPLETE, TrialState.RUNNING]\n trials = [trial for trial in study.trials if trial.state in target_state]\n\n if len(trials) == 0:\n logger.warning(\"Study instance does not contain trials.\")\n return go.Figure(data=[], layout=layout)\n\n traces = []\n for trial in trials:\n if trial.intermediate_values:\n sorted_intermediate_values = sorted(trial.intermediate_values.items())\n trace = go.Scatter(\n x=tuple((x for x, _ in sorted_intermediate_values)),\n y=tuple((y for _, y in sorted_intermediate_values)),\n mode=\"lines+markers\",\n marker={\"maxdisplayed\": 10},\n name=\"Trial{}\".format(trial.number),\n )\n traces.append(trace)\n\n if not traces:\n logger.warning(\n \"You need to set up the pruning feature to utilize `plot_intermediate_values()`\"\n )\n return go.Figure(data=[], layout=layout)\n\n figure = go.Figure(data=traces, layout=layout)\n\n return figure\n", "path": "optuna/visualization/intermediate_values.py"}, {"content": "import os\n\nimport plotly\n\nimport optuna\n\n\ndef objective(trial):\n x = trial.suggest_uniform(\"x\", -100, 100)\n y = trial.suggest_categorical(\"y\", [-1, 0, 1])\n return x ** 2 + y\n\n\ndef main():\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=10)\n\n fig = optuna.visualization.plot_intermediate_values(study)\n fig_html = plotly.offline.plot(fig, output_type=\"div\", include_plotlyjs=\"cdn\", auto_open=False)\n\n fig_dir = \"../plotly_figures\"\n os.makedirs(fig_dir, exist_ok=True)\n with open(os.path.join(fig_dir, \"plot_intermediate_values.html\"), \"w\") as f:\n f.write(fig_html)\n\n\nif __name__ == \"__main__\":\n main()\n", "path": "docs/source/scripts/plot_intermediate_values.py"}], "after_files": [{"content": "from optuna.logging import get_logger\nfrom optuna.structs import TrialState\nfrom optuna import type_checking\nfrom optuna.visualization.utils import _check_plotly_availability\nfrom optuna.visualization.utils import is_available\n\nif type_checking.TYPE_CHECKING:\n from optuna.study import Study # NOQA\n\nif is_available():\n from optuna.visualization.plotly_imports import go\n\nlogger = get_logger(__name__)\n\n\ndef plot_intermediate_values(study):\n # type: (Study) -> go.Figure\n \"\"\"Plot intermediate values of all trials in a study.\n\n Example:\n\n The following code snippet shows how to plot intermediate values.\n\n .. testcode::\n\n import optuna\n\n def f(x):\n return (x - 2) ** 2\n\n def df(x):\n return 2 * x - 4\n\n def objective(trial):\n lr = trial.suggest_loguniform(\"lr\", 1e-5, 1e-1)\n\n x = 3\n for step in range(128):\n y = f(x)\n\n trial.report(y, step=step)\n if trial.should_prune():\n raise optuna.exceptions.TrialPruned()\n\n gy = df(x)\n x -= gy * lr\n\n return y\n\n study = optuna.create_study()\n study.optimize(objective, n_trials=16)\n\n optuna.visualization.plot_intermediate_values(study)\n\n .. raw:: html\n\n <iframe src=\"../_static/plot_intermediate_values.html\"\n width=\"100%\" height=\"500px\" frameborder=\"0\">\n </iframe>\n\n Args:\n study:\n A :class:`~optuna.study.Study` object whose trials are plotted for their intermediate\n values.\n\n Returns:\n A :class:`plotly.graph_objs.Figure` object.\n \"\"\"\n\n _check_plotly_availability()\n return _get_intermediate_plot(study)\n\n\ndef _get_intermediate_plot(study):\n # type: (Study) -> go.Figure\n\n layout = go.Layout(\n title=\"Intermediate Values Plot\",\n xaxis={\"title\": \"Step\"},\n yaxis={\"title\": \"Intermediate Value\"},\n showlegend=False,\n )\n\n target_state = [TrialState.PRUNED, TrialState.COMPLETE, TrialState.RUNNING]\n trials = [trial for trial in study.trials if trial.state in target_state]\n\n if len(trials) == 0:\n logger.warning(\"Study instance does not contain trials.\")\n return go.Figure(data=[], layout=layout)\n\n traces = []\n for trial in trials:\n if trial.intermediate_values:\n sorted_intermediate_values = sorted(trial.intermediate_values.items())\n trace = go.Scatter(\n x=tuple((x for x, _ in sorted_intermediate_values)),\n y=tuple((y for _, y in sorted_intermediate_values)),\n mode=\"lines+markers\",\n marker={\"maxdisplayed\": 10},\n name=\"Trial{}\".format(trial.number),\n )\n traces.append(trace)\n\n if not traces:\n logger.warning(\n \"You need to set up the pruning feature to utilize `plot_intermediate_values()`\"\n )\n return go.Figure(data=[], layout=layout)\n\n figure = go.Figure(data=traces, layout=layout)\n\n return figure\n", "path": "optuna/visualization/intermediate_values.py"}, {"content": "import os\n\nimport plotly\n\nimport optuna\n\n\ndef f(x):\n return (x - 2) ** 2\n\n\ndef df(x):\n return 2 * x - 4\n\n\ndef objective(trial):\n lr = trial.suggest_loguniform(\"lr\", 1e-5, 1e-1)\n\n x = 3\n for step in range(128):\n y = f(x)\n\n trial.report(y, step=step)\n if trial.should_prune():\n raise optuna.exceptions.TrialPruned()\n\n gy = df(x)\n x -= gy * lr\n\n return y\n\n\ndef main():\n sampler = optuna.samplers.TPESampler(seed=10)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=16)\n\n fig = optuna.visualization.plot_intermediate_values(study)\n fig_html = plotly.offline.plot(fig, output_type=\"div\", include_plotlyjs=\"cdn\", auto_open=False)\n\n fig_dir = \"../plotly_figures\"\n os.makedirs(fig_dir, exist_ok=True)\n with open(os.path.join(fig_dir, \"plot_intermediate_values.html\"), \"w\") as f:\n f.write(fig_html)\n\n\nif __name__ == \"__main__\":\n main()\n", "path": "docs/source/scripts/plot_intermediate_values.py"}]}
1,525
671
gh_patches_debug_4254
rasdani/github-patches
git_diff
facebookresearch__Mephisto-594
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- NameError: name 'Blueprint' is not defined Hi! I wanted to try the project from the "quickstart" but I hit >NameError: name 'Blueprint' is not defined After running these steps: ```bash pip install -e . mkdir ~/data mephisto config core.main_data_directory ~/data mephisto check # OK cd examples/simple_static_task python static_test_script.py ``` Any idea? Seems to be related to Flask. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py` Content: ``` 1 #!/usr/bin/env python3 2 3 # Copyright (c) Facebook, Inc. and its affiliates. 4 # This source code is licensed under the MIT license found in the 5 # LICENSE file in the root directory of this source tree. 6 7 from mephisto.abstractions.blueprints.abstract.static_task.static_blueprint import ( 8 StaticBlueprint, 9 StaticBlueprintArgs, 10 ) 11 from dataclasses import dataclass, field 12 from omegaconf import MISSING, DictConfig 13 from mephisto.abstractions.blueprints.static_html_task.static_html_task_builder import ( 14 StaticHTMLTaskBuilder, 15 ) 16 from mephisto.operations.registry import register_mephisto_abstraction 17 18 import os 19 import time 20 import csv 21 import types 22 23 from typing import ClassVar, List, Type, Any, Dict, Iterable, Optional, TYPE_CHECKING 24 25 if TYPE_CHECKING: 26 from mephisto.data_model.task_run import TaskRun 27 from mephisto.data_model.blueprint import ( 28 AgentState, 29 TaskRunner, 30 TaskBuilder, 31 SharedTaskState, 32 ) 33 from mephisto.data_model.assignment import Assignment 34 from mephisto.data_model.agent import OnboardingAgent 35 from mephisto.data_model.worker import Worker 36 37 BLUEPRINT_TYPE = "static_task" 38 39 40 @dataclass 41 class StaticHTMLBlueprintArgs(StaticBlueprintArgs): 42 """ 43 Adds required options for StaticBlueprints. 44 task_source points to the file intending to be deployed for this task 45 data_csv has the data to be deployed for this task. 46 """ 47 48 _blueprint_type: str = BLUEPRINT_TYPE 49 _group: str = field( 50 default="StaticBlueprint", 51 metadata={ 52 "help": ( 53 "Tasks launched from static blueprints need a " 54 "source html file to display to workers, as well as a csv " 55 "containing values that will be inserted into templates in " 56 "the html. " 57 ) 58 }, 59 ) 60 task_source: str = field( 61 default=MISSING, 62 metadata={ 63 "help": "Path to source HTML file for the task being run", 64 "required": True, 65 }, 66 ) 67 preview_source: Optional[str] = field( 68 default=MISSING, 69 metadata={"help": "Optional path to source HTML file to preview the task"}, 70 ) 71 onboarding_source: Optional[str] = field( 72 default=MISSING, 73 metadata={"help": "Optional path to source HTML file to onboarding the task"}, 74 ) 75 76 77 @register_mephisto_abstraction() 78 class StaticHTMLBlueprint(StaticBlueprint): 79 """Blueprint for a task that runs off of a built react javascript bundle""" 80 81 TaskBuilderClass = StaticHTMLTaskBuilder 82 ArgsClass = StaticHTMLBlueprintArgs 83 BLUEPRINT_TYPE = BLUEPRINT_TYPE 84 85 def __init__( 86 self, task_run: "TaskRun", args: "DictConfig", shared_state: "SharedTaskState" 87 ): 88 super().__init__(task_run, args, shared_state) 89 self.html_file = os.path.expanduser(args.blueprint.task_source) 90 if not os.path.exists(self.html_file): 91 raise FileNotFoundError( 92 f"Specified html file {self.html_file} was not found from {os.getcwd()}" 93 ) 94 95 self.onboarding_html_file = args.blueprint.get("onboarding_source", None) 96 if self.onboarding_html_file is not None: 97 self.onboarding_html_file = os.path.expanduser(self.onboarding_html_file) 98 if not os.path.exists(self.onboarding_html_file): 99 raise FileNotFoundError( 100 f"Specified onboarding html file {self.onboarding_html_file} was not found from {os.getcwd()}" 101 ) 102 103 task_file_name = os.path.basename(self.html_file) 104 for entry in self._initialization_data_dicts: 105 entry["html"] = task_file_name 106 107 @classmethod 108 def assert_task_args(cls, args: DictConfig, shared_state: "SharedTaskState"): 109 """Ensure that the data can be properly loaded""" 110 Blueprint.assert_task_args(args, shared_state) 111 blue_args = args.blueprint 112 if isinstance(shared_state.static_task_data, types.GeneratorType): 113 raise AssertionError("You can't launch an HTML static task on a generator") 114 if blue_args.get("data_csv", None) is not None: 115 csv_file = os.path.expanduser(blue_args.data_csv) 116 assert os.path.exists( 117 csv_file 118 ), f"Provided csv file {csv_file} doesn't exist" 119 elif blue_args.get("data_json", None) is not None: 120 json_file = os.path.expanduser(blue_args.data_json) 121 assert os.path.exists( 122 json_file 123 ), f"Provided JSON file {json_file} doesn't exist" 124 elif blue_args.get("data_jsonl", None) is not None: 125 jsonl_file = os.path.expanduser(blue_args.data_jsonl) 126 assert os.path.exists( 127 jsonl_file 128 ), f"Provided JSON-L file {jsonl_file} doesn't exist" 129 elif shared_state.static_task_data is not None: 130 assert ( 131 len(shared_state.static_task_data) > 0 132 ), "Length of data dict provided was 0" 133 else: 134 raise AssertionError( 135 "Must provide one of a data csv, json, json-L, or a list of tasks" 136 ) 137 138 if blue_args.get("onboarding_qualification", None) is not None: 139 assert blue_args.get("onboarding_source", None) is not None, ( 140 "Must use onboarding html with an onboarding qualification to " 141 "use onboarding." 142 ) 143 assert shared_state.validate_onboarding is not None, ( 144 "Must use an onboarding validation function to use onboarding " 145 "with static tasks." 146 ) 147 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py b/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py --- a/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py +++ b/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py @@ -10,6 +10,7 @@ ) from dataclasses import dataclass, field from omegaconf import MISSING, DictConfig +from mephisto.abstractions.blueprint import Blueprint from mephisto.abstractions.blueprints.static_html_task.static_html_task_builder import ( StaticHTMLTaskBuilder, )
{"golden_diff": "diff --git a/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py b/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py\n--- a/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py\n+++ b/mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py\n@@ -10,6 +10,7 @@\n )\n from dataclasses import dataclass, field\n from omegaconf import MISSING, DictConfig\n+from mephisto.abstractions.blueprint import Blueprint\n from mephisto.abstractions.blueprints.static_html_task.static_html_task_builder import (\n StaticHTMLTaskBuilder,\n )\n", "issue": "NameError: name 'Blueprint' is not defined\nHi!\r\n\r\nI wanted to try the project from the \"quickstart\" but I hit\r\n\r\n>NameError: name 'Blueprint' is not defined\r\n\r\nAfter running these steps:\r\n\r\n```bash\r\npip install -e .\r\nmkdir ~/data\r\nmephisto config core.main_data_directory ~/data\r\nmephisto check\r\n# OK\r\ncd examples/simple_static_task\r\npython static_test_script.py\r\n```\r\n\r\nAny idea? Seems to be related to Flask.\n", "before_files": [{"content": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom mephisto.abstractions.blueprints.abstract.static_task.static_blueprint import (\n StaticBlueprint,\n StaticBlueprintArgs,\n)\nfrom dataclasses import dataclass, field\nfrom omegaconf import MISSING, DictConfig\nfrom mephisto.abstractions.blueprints.static_html_task.static_html_task_builder import (\n StaticHTMLTaskBuilder,\n)\nfrom mephisto.operations.registry import register_mephisto_abstraction\n\nimport os\nimport time\nimport csv\nimport types\n\nfrom typing import ClassVar, List, Type, Any, Dict, Iterable, Optional, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from mephisto.data_model.task_run import TaskRun\n from mephisto.data_model.blueprint import (\n AgentState,\n TaskRunner,\n TaskBuilder,\n SharedTaskState,\n )\n from mephisto.data_model.assignment import Assignment\n from mephisto.data_model.agent import OnboardingAgent\n from mephisto.data_model.worker import Worker\n\nBLUEPRINT_TYPE = \"static_task\"\n\n\n@dataclass\nclass StaticHTMLBlueprintArgs(StaticBlueprintArgs):\n \"\"\"\n Adds required options for StaticBlueprints.\n task_source points to the file intending to be deployed for this task\n data_csv has the data to be deployed for this task.\n \"\"\"\n\n _blueprint_type: str = BLUEPRINT_TYPE\n _group: str = field(\n default=\"StaticBlueprint\",\n metadata={\n \"help\": (\n \"Tasks launched from static blueprints need a \"\n \"source html file to display to workers, as well as a csv \"\n \"containing values that will be inserted into templates in \"\n \"the html. \"\n )\n },\n )\n task_source: str = field(\n default=MISSING,\n metadata={\n \"help\": \"Path to source HTML file for the task being run\",\n \"required\": True,\n },\n )\n preview_source: Optional[str] = field(\n default=MISSING,\n metadata={\"help\": \"Optional path to source HTML file to preview the task\"},\n )\n onboarding_source: Optional[str] = field(\n default=MISSING,\n metadata={\"help\": \"Optional path to source HTML file to onboarding the task\"},\n )\n\n\n@register_mephisto_abstraction()\nclass StaticHTMLBlueprint(StaticBlueprint):\n \"\"\"Blueprint for a task that runs off of a built react javascript bundle\"\"\"\n\n TaskBuilderClass = StaticHTMLTaskBuilder\n ArgsClass = StaticHTMLBlueprintArgs\n BLUEPRINT_TYPE = BLUEPRINT_TYPE\n\n def __init__(\n self, task_run: \"TaskRun\", args: \"DictConfig\", shared_state: \"SharedTaskState\"\n ):\n super().__init__(task_run, args, shared_state)\n self.html_file = os.path.expanduser(args.blueprint.task_source)\n if not os.path.exists(self.html_file):\n raise FileNotFoundError(\n f\"Specified html file {self.html_file} was not found from {os.getcwd()}\"\n )\n\n self.onboarding_html_file = args.blueprint.get(\"onboarding_source\", None)\n if self.onboarding_html_file is not None:\n self.onboarding_html_file = os.path.expanduser(self.onboarding_html_file)\n if not os.path.exists(self.onboarding_html_file):\n raise FileNotFoundError(\n f\"Specified onboarding html file {self.onboarding_html_file} was not found from {os.getcwd()}\"\n )\n\n task_file_name = os.path.basename(self.html_file)\n for entry in self._initialization_data_dicts:\n entry[\"html\"] = task_file_name\n\n @classmethod\n def assert_task_args(cls, args: DictConfig, shared_state: \"SharedTaskState\"):\n \"\"\"Ensure that the data can be properly loaded\"\"\"\n Blueprint.assert_task_args(args, shared_state)\n blue_args = args.blueprint\n if isinstance(shared_state.static_task_data, types.GeneratorType):\n raise AssertionError(\"You can't launch an HTML static task on a generator\")\n if blue_args.get(\"data_csv\", None) is not None:\n csv_file = os.path.expanduser(blue_args.data_csv)\n assert os.path.exists(\n csv_file\n ), f\"Provided csv file {csv_file} doesn't exist\"\n elif blue_args.get(\"data_json\", None) is not None:\n json_file = os.path.expanduser(blue_args.data_json)\n assert os.path.exists(\n json_file\n ), f\"Provided JSON file {json_file} doesn't exist\"\n elif blue_args.get(\"data_jsonl\", None) is not None:\n jsonl_file = os.path.expanduser(blue_args.data_jsonl)\n assert os.path.exists(\n jsonl_file\n ), f\"Provided JSON-L file {jsonl_file} doesn't exist\"\n elif shared_state.static_task_data is not None:\n assert (\n len(shared_state.static_task_data) > 0\n ), \"Length of data dict provided was 0\"\n else:\n raise AssertionError(\n \"Must provide one of a data csv, json, json-L, or a list of tasks\"\n )\n\n if blue_args.get(\"onboarding_qualification\", None) is not None:\n assert blue_args.get(\"onboarding_source\", None) is not None, (\n \"Must use onboarding html with an onboarding qualification to \"\n \"use onboarding.\"\n )\n assert shared_state.validate_onboarding is not None, (\n \"Must use an onboarding validation function to use onboarding \"\n \"with static tasks.\"\n )\n", "path": "mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom mephisto.abstractions.blueprints.abstract.static_task.static_blueprint import (\n StaticBlueprint,\n StaticBlueprintArgs,\n)\nfrom dataclasses import dataclass, field\nfrom omegaconf import MISSING, DictConfig\nfrom mephisto.abstractions.blueprint import Blueprint\nfrom mephisto.abstractions.blueprints.static_html_task.static_html_task_builder import (\n StaticHTMLTaskBuilder,\n)\nfrom mephisto.operations.registry import register_mephisto_abstraction\n\nimport os\nimport time\nimport csv\nimport types\n\nfrom typing import ClassVar, List, Type, Any, Dict, Iterable, Optional, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from mephisto.data_model.task_run import TaskRun\n from mephisto.data_model.blueprint import (\n AgentState,\n TaskRunner,\n TaskBuilder,\n SharedTaskState,\n )\n from mephisto.data_model.assignment import Assignment\n from mephisto.data_model.agent import OnboardingAgent\n from mephisto.data_model.worker import Worker\n\nBLUEPRINT_TYPE = \"static_task\"\n\n\n@dataclass\nclass StaticHTMLBlueprintArgs(StaticBlueprintArgs):\n \"\"\"\n Adds required options for StaticBlueprints.\n task_source points to the file intending to be deployed for this task\n data_csv has the data to be deployed for this task.\n \"\"\"\n\n _blueprint_type: str = BLUEPRINT_TYPE\n _group: str = field(\n default=\"StaticBlueprint\",\n metadata={\n \"help\": (\n \"Tasks launched from static blueprints need a \"\n \"source html file to display to workers, as well as a csv \"\n \"containing values that will be inserted into templates in \"\n \"the html. \"\n )\n },\n )\n task_source: str = field(\n default=MISSING,\n metadata={\n \"help\": \"Path to source HTML file for the task being run\",\n \"required\": True,\n },\n )\n preview_source: Optional[str] = field(\n default=MISSING,\n metadata={\"help\": \"Optional path to source HTML file to preview the task\"},\n )\n onboarding_source: Optional[str] = field(\n default=MISSING,\n metadata={\"help\": \"Optional path to source HTML file to onboarding the task\"},\n )\n\n\n@register_mephisto_abstraction()\nclass StaticHTMLBlueprint(StaticBlueprint):\n \"\"\"Blueprint for a task that runs off of a built react javascript bundle\"\"\"\n\n TaskBuilderClass = StaticHTMLTaskBuilder\n ArgsClass = StaticHTMLBlueprintArgs\n BLUEPRINT_TYPE = BLUEPRINT_TYPE\n\n def __init__(\n self, task_run: \"TaskRun\", args: \"DictConfig\", shared_state: \"SharedTaskState\"\n ):\n super().__init__(task_run, args, shared_state)\n self.html_file = os.path.expanduser(args.blueprint.task_source)\n if not os.path.exists(self.html_file):\n raise FileNotFoundError(\n f\"Specified html file {self.html_file} was not found from {os.getcwd()}\"\n )\n\n self.onboarding_html_file = args.blueprint.get(\"onboarding_source\", None)\n if self.onboarding_html_file is not None:\n self.onboarding_html_file = os.path.expanduser(self.onboarding_html_file)\n if not os.path.exists(self.onboarding_html_file):\n raise FileNotFoundError(\n f\"Specified onboarding html file {self.onboarding_html_file} was not found from {os.getcwd()}\"\n )\n\n task_file_name = os.path.basename(self.html_file)\n for entry in self._initialization_data_dicts:\n entry[\"html\"] = task_file_name\n\n @classmethod\n def assert_task_args(cls, args: DictConfig, shared_state: \"SharedTaskState\"):\n \"\"\"Ensure that the data can be properly loaded\"\"\"\n Blueprint.assert_task_args(args, shared_state)\n blue_args = args.blueprint\n if isinstance(shared_state.static_task_data, types.GeneratorType):\n raise AssertionError(\"You can't launch an HTML static task on a generator\")\n if blue_args.get(\"data_csv\", None) is not None:\n csv_file = os.path.expanduser(blue_args.data_csv)\n assert os.path.exists(\n csv_file\n ), f\"Provided csv file {csv_file} doesn't exist\"\n elif blue_args.get(\"data_json\", None) is not None:\n json_file = os.path.expanduser(blue_args.data_json)\n assert os.path.exists(\n json_file\n ), f\"Provided JSON file {json_file} doesn't exist\"\n elif blue_args.get(\"data_jsonl\", None) is not None:\n jsonl_file = os.path.expanduser(blue_args.data_jsonl)\n assert os.path.exists(\n jsonl_file\n ), f\"Provided JSON-L file {jsonl_file} doesn't exist\"\n elif shared_state.static_task_data is not None:\n assert (\n len(shared_state.static_task_data) > 0\n ), \"Length of data dict provided was 0\"\n else:\n raise AssertionError(\n \"Must provide one of a data csv, json, json-L, or a list of tasks\"\n )\n\n if blue_args.get(\"onboarding_qualification\", None) is not None:\n assert blue_args.get(\"onboarding_source\", None) is not None, (\n \"Must use onboarding html with an onboarding qualification to \"\n \"use onboarding.\"\n )\n assert shared_state.validate_onboarding is not None, (\n \"Must use an onboarding validation function to use onboarding \"\n \"with static tasks.\"\n )\n", "path": "mephisto/abstractions/blueprints/static_html_task/static_html_blueprint.py"}]}
1,932
145
gh_patches_debug_31256
rasdani/github-patches
git_diff
open-mmlab__mmdetection-3529
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- ModuleNotFoundError: No module named 'tools' i would like to test the result of training, so i write the next: (base) zhangshen@zhangshen-X550JX:~/mmdetection$ python tools/test.py configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth --out./result/result_100/pkl --eval bbox but i got: Traceback (most recent call last): File "tools/test.py", line 9, in <module> from tools.fuse_conv_bn import fuse_module ModuleNotFoundError: No module named 'tools' how can i solve this problem? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `tools/fuse_conv_bn.py` Content: ``` 1 import argparse 2 3 import torch 4 import torch.nn as nn 5 from mmcv.runner import save_checkpoint 6 7 from mmdet.apis import init_detector 8 9 10 def fuse_conv_bn(conv, bn): 11 """During inference, the functionary of batch norm layers is turned off but 12 only the mean and var alone channels are used, which exposes the chance to 13 fuse it with the preceding conv layers to save computations and simplify 14 network structures.""" 15 conv_w = conv.weight 16 conv_b = conv.bias if conv.bias is not None else torch.zeros_like( 17 bn.running_mean) 18 19 factor = bn.weight / torch.sqrt(bn.running_var + bn.eps) 20 conv.weight = nn.Parameter(conv_w * 21 factor.reshape([conv.out_channels, 1, 1, 1])) 22 conv.bias = nn.Parameter((conv_b - bn.running_mean) * factor + bn.bias) 23 return conv 24 25 26 def fuse_module(m): 27 last_conv = None 28 last_conv_name = None 29 30 for name, child in m.named_children(): 31 if isinstance(child, (nn.BatchNorm2d, nn.SyncBatchNorm)): 32 if last_conv is None: # only fuse BN that is after Conv 33 continue 34 fused_conv = fuse_conv_bn(last_conv, child) 35 m._modules[last_conv_name] = fused_conv 36 # To reduce changes, set BN as Identity instead of deleting it. 37 m._modules[name] = nn.Identity() 38 last_conv = None 39 elif isinstance(child, nn.Conv2d): 40 last_conv = child 41 last_conv_name = name 42 else: 43 fuse_module(child) 44 return m 45 46 47 def parse_args(): 48 parser = argparse.ArgumentParser( 49 description='fuse Conv and BN layers in a model') 50 parser.add_argument('config', help='config file path') 51 parser.add_argument('checkpoint', help='checkpoint file path') 52 parser.add_argument('out', help='output path of the converted model') 53 args = parser.parse_args() 54 return args 55 56 57 def main(): 58 args = parse_args() 59 # build the model from a config file and a checkpoint file 60 model = init_detector(args.config, args.checkpoint) 61 # fuse conv and bn layers of the model 62 fused_model = fuse_module(model) 63 save_checkpoint(fused_model, args.out) 64 65 66 if __name__ == '__main__': 67 main() 68 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/tools/fuse_conv_bn.py b/tools/fuse_conv_bn.py deleted file mode 100644 --- a/tools/fuse_conv_bn.py +++ /dev/null @@ -1,67 +0,0 @@ -import argparse - -import torch -import torch.nn as nn -from mmcv.runner import save_checkpoint - -from mmdet.apis import init_detector - - -def fuse_conv_bn(conv, bn): - """During inference, the functionary of batch norm layers is turned off but - only the mean and var alone channels are used, which exposes the chance to - fuse it with the preceding conv layers to save computations and simplify - network structures.""" - conv_w = conv.weight - conv_b = conv.bias if conv.bias is not None else torch.zeros_like( - bn.running_mean) - - factor = bn.weight / torch.sqrt(bn.running_var + bn.eps) - conv.weight = nn.Parameter(conv_w * - factor.reshape([conv.out_channels, 1, 1, 1])) - conv.bias = nn.Parameter((conv_b - bn.running_mean) * factor + bn.bias) - return conv - - -def fuse_module(m): - last_conv = None - last_conv_name = None - - for name, child in m.named_children(): - if isinstance(child, (nn.BatchNorm2d, nn.SyncBatchNorm)): - if last_conv is None: # only fuse BN that is after Conv - continue - fused_conv = fuse_conv_bn(last_conv, child) - m._modules[last_conv_name] = fused_conv - # To reduce changes, set BN as Identity instead of deleting it. - m._modules[name] = nn.Identity() - last_conv = None - elif isinstance(child, nn.Conv2d): - last_conv = child - last_conv_name = name - else: - fuse_module(child) - return m - - -def parse_args(): - parser = argparse.ArgumentParser( - description='fuse Conv and BN layers in a model') - parser.add_argument('config', help='config file path') - parser.add_argument('checkpoint', help='checkpoint file path') - parser.add_argument('out', help='output path of the converted model') - args = parser.parse_args() - return args - - -def main(): - args = parse_args() - # build the model from a config file and a checkpoint file - model = init_detector(args.config, args.checkpoint) - # fuse conv and bn layers of the model - fused_model = fuse_module(model) - save_checkpoint(fused_model, args.out) - - -if __name__ == '__main__': - main()
{"golden_diff": "diff --git a/tools/fuse_conv_bn.py b/tools/fuse_conv_bn.py\ndeleted file mode 100644\n--- a/tools/fuse_conv_bn.py\n+++ /dev/null\n@@ -1,67 +0,0 @@\n-import argparse\n-\n-import torch\n-import torch.nn as nn\n-from mmcv.runner import save_checkpoint\n-\n-from mmdet.apis import init_detector\n-\n-\n-def fuse_conv_bn(conv, bn):\n- \"\"\"During inference, the functionary of batch norm layers is turned off but\n- only the mean and var alone channels are used, which exposes the chance to\n- fuse it with the preceding conv layers to save computations and simplify\n- network structures.\"\"\"\n- conv_w = conv.weight\n- conv_b = conv.bias if conv.bias is not None else torch.zeros_like(\n- bn.running_mean)\n-\n- factor = bn.weight / torch.sqrt(bn.running_var + bn.eps)\n- conv.weight = nn.Parameter(conv_w *\n- factor.reshape([conv.out_channels, 1, 1, 1]))\n- conv.bias = nn.Parameter((conv_b - bn.running_mean) * factor + bn.bias)\n- return conv\n-\n-\n-def fuse_module(m):\n- last_conv = None\n- last_conv_name = None\n-\n- for name, child in m.named_children():\n- if isinstance(child, (nn.BatchNorm2d, nn.SyncBatchNorm)):\n- if last_conv is None: # only fuse BN that is after Conv\n- continue\n- fused_conv = fuse_conv_bn(last_conv, child)\n- m._modules[last_conv_name] = fused_conv\n- # To reduce changes, set BN as Identity instead of deleting it.\n- m._modules[name] = nn.Identity()\n- last_conv = None\n- elif isinstance(child, nn.Conv2d):\n- last_conv = child\n- last_conv_name = name\n- else:\n- fuse_module(child)\n- return m\n-\n-\n-def parse_args():\n- parser = argparse.ArgumentParser(\n- description='fuse Conv and BN layers in a model')\n- parser.add_argument('config', help='config file path')\n- parser.add_argument('checkpoint', help='checkpoint file path')\n- parser.add_argument('out', help='output path of the converted model')\n- args = parser.parse_args()\n- return args\n-\n-\n-def main():\n- args = parse_args()\n- # build the model from a config file and a checkpoint file\n- model = init_detector(args.config, args.checkpoint)\n- # fuse conv and bn layers of the model\n- fused_model = fuse_module(model)\n- save_checkpoint(fused_model, args.out)\n-\n-\n-if __name__ == '__main__':\n- main()\n", "issue": "ModuleNotFoundError: No module named 'tools'\n i would like to test the result of training, so i write the next:\r\n(base) zhangshen@zhangshen-X550JX:~/mmdetection$ python tools/test.py configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth --out./result/result_100/pkl --eval bbox\r\n\r\nbut i got:\r\nTraceback (most recent call last):\r\n File \"tools/test.py\", line 9, in <module>\r\n from tools.fuse_conv_bn import fuse_module\r\nModuleNotFoundError: No module named 'tools'\r\n\r\nhow can i solve this problem?\n", "before_files": [{"content": "import argparse\n\nimport torch\nimport torch.nn as nn\nfrom mmcv.runner import save_checkpoint\n\nfrom mmdet.apis import init_detector\n\n\ndef fuse_conv_bn(conv, bn):\n \"\"\"During inference, the functionary of batch norm layers is turned off but\n only the mean and var alone channels are used, which exposes the chance to\n fuse it with the preceding conv layers to save computations and simplify\n network structures.\"\"\"\n conv_w = conv.weight\n conv_b = conv.bias if conv.bias is not None else torch.zeros_like(\n bn.running_mean)\n\n factor = bn.weight / torch.sqrt(bn.running_var + bn.eps)\n conv.weight = nn.Parameter(conv_w *\n factor.reshape([conv.out_channels, 1, 1, 1]))\n conv.bias = nn.Parameter((conv_b - bn.running_mean) * factor + bn.bias)\n return conv\n\n\ndef fuse_module(m):\n last_conv = None\n last_conv_name = None\n\n for name, child in m.named_children():\n if isinstance(child, (nn.BatchNorm2d, nn.SyncBatchNorm)):\n if last_conv is None: # only fuse BN that is after Conv\n continue\n fused_conv = fuse_conv_bn(last_conv, child)\n m._modules[last_conv_name] = fused_conv\n # To reduce changes, set BN as Identity instead of deleting it.\n m._modules[name] = nn.Identity()\n last_conv = None\n elif isinstance(child, nn.Conv2d):\n last_conv = child\n last_conv_name = name\n else:\n fuse_module(child)\n return m\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='fuse Conv and BN layers in a model')\n parser.add_argument('config', help='config file path')\n parser.add_argument('checkpoint', help='checkpoint file path')\n parser.add_argument('out', help='output path of the converted model')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n # build the model from a config file and a checkpoint file\n model = init_detector(args.config, args.checkpoint)\n # fuse conv and bn layers of the model\n fused_model = fuse_module(model)\n save_checkpoint(fused_model, args.out)\n\n\nif __name__ == '__main__':\n main()\n", "path": "tools/fuse_conv_bn.py"}], "after_files": [{"content": null, "path": "tools/fuse_conv_bn.py"}]}
1,065
600
gh_patches_debug_21808
rasdani/github-patches
git_diff
nonebot__nonebot2-1720
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Feature: 替换 toml 读取方式 在 python 3.11 中已经支持了读取 toml 配置。https://docs.python.org/3/library/tomllib.html --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `nonebot/plugin/load.py` Content: ``` 1 """本模块定义插件加载接口。 2 3 FrontMatter: 4 sidebar_position: 1 5 description: nonebot.plugin.load 模块 6 """ 7 import json 8 from pathlib import Path 9 from types import ModuleType 10 from typing import Set, Union, Iterable, Optional 11 12 import tomlkit 13 14 from nonebot.utils import path_to_module_name 15 16 from .plugin import Plugin 17 from .manager import PluginManager 18 from . import _managers, get_plugin, _module_name_to_plugin_name 19 20 21 def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: 22 """加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 23 24 参数: 25 module_path: 插件名称 `path.to.your.plugin` 或插件路径 `pathlib.Path(path/to/your/plugin)` 26 """ 27 module_path = ( 28 path_to_module_name(module_path) 29 if isinstance(module_path, Path) 30 else module_path 31 ) 32 manager = PluginManager([module_path]) 33 _managers.append(manager) 34 return manager.load_plugin(module_path) 35 36 37 def load_plugins(*plugin_dir: str) -> Set[Plugin]: 38 """导入文件夹下多个插件,以 `_` 开头的插件不会被导入! 39 40 参数: 41 plugin_dir: 文件夹路径 42 """ 43 manager = PluginManager(search_path=plugin_dir) 44 _managers.append(manager) 45 return manager.load_all_plugins() 46 47 48 def load_all_plugins( 49 module_path: Iterable[str], plugin_dir: Iterable[str] 50 ) -> Set[Plugin]: 51 """导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入! 52 53 参数: 54 module_path: 指定插件集合 55 plugin_dir: 指定文件夹路径集合 56 """ 57 manager = PluginManager(module_path, plugin_dir) 58 _managers.append(manager) 59 return manager.load_all_plugins() 60 61 62 def load_from_json(file_path: str, encoding: str = "utf-8") -> Set[Plugin]: 63 """导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入! 64 65 参数: 66 file_path: 指定 json 文件路径 67 encoding: 指定 json 文件编码 68 69 用法: 70 ```json title=plugins.json 71 { 72 "plugins": ["some_plugin"], 73 "plugin_dirs": ["some_dir"] 74 } 75 ``` 76 77 ```python 78 nonebot.load_from_json("plugins.json") 79 ``` 80 """ 81 with open(file_path, "r", encoding=encoding) as f: 82 data = json.load(f) 83 if not isinstance(data, dict): 84 raise TypeError("json file must contains a dict!") 85 plugins = data.get("plugins") 86 plugin_dirs = data.get("plugin_dirs") 87 assert isinstance(plugins, list), "plugins must be a list of plugin name" 88 assert isinstance(plugin_dirs, list), "plugin_dirs must be a list of directories" 89 return load_all_plugins(set(plugins), set(plugin_dirs)) 90 91 92 def load_from_toml(file_path: str, encoding: str = "utf-8") -> Set[Plugin]: 93 """导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入! 94 95 参数: 96 file_path: 指定 toml 文件路径 97 encoding: 指定 toml 文件编码 98 99 用法: 100 ```toml title=pyproject.toml 101 [tool.nonebot] 102 plugins = ["some_plugin"] 103 plugin_dirs = ["some_dir"] 104 ``` 105 106 ```python 107 nonebot.load_from_toml("pyproject.toml") 108 ``` 109 """ 110 with open(file_path, "r", encoding=encoding) as f: 111 data = tomlkit.parse(f.read()) # type: ignore 112 113 nonebot_data = data.get("tool", {}).get("nonebot") 114 if nonebot_data is None: 115 raise ValueError("Cannot find '[tool.nonebot]' in given toml file!") 116 if not isinstance(nonebot_data, dict): 117 raise TypeError("'[tool.nonebot]' must be a Table!") 118 plugins = nonebot_data.get("plugins", []) 119 plugin_dirs = nonebot_data.get("plugin_dirs", []) 120 assert isinstance(plugins, list), "plugins must be a list of plugin name" 121 assert isinstance(plugin_dirs, list), "plugin_dirs must be a list of directories" 122 return load_all_plugins(plugins, plugin_dirs) 123 124 125 def load_builtin_plugin(name: str) -> Optional[Plugin]: 126 """导入 NoneBot 内置插件。 127 128 参数: 129 name: 插件名称 130 """ 131 return load_plugin(f"nonebot.plugins.{name}") 132 133 134 def load_builtin_plugins(*plugins: str) -> Set[Plugin]: 135 """导入多个 NoneBot 内置插件。 136 137 参数: 138 plugins: 插件名称列表 139 """ 140 return load_all_plugins([f"nonebot.plugins.{p}" for p in plugins], []) 141 142 143 def _find_manager_by_name(name: str) -> Optional[PluginManager]: 144 for manager in reversed(_managers): 145 if name in manager.plugins or name in manager.searched_plugins: 146 return manager 147 148 149 def require(name: str) -> ModuleType: 150 """获取一个插件的导出内容。 151 152 如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。 153 154 参数: 155 name: 插件名,即 {ref}`nonebot.plugin.plugin.Plugin.name`。 156 157 异常: 158 RuntimeError: 插件无法加载 159 """ 160 plugin = get_plugin(_module_name_to_plugin_name(name)) 161 if not plugin: 162 if manager := _find_manager_by_name(name): 163 plugin = manager.load_plugin(name) 164 else: 165 plugin = load_plugin(name) 166 if not plugin: 167 raise RuntimeError(f'Cannot load plugin "{name}"!') 168 return plugin.module 169 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/nonebot/plugin/load.py b/nonebot/plugin/load.py --- a/nonebot/plugin/load.py +++ b/nonebot/plugin/load.py @@ -9,14 +9,17 @@ from types import ModuleType from typing import Set, Union, Iterable, Optional -import tomlkit - from nonebot.utils import path_to_module_name from .plugin import Plugin from .manager import PluginManager from . import _managers, get_plugin, _module_name_to_plugin_name +try: + import tomllib # pyright: reportMissingImports=false +except ModuleNotFoundError: + import tomli as tomllib + def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: """加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 @@ -108,7 +111,7 @@ ``` """ with open(file_path, "r", encoding=encoding) as f: - data = tomlkit.parse(f.read()) # type: ignore + data = tomllib.loads(f.read()) nonebot_data = data.get("tool", {}).get("nonebot") if nonebot_data is None:
{"golden_diff": "diff --git a/nonebot/plugin/load.py b/nonebot/plugin/load.py\n--- a/nonebot/plugin/load.py\n+++ b/nonebot/plugin/load.py\n@@ -9,14 +9,17 @@\n from types import ModuleType\n from typing import Set, Union, Iterable, Optional\n \n-import tomlkit\n-\n from nonebot.utils import path_to_module_name\n \n from .plugin import Plugin\n from .manager import PluginManager\n from . import _managers, get_plugin, _module_name_to_plugin_name\n \n+try:\n+ import tomllib # pyright: reportMissingImports=false\n+except ModuleNotFoundError:\n+ import tomli as tomllib\n+\n \n def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:\n \"\"\"\u52a0\u8f7d\u5355\u4e2a\u63d2\u4ef6\uff0c\u53ef\u4ee5\u662f\u672c\u5730\u63d2\u4ef6\u6216\u662f\u901a\u8fc7 `pip` \u5b89\u88c5\u7684\u63d2\u4ef6\u3002\n@@ -108,7 +111,7 @@\n ```\n \"\"\"\n with open(file_path, \"r\", encoding=encoding) as f:\n- data = tomlkit.parse(f.read()) # type: ignore\n+ data = tomllib.loads(f.read())\n \n nonebot_data = data.get(\"tool\", {}).get(\"nonebot\")\n if nonebot_data is None:\n", "issue": "Feature: \u66ff\u6362 toml \u8bfb\u53d6\u65b9\u5f0f\n\u5728 python 3.11 \u4e2d\u5df2\u7ecf\u652f\u6301\u4e86\u8bfb\u53d6 toml \u914d\u7f6e\u3002https://docs.python.org/3/library/tomllib.html\n", "before_files": [{"content": "\"\"\"\u672c\u6a21\u5757\u5b9a\u4e49\u63d2\u4ef6\u52a0\u8f7d\u63a5\u53e3\u3002\n\nFrontMatter:\n sidebar_position: 1\n description: nonebot.plugin.load \u6a21\u5757\n\"\"\"\nimport json\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import Set, Union, Iterable, Optional\n\nimport tomlkit\n\nfrom nonebot.utils import path_to_module_name\n\nfrom .plugin import Plugin\nfrom .manager import PluginManager\nfrom . import _managers, get_plugin, _module_name_to_plugin_name\n\n\ndef load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:\n \"\"\"\u52a0\u8f7d\u5355\u4e2a\u63d2\u4ef6\uff0c\u53ef\u4ee5\u662f\u672c\u5730\u63d2\u4ef6\u6216\u662f\u901a\u8fc7 `pip` \u5b89\u88c5\u7684\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n module_path: \u63d2\u4ef6\u540d\u79f0 `path.to.your.plugin` \u6216\u63d2\u4ef6\u8def\u5f84 `pathlib.Path(path/to/your/plugin)`\n \"\"\"\n module_path = (\n path_to_module_name(module_path)\n if isinstance(module_path, Path)\n else module_path\n )\n manager = PluginManager([module_path])\n _managers.append(manager)\n return manager.load_plugin(module_path)\n\n\ndef load_plugins(*plugin_dir: str) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6587\u4ef6\u5939\u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n plugin_dir: \u6587\u4ef6\u5939\u8def\u5f84\n \"\"\"\n manager = PluginManager(search_path=plugin_dir)\n _managers.append(manager)\n return manager.load_all_plugins()\n\n\ndef load_all_plugins(\n module_path: Iterable[str], plugin_dir: Iterable[str]\n) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a\u5217\u8868\u4e2d\u7684\u63d2\u4ef6\u4ee5\u53ca\u6307\u5b9a\u76ee\u5f55\u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n module_path: \u6307\u5b9a\u63d2\u4ef6\u96c6\u5408\n plugin_dir: \u6307\u5b9a\u6587\u4ef6\u5939\u8def\u5f84\u96c6\u5408\n \"\"\"\n manager = PluginManager(module_path, plugin_dir)\n _managers.append(manager)\n return manager.load_all_plugins()\n\n\ndef load_from_json(file_path: str, encoding: str = \"utf-8\") -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a json \u6587\u4ef6\u4e2d\u7684 `plugins` \u4ee5\u53ca `plugin_dirs` \u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n file_path: \u6307\u5b9a json \u6587\u4ef6\u8def\u5f84\n encoding: \u6307\u5b9a json \u6587\u4ef6\u7f16\u7801\n\n \u7528\u6cd5:\n ```json title=plugins.json\n {\n \"plugins\": [\"some_plugin\"],\n \"plugin_dirs\": [\"some_dir\"]\n }\n ```\n\n ```python\n nonebot.load_from_json(\"plugins.json\")\n ```\n \"\"\"\n with open(file_path, \"r\", encoding=encoding) as f:\n data = json.load(f)\n if not isinstance(data, dict):\n raise TypeError(\"json file must contains a dict!\")\n plugins = data.get(\"plugins\")\n plugin_dirs = data.get(\"plugin_dirs\")\n assert isinstance(plugins, list), \"plugins must be a list of plugin name\"\n assert isinstance(plugin_dirs, list), \"plugin_dirs must be a list of directories\"\n return load_all_plugins(set(plugins), set(plugin_dirs))\n\n\ndef load_from_toml(file_path: str, encoding: str = \"utf-8\") -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a toml \u6587\u4ef6 `[tool.nonebot]` \u4e2d\u7684 `plugins` \u4ee5\u53ca `plugin_dirs` \u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n file_path: \u6307\u5b9a toml \u6587\u4ef6\u8def\u5f84\n encoding: \u6307\u5b9a toml \u6587\u4ef6\u7f16\u7801\n\n \u7528\u6cd5:\n ```toml title=pyproject.toml\n [tool.nonebot]\n plugins = [\"some_plugin\"]\n plugin_dirs = [\"some_dir\"]\n ```\n\n ```python\n nonebot.load_from_toml(\"pyproject.toml\")\n ```\n \"\"\"\n with open(file_path, \"r\", encoding=encoding) as f:\n data = tomlkit.parse(f.read()) # type: ignore\n\n nonebot_data = data.get(\"tool\", {}).get(\"nonebot\")\n if nonebot_data is None:\n raise ValueError(\"Cannot find '[tool.nonebot]' in given toml file!\")\n if not isinstance(nonebot_data, dict):\n raise TypeError(\"'[tool.nonebot]' must be a Table!\")\n plugins = nonebot_data.get(\"plugins\", [])\n plugin_dirs = nonebot_data.get(\"plugin_dirs\", [])\n assert isinstance(plugins, list), \"plugins must be a list of plugin name\"\n assert isinstance(plugin_dirs, list), \"plugin_dirs must be a list of directories\"\n return load_all_plugins(plugins, plugin_dirs)\n\n\ndef load_builtin_plugin(name: str) -> Optional[Plugin]:\n \"\"\"\u5bfc\u5165 NoneBot \u5185\u7f6e\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n name: \u63d2\u4ef6\u540d\u79f0\n \"\"\"\n return load_plugin(f\"nonebot.plugins.{name}\")\n\n\ndef load_builtin_plugins(*plugins: str) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u591a\u4e2a NoneBot \u5185\u7f6e\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n plugins: \u63d2\u4ef6\u540d\u79f0\u5217\u8868\n \"\"\"\n return load_all_plugins([f\"nonebot.plugins.{p}\" for p in plugins], [])\n\n\ndef _find_manager_by_name(name: str) -> Optional[PluginManager]:\n for manager in reversed(_managers):\n if name in manager.plugins or name in manager.searched_plugins:\n return manager\n\n\ndef require(name: str) -> ModuleType:\n \"\"\"\u83b7\u53d6\u4e00\u4e2a\u63d2\u4ef6\u7684\u5bfc\u51fa\u5185\u5bb9\u3002\n\n \u5982\u679c\u4e3a `load_plugins` \u6587\u4ef6\u5939\u5bfc\u5165\u7684\u63d2\u4ef6\uff0c\u5219\u4e3a\u6587\u4ef6(\u5939)\u540d\u3002\n\n \u53c2\u6570:\n name: \u63d2\u4ef6\u540d\uff0c\u5373 {ref}`nonebot.plugin.plugin.Plugin.name`\u3002\n\n \u5f02\u5e38:\n RuntimeError: \u63d2\u4ef6\u65e0\u6cd5\u52a0\u8f7d\n \"\"\"\n plugin = get_plugin(_module_name_to_plugin_name(name))\n if not plugin:\n if manager := _find_manager_by_name(name):\n plugin = manager.load_plugin(name)\n else:\n plugin = load_plugin(name)\n if not plugin:\n raise RuntimeError(f'Cannot load plugin \"{name}\"!')\n return plugin.module\n", "path": "nonebot/plugin/load.py"}], "after_files": [{"content": "\"\"\"\u672c\u6a21\u5757\u5b9a\u4e49\u63d2\u4ef6\u52a0\u8f7d\u63a5\u53e3\u3002\n\nFrontMatter:\n sidebar_position: 1\n description: nonebot.plugin.load \u6a21\u5757\n\"\"\"\nimport json\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import Set, Union, Iterable, Optional\n\nfrom nonebot.utils import path_to_module_name\n\nfrom .plugin import Plugin\nfrom .manager import PluginManager\nfrom . import _managers, get_plugin, _module_name_to_plugin_name\n\ntry:\n import tomllib # pyright: reportMissingImports=false\nexcept ModuleNotFoundError:\n import tomli as tomllib\n\n\ndef load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:\n \"\"\"\u52a0\u8f7d\u5355\u4e2a\u63d2\u4ef6\uff0c\u53ef\u4ee5\u662f\u672c\u5730\u63d2\u4ef6\u6216\u662f\u901a\u8fc7 `pip` \u5b89\u88c5\u7684\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n module_path: \u63d2\u4ef6\u540d\u79f0 `path.to.your.plugin` \u6216\u63d2\u4ef6\u8def\u5f84 `pathlib.Path(path/to/your/plugin)`\n \"\"\"\n module_path = (\n path_to_module_name(module_path)\n if isinstance(module_path, Path)\n else module_path\n )\n manager = PluginManager([module_path])\n _managers.append(manager)\n return manager.load_plugin(module_path)\n\n\ndef load_plugins(*plugin_dir: str) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6587\u4ef6\u5939\u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n plugin_dir: \u6587\u4ef6\u5939\u8def\u5f84\n \"\"\"\n manager = PluginManager(search_path=plugin_dir)\n _managers.append(manager)\n return manager.load_all_plugins()\n\n\ndef load_all_plugins(\n module_path: Iterable[str], plugin_dir: Iterable[str]\n) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a\u5217\u8868\u4e2d\u7684\u63d2\u4ef6\u4ee5\u53ca\u6307\u5b9a\u76ee\u5f55\u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n module_path: \u6307\u5b9a\u63d2\u4ef6\u96c6\u5408\n plugin_dir: \u6307\u5b9a\u6587\u4ef6\u5939\u8def\u5f84\u96c6\u5408\n \"\"\"\n manager = PluginManager(module_path, plugin_dir)\n _managers.append(manager)\n return manager.load_all_plugins()\n\n\ndef load_from_json(file_path: str, encoding: str = \"utf-8\") -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a json \u6587\u4ef6\u4e2d\u7684 `plugins` \u4ee5\u53ca `plugin_dirs` \u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n file_path: \u6307\u5b9a json \u6587\u4ef6\u8def\u5f84\n encoding: \u6307\u5b9a json \u6587\u4ef6\u7f16\u7801\n\n \u7528\u6cd5:\n ```json title=plugins.json\n {\n \"plugins\": [\"some_plugin\"],\n \"plugin_dirs\": [\"some_dir\"]\n }\n ```\n\n ```python\n nonebot.load_from_json(\"plugins.json\")\n ```\n \"\"\"\n with open(file_path, \"r\", encoding=encoding) as f:\n data = json.load(f)\n if not isinstance(data, dict):\n raise TypeError(\"json file must contains a dict!\")\n plugins = data.get(\"plugins\")\n plugin_dirs = data.get(\"plugin_dirs\")\n assert isinstance(plugins, list), \"plugins must be a list of plugin name\"\n assert isinstance(plugin_dirs, list), \"plugin_dirs must be a list of directories\"\n return load_all_plugins(set(plugins), set(plugin_dirs))\n\n\ndef load_from_toml(file_path: str, encoding: str = \"utf-8\") -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u6307\u5b9a toml \u6587\u4ef6 `[tool.nonebot]` \u4e2d\u7684 `plugins` \u4ee5\u53ca `plugin_dirs` \u4e0b\u591a\u4e2a\u63d2\u4ef6\uff0c\u4ee5 `_` \u5f00\u5934\u7684\u63d2\u4ef6\u4e0d\u4f1a\u88ab\u5bfc\u5165!\n\n \u53c2\u6570:\n file_path: \u6307\u5b9a toml \u6587\u4ef6\u8def\u5f84\n encoding: \u6307\u5b9a toml \u6587\u4ef6\u7f16\u7801\n\n \u7528\u6cd5:\n ```toml title=pyproject.toml\n [tool.nonebot]\n plugins = [\"some_plugin\"]\n plugin_dirs = [\"some_dir\"]\n ```\n\n ```python\n nonebot.load_from_toml(\"pyproject.toml\")\n ```\n \"\"\"\n with open(file_path, \"r\", encoding=encoding) as f:\n data = tomllib.loads(f.read())\n\n nonebot_data = data.get(\"tool\", {}).get(\"nonebot\")\n if nonebot_data is None:\n raise ValueError(\"Cannot find '[tool.nonebot]' in given toml file!\")\n if not isinstance(nonebot_data, dict):\n raise TypeError(\"'[tool.nonebot]' must be a Table!\")\n plugins = nonebot_data.get(\"plugins\", [])\n plugin_dirs = nonebot_data.get(\"plugin_dirs\", [])\n assert isinstance(plugins, list), \"plugins must be a list of plugin name\"\n assert isinstance(plugin_dirs, list), \"plugin_dirs must be a list of directories\"\n return load_all_plugins(plugins, plugin_dirs)\n\n\ndef load_builtin_plugin(name: str) -> Optional[Plugin]:\n \"\"\"\u5bfc\u5165 NoneBot \u5185\u7f6e\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n name: \u63d2\u4ef6\u540d\u79f0\n \"\"\"\n return load_plugin(f\"nonebot.plugins.{name}\")\n\n\ndef load_builtin_plugins(*plugins: str) -> Set[Plugin]:\n \"\"\"\u5bfc\u5165\u591a\u4e2a NoneBot \u5185\u7f6e\u63d2\u4ef6\u3002\n\n \u53c2\u6570:\n plugins: \u63d2\u4ef6\u540d\u79f0\u5217\u8868\n \"\"\"\n return load_all_plugins([f\"nonebot.plugins.{p}\" for p in plugins], [])\n\n\ndef _find_manager_by_name(name: str) -> Optional[PluginManager]:\n for manager in reversed(_managers):\n if name in manager.plugins or name in manager.searched_plugins:\n return manager\n\n\ndef require(name: str) -> ModuleType:\n \"\"\"\u83b7\u53d6\u4e00\u4e2a\u63d2\u4ef6\u7684\u5bfc\u51fa\u5185\u5bb9\u3002\n\n \u5982\u679c\u4e3a `load_plugins` \u6587\u4ef6\u5939\u5bfc\u5165\u7684\u63d2\u4ef6\uff0c\u5219\u4e3a\u6587\u4ef6(\u5939)\u540d\u3002\n\n \u53c2\u6570:\n name: \u63d2\u4ef6\u540d\uff0c\u5373 {ref}`nonebot.plugin.plugin.Plugin.name`\u3002\n\n \u5f02\u5e38:\n RuntimeError: \u63d2\u4ef6\u65e0\u6cd5\u52a0\u8f7d\n \"\"\"\n plugin = get_plugin(_module_name_to_plugin_name(name))\n if not plugin:\n if manager := _find_manager_by_name(name):\n plugin = manager.load_plugin(name)\n else:\n plugin = load_plugin(name)\n if not plugin:\n raise RuntimeError(f'Cannot load plugin \"{name}\"!')\n return plugin.module\n", "path": "nonebot/plugin/load.py"}]}
2,020
272
gh_patches_debug_25092
rasdani/github-patches
git_diff
jupyterhub__jupyterhub-1413
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Fractional memory / CPU limits / guarantees fail **How to reproduce the issue** Set memory limit (or guarantee, or cpu limit / guarantee) to a non-integral spec: ```python c.Spawner.mem_limit = "1.5G" ``` **What you expected to happen** (In supported spawners) memory limit is set to 1.5 gigabytes of RAM **What actually happens** JupyterHub refuses to start, with: ``` [E 2017-04-18 05:39:02.270 JupyterHub app:1527] Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1524, in launch_instance_async yield self.initialize(argv) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1315, in initialize yield self.init_spawners() File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1084, in init_spawners self.users[orm_user.id] = user = User(orm_user, self.tornado_settings) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/user.py", line 128, in __init__ config=self.settings.get('config'), File "/usr/local/lib/python3.4/dist-packages/kubespawner/spawner.py", line 29, in __init__ super().__init__(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/spawner.py", line 345, in __init__ super(Spawner, self).__init__(**kwargs) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 84, in __init__ self.config = config File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 585, in __set__ self.set(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 574, in set obj._notify_trait(self.name, old_value, new_value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 1139, in _notify_trait type='change', File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 1176, in notify_change c(change) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 819, in compatible_observer return func(self, change) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 186, in _config_changed self._load_config(change.new, traits=traits, section_names=section_names) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 153, in _load_config setattr(self, name, deepcopy(config_value)) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 585, in __set__ self.set(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 559, in set new_value = self._validate(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 591, in _validate value = self.validate(obj, value) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/traitlets.py", line 71, in validate return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix] ValueError: invalid literal for int() with base 10: '1.5' ``` **Share what version of JupyterHub you are using** 0.72. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `jupyterhub/traitlets.py` Content: ``` 1 """ 2 Traitlets that are used in JupyterHub 3 """ 4 # Copyright (c) Jupyter Development Team. 5 # Distributed under the terms of the Modified BSD License. 6 7 from traitlets import List, Unicode, Integer, TraitError 8 9 10 class URLPrefix(Unicode): 11 def validate(self, obj, value): 12 u = super().validate(obj, value) 13 if not u.startswith('/'): 14 u = '/' + u 15 if not u.endswith('/'): 16 u = u + '/' 17 return u 18 19 20 class Command(List): 21 """Traitlet for a command that should be a list of strings, 22 but allows it to be specified as a single string. 23 """ 24 def __init__(self, default_value=None, **kwargs): 25 kwargs.setdefault('minlen', 1) 26 if isinstance(default_value, str): 27 default_value = [default_value] 28 super().__init__(Unicode(), default_value, **kwargs) 29 30 def validate(self, obj, value): 31 if isinstance(value, str): 32 value = [value] 33 return super().validate(obj, value) 34 35 36 class ByteSpecification(Integer): 37 """ 38 Allow easily specifying bytes in units of 1024 with suffixes 39 40 Suffixes allowed are: 41 - K -> Kilobyte 42 - M -> Megabyte 43 - G -> Gigabyte 44 - T -> Terabyte 45 """ 46 47 UNIT_SUFFIXES = { 48 'K': 1024, 49 'M': 1024 * 1024, 50 'G': 1024 * 1024 * 1024, 51 'T': 1024 * 1024 * 1024 * 1024 52 } 53 54 # Default to allowing None as a value 55 allow_none = True 56 57 def validate(self, obj, value): 58 """ 59 Validate that the passed in value is a valid memory specification 60 61 It could either be a pure int, when it is taken as a byte value. 62 If it has one of the suffixes, it is converted into the appropriate 63 pure byte value. 64 """ 65 if isinstance(value, int): 66 return value 67 num = value[:-1] 68 suffix = value[-1] 69 if not num.isdigit() and suffix not in ByteSpecification.UNIT_SUFFIXES: 70 raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) 71 else: 72 return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix] 73 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/jupyterhub/traitlets.py b/jupyterhub/traitlets.py --- a/jupyterhub/traitlets.py +++ b/jupyterhub/traitlets.py @@ -48,7 +48,7 @@ 'K': 1024, 'M': 1024 * 1024, 'G': 1024 * 1024 * 1024, - 'T': 1024 * 1024 * 1024 * 1024 + 'T': 1024 * 1024 * 1024 * 1024, } # Default to allowing None as a value @@ -62,11 +62,15 @@ If it has one of the suffixes, it is converted into the appropriate pure byte value. """ - if isinstance(value, int): - return value - num = value[:-1] + if isinstance(value, (int, float)): + return int(value) + + try: + num = float(value[:-1]) + except ValueError: + raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) suffix = value[-1] - if not num.isdigit() and suffix not in ByteSpecification.UNIT_SUFFIXES: + if suffix not in self.UNIT_SUFFIXES: raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) else: - return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix] + return int(float(num) * self.UNIT_SUFFIXES[suffix])
{"golden_diff": "diff --git a/jupyterhub/traitlets.py b/jupyterhub/traitlets.py\n--- a/jupyterhub/traitlets.py\n+++ b/jupyterhub/traitlets.py\n@@ -48,7 +48,7 @@\n 'K': 1024,\n 'M': 1024 * 1024,\n 'G': 1024 * 1024 * 1024,\n- 'T': 1024 * 1024 * 1024 * 1024\n+ 'T': 1024 * 1024 * 1024 * 1024,\n }\n \n # Default to allowing None as a value\n@@ -62,11 +62,15 @@\n If it has one of the suffixes, it is converted into the appropriate\n pure byte value.\n \"\"\"\n- if isinstance(value, int):\n- return value\n- num = value[:-1]\n+ if isinstance(value, (int, float)):\n+ return int(value)\n+\n+ try:\n+ num = float(value[:-1])\n+ except ValueError:\n+ raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))\n suffix = value[-1]\n- if not num.isdigit() and suffix not in ByteSpecification.UNIT_SUFFIXES:\n+ if suffix not in self.UNIT_SUFFIXES:\n raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))\n else:\n- return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix]\n+ return int(float(num) * self.UNIT_SUFFIXES[suffix])\n", "issue": "Fractional memory / CPU limits / guarantees fail\n**How to reproduce the issue**\r\n\r\nSet memory limit (or guarantee, or cpu limit / guarantee) to a non-integral spec:\r\n\r\n```python\r\nc.Spawner.mem_limit = \"1.5G\"\r\n```\r\n\r\n**What you expected to happen**\r\n\r\n(In supported spawners) memory limit is set to 1.5 gigabytes of RAM\r\n\r\n**What actually happens**\r\n\r\nJupyterHub refuses to start, with:\r\n\r\n```\r\n[E 2017-04-18 05:39:02.270 JupyterHub app:1527]\r\n Traceback (most recent call last):\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py\", line 1524, in launch_instance_async\r\n yield self.initialize(argv)\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py\", line 1315, in initialize\r\n yield self.init_spawners()\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py\", line 1084, in init_spawners\r\n self.users[orm_user.id] = user = User(orm_user, self.tornado_settings)\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/user.py\", line 128, in __init__\r\n config=self.settings.get('config'),\r\n File \"/usr/local/lib/python3.4/dist-packages/kubespawner/spawner.py\", line 29, in __init__\r\n super().__init__(*args, **kwargs)\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/spawner.py\", line 345, in __init__\r\n super(Spawner, self).__init__(**kwargs)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py\", line 84, in __init__\r\n self.config = config\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 585, in __set__\r\n self.set(obj, value)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 574, in set\r\n obj._notify_trait(self.name, old_value, new_value)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 1139, in _notify_trait\r\n type='change',\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 1176, in notify_change\r\n c(change)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 819, in compatible_observer\r\n return func(self, change)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py\", line 186, in _config_changed\r\n self._load_config(change.new, traits=traits, section_names=section_names)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py\", line 153, in _load_config\r\n setattr(self, name, deepcopy(config_value))\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 585, in __set__\r\n self.set(obj, value)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 559, in set\r\n new_value = self._validate(obj, value)\r\n File \"/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py\", line 591, in _validate\r\n value = self.validate(obj, value)\r\n File \"/usr/local/lib/python3.4/dist-packages/jupyterhub/traitlets.py\", line 71, in validate\r\n return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix]\r\n ValueError: invalid literal for int() with base 10: '1.5'\r\n```\r\n\r\n**Share what version of JupyterHub you are using**\r\n\r\n0.72.\n", "before_files": [{"content": "\"\"\"\nTraitlets that are used in JupyterHub\n\"\"\"\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import List, Unicode, Integer, TraitError\n\n\nclass URLPrefix(Unicode):\n def validate(self, obj, value):\n u = super().validate(obj, value)\n if not u.startswith('/'):\n u = '/' + u\n if not u.endswith('/'):\n u = u + '/'\n return u\n\n\nclass Command(List):\n \"\"\"Traitlet for a command that should be a list of strings,\n but allows it to be specified as a single string.\n \"\"\"\n def __init__(self, default_value=None, **kwargs):\n kwargs.setdefault('minlen', 1)\n if isinstance(default_value, str):\n default_value = [default_value]\n super().__init__(Unicode(), default_value, **kwargs)\n\n def validate(self, obj, value):\n if isinstance(value, str):\n value = [value]\n return super().validate(obj, value)\n\n\nclass ByteSpecification(Integer):\n \"\"\"\n Allow easily specifying bytes in units of 1024 with suffixes\n\n Suffixes allowed are:\n - K -> Kilobyte\n - M -> Megabyte\n - G -> Gigabyte\n - T -> Terabyte\n \"\"\"\n\n UNIT_SUFFIXES = {\n 'K': 1024,\n 'M': 1024 * 1024,\n 'G': 1024 * 1024 * 1024,\n 'T': 1024 * 1024 * 1024 * 1024\n }\n\n # Default to allowing None as a value\n allow_none = True\n\n def validate(self, obj, value):\n \"\"\"\n Validate that the passed in value is a valid memory specification\n\n It could either be a pure int, when it is taken as a byte value.\n If it has one of the suffixes, it is converted into the appropriate\n pure byte value.\n \"\"\"\n if isinstance(value, int):\n return value\n num = value[:-1]\n suffix = value[-1]\n if not num.isdigit() and suffix not in ByteSpecification.UNIT_SUFFIXES:\n raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))\n else:\n return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix]\n", "path": "jupyterhub/traitlets.py"}], "after_files": [{"content": "\"\"\"\nTraitlets that are used in JupyterHub\n\"\"\"\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom traitlets import List, Unicode, Integer, TraitError\n\n\nclass URLPrefix(Unicode):\n def validate(self, obj, value):\n u = super().validate(obj, value)\n if not u.startswith('/'):\n u = '/' + u\n if not u.endswith('/'):\n u = u + '/'\n return u\n\n\nclass Command(List):\n \"\"\"Traitlet for a command that should be a list of strings,\n but allows it to be specified as a single string.\n \"\"\"\n def __init__(self, default_value=None, **kwargs):\n kwargs.setdefault('minlen', 1)\n if isinstance(default_value, str):\n default_value = [default_value]\n super().__init__(Unicode(), default_value, **kwargs)\n\n def validate(self, obj, value):\n if isinstance(value, str):\n value = [value]\n return super().validate(obj, value)\n\n\nclass ByteSpecification(Integer):\n \"\"\"\n Allow easily specifying bytes in units of 1024 with suffixes\n\n Suffixes allowed are:\n - K -> Kilobyte\n - M -> Megabyte\n - G -> Gigabyte\n - T -> Terabyte\n \"\"\"\n\n UNIT_SUFFIXES = {\n 'K': 1024,\n 'M': 1024 * 1024,\n 'G': 1024 * 1024 * 1024,\n 'T': 1024 * 1024 * 1024 * 1024,\n }\n\n # Default to allowing None as a value\n allow_none = True\n\n def validate(self, obj, value):\n \"\"\"\n Validate that the passed in value is a valid memory specification\n\n It could either be a pure int, when it is taken as a byte value.\n If it has one of the suffixes, it is converted into the appropriate\n pure byte value.\n \"\"\"\n if isinstance(value, (int, float)):\n return int(value)\n\n try:\n num = float(value[:-1])\n except ValueError:\n raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))\n suffix = value[-1]\n if suffix not in self.UNIT_SUFFIXES:\n raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))\n else:\n return int(float(num) * self.UNIT_SUFFIXES[suffix])\n", "path": "jupyterhub/traitlets.py"}]}
1,874
413
gh_patches_debug_59179
rasdani/github-patches
git_diff
TheAlgorithms__Python-1943
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Same name for an attribute and a function Hi, I'm new to programming and I'm not sure if it's a problem, but the code( Python/data_structures/queue/queue_on_list.py) have the same name for an attribute and a function. ``` class Queue: def __init__(self): self.entries = [] self.length = 0 self.front = 0 def front(self): return self.entries[0] ``` When executed it gives me the error: TypeError: 'int' object is not callable --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `data_structures/queue/queue_on_list.py` Content: ``` 1 """Queue represented by a Python list""" 2 3 4 class Queue: 5 def __init__(self): 6 self.entries = [] 7 self.length = 0 8 self.front = 0 9 10 def __str__(self): 11 printed = "<" + str(self.entries)[1:-1] + ">" 12 return printed 13 14 """Enqueues {@code item} 15 @param item 16 item to enqueue""" 17 18 def put(self, item): 19 self.entries.append(item) 20 self.length = self.length + 1 21 22 """Dequeues {@code item} 23 @requirement: |self.length| > 0 24 @return dequeued 25 item that was dequeued""" 26 27 def get(self): 28 self.length = self.length - 1 29 dequeued = self.entries[self.front] 30 # self.front-=1 31 # self.entries = self.entries[self.front:] 32 self.entries = self.entries[1:] 33 return dequeued 34 35 """Rotates the queue {@code rotation} times 36 @param rotation 37 number of times to rotate queue""" 38 39 def rotate(self, rotation): 40 for i in range(rotation): 41 self.put(self.get()) 42 43 """Enqueues {@code item} 44 @return item at front of self.entries""" 45 46 def front(self): 47 return self.entries[0] 48 49 """Returns the length of this.entries""" 50 51 def size(self): 52 return self.length 53 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py --- a/data_structures/queue/queue_on_list.py +++ b/data_structures/queue/queue_on_list.py @@ -43,7 +43,7 @@ """Enqueues {@code item} @return item at front of self.entries""" - def front(self): + def get_front(self): return self.entries[0] """Returns the length of this.entries"""
{"golden_diff": "diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py\n--- a/data_structures/queue/queue_on_list.py\n+++ b/data_structures/queue/queue_on_list.py\n@@ -43,7 +43,7 @@\n \"\"\"Enqueues {@code item}\r\n @return item at front of self.entries\"\"\"\r\n \r\n- def front(self):\r\n+ def get_front(self):\r\n return self.entries[0]\r\n \r\n \"\"\"Returns the length of this.entries\"\"\"\n", "issue": "Same name for an attribute and a function\nHi, I'm new to programming and I'm not sure if it's a problem, but the code(\r\nPython/data_structures/queue/queue_on_list.py) have the same name for an attribute and a function.\r\n```\r\nclass Queue:\r\n def __init__(self):\r\n self.entries = []\r\n self.length = 0\r\n self.front = 0\r\n\r\n def front(self):\r\n return self.entries[0]\r\n```\r\nWhen executed it gives me the error:\r\nTypeError: 'int' object is not callable\n", "before_files": [{"content": "\"\"\"Queue represented by a Python list\"\"\"\r\n\r\n\r\nclass Queue:\r\n def __init__(self):\r\n self.entries = []\r\n self.length = 0\r\n self.front = 0\r\n\r\n def __str__(self):\r\n printed = \"<\" + str(self.entries)[1:-1] + \">\"\r\n return printed\r\n\r\n \"\"\"Enqueues {@code item}\r\n @param item\r\n item to enqueue\"\"\"\r\n\r\n def put(self, item):\r\n self.entries.append(item)\r\n self.length = self.length + 1\r\n\r\n \"\"\"Dequeues {@code item}\r\n @requirement: |self.length| > 0\r\n @return dequeued\r\n item that was dequeued\"\"\"\r\n\r\n def get(self):\r\n self.length = self.length - 1\r\n dequeued = self.entries[self.front]\r\n # self.front-=1\r\n # self.entries = self.entries[self.front:]\r\n self.entries = self.entries[1:]\r\n return dequeued\r\n\r\n \"\"\"Rotates the queue {@code rotation} times\r\n @param rotation\r\n number of times to rotate queue\"\"\"\r\n\r\n def rotate(self, rotation):\r\n for i in range(rotation):\r\n self.put(self.get())\r\n\r\n \"\"\"Enqueues {@code item}\r\n @return item at front of self.entries\"\"\"\r\n\r\n def front(self):\r\n return self.entries[0]\r\n\r\n \"\"\"Returns the length of this.entries\"\"\"\r\n\r\n def size(self):\r\n return self.length\r\n", "path": "data_structures/queue/queue_on_list.py"}], "after_files": [{"content": "\"\"\"Queue represented by a Python list\"\"\"\r\n\r\n\r\nclass Queue:\r\n def __init__(self):\r\n self.entries = []\r\n self.length = 0\r\n self.front = 0\r\n\r\n def __str__(self):\r\n printed = \"<\" + str(self.entries)[1:-1] + \">\"\r\n return printed\r\n\r\n \"\"\"Enqueues {@code item}\r\n @param item\r\n item to enqueue\"\"\"\r\n\r\n def put(self, item):\r\n self.entries.append(item)\r\n self.length = self.length + 1\r\n\r\n \"\"\"Dequeues {@code item}\r\n @requirement: |self.length| > 0\r\n @return dequeued\r\n item that was dequeued\"\"\"\r\n\r\n def get(self):\r\n self.length = self.length - 1\r\n dequeued = self.entries[self.front]\r\n # self.front-=1\r\n # self.entries = self.entries[self.front:]\r\n self.entries = self.entries[1:]\r\n return dequeued\r\n\r\n \"\"\"Rotates the queue {@code rotation} times\r\n @param rotation\r\n number of times to rotate queue\"\"\"\r\n\r\n def rotate(self, rotation):\r\n for i in range(rotation):\r\n self.put(self.get())\r\n\r\n \"\"\"Enqueues {@code item}\r\n @return item at front of self.entries\"\"\"\r\n\r\n def get_front(self):\r\n return self.entries[0]\r\n\r\n \"\"\"Returns the length of this.entries\"\"\"\r\n\r\n def size(self):\r\n return self.length\r\n", "path": "data_structures/queue/queue_on_list.py"}]}
782
113
gh_patches_debug_31878
rasdani/github-patches
git_diff
googleapis__google-cloud-python-4817
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Vision: Single feature functions generated by cloud vision client library does not support parameter max_results As specified in [the gRPC reference](https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateImageRequest), AnnotateImageRequest message have three fields, _image_, _features[]_ and _image_context_, in which the _features[]_ field determines what feature user is request (_type_) and max number of returned results (_max_results_). The code for generating single-feature functions (for example, _face_detection()_), however, does not allow user to specify _max_results_: ``` feature_value = {'type': enum.__dict__[feature]} def inner(self, image, options=None, **kwargs): request = dict( image=image, features=[feature_value], **kwargs ) return self.annotate_image(request, options=options) ``` Reported in https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1173 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `vision/google/cloud/vision_helpers/decorators.py` Content: ``` 1 # Copyright 2017, Google LLC All rights reserved. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 from __future__ import absolute_import 16 17 18 def add_single_feature_methods(cls): 19 """Custom decorator intended for :class:`~vision.helpers.VisionHelpers`. 20 21 This metaclass adds a `{feature}` method for every feature 22 defined on the Feature enum. 23 """ 24 # Sanity check: This only makes sense if we are building the GAPIC 25 # subclass and have enums already attached. 26 if not hasattr(cls, 'enums'): 27 return cls 28 29 # Iterate over the Feature.Type enum and add get a list of 30 # features which will receive single-feature detection methods. 31 features = [k for k in cls.enums.Feature.Type.__dict__.keys() 32 if k.replace('_', '').isalpha() and k.upper() == k] 33 34 # Add each single-feature method to the class. 35 for feature in features: 36 # Sanity check: Do not make a method for the falsy feature. 37 if feature == 'TYPE_UNSPECIFIED': 38 continue 39 40 # Assign the appropriate metadata to the function. 41 detect = _create_single_feature_method(feature, cls.enums.Feature.Type) 42 43 # Assign a qualified name to the function, and perform module 44 # replacement on the docstring. 45 detect.__qualname__ = '{cls}.{name}'.format( 46 cls=cls.__name__, 47 name=detect.__name__, 48 ) 49 detect.__doc__ = detect.__doc__.format( 50 module=cls.__module__, 51 ) 52 53 # Place the function on the class being created. 54 setattr(cls, detect.__name__, detect) 55 56 # Done; return the class. 57 return cls 58 59 60 def _create_single_feature_method(feature, enum): 61 """Return a function that will detect a single feature. 62 63 Args: 64 feature (str): A specific feature defined as an attribute on 65 :class:`~enums.Feature.Type`. 66 enum (class): The :class:`~enums.Feature.Type` class. 67 68 Returns: 69 function: A helper function to detect just that feature. 70 """ 71 # Define the function properties. 72 fx_name = feature.lower() 73 if 'detection' in fx_name: 74 fx_doc = 'Perform {0}.'.format(fx_name.replace('_', ' ')) 75 else: 76 fx_doc = 'Return {desc} information.'.format( 77 desc=fx_name.replace('_', ' '), 78 ) 79 80 # Provide a complete docstring with argument and return value 81 # information. 82 fx_doc += """ 83 84 Args: 85 image (:class:`~.{module}.types.Image`): The image to analyze. 86 options (:class:`google.gax.CallOptions`): Overrides the 87 default settings for this call, e.g, timeout, retries, etc. 88 kwargs (dict): Additional properties to be set on the 89 :class:`~.{module}.types.AnnotateImageRequest`. 90 91 Returns: 92 :class:`~.{module}.types.AnnotateImageResponse`: The API response. 93 """ 94 95 # Get the actual feature value to send. 96 feature_value = {'type': enum.__dict__[feature]} 97 98 # Define the function to be returned. 99 def inner(self, image, retry=None, timeout=None, **kwargs): 100 """Return a single feature annotation for the given image. 101 102 Intended for use with functools.partial, to create the particular 103 single-feature methods. 104 """ 105 request = dict( 106 image=image, 107 features=[feature_value], 108 **kwargs 109 ) 110 return self.annotate_image(request, retry=retry, timeout=timeout) 111 112 # Set the appropriate function metadata. 113 inner.__name__ = fx_name 114 inner.__doc__ = fx_doc 115 116 # Return the final function. 117 return inner 118 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/vision/google/cloud/vision_helpers/decorators.py b/vision/google/cloud/vision_helpers/decorators.py --- a/vision/google/cloud/vision_helpers/decorators.py +++ b/vision/google/cloud/vision_helpers/decorators.py @@ -83,8 +83,11 @@ Args: image (:class:`~.{module}.types.Image`): The image to analyze. - options (:class:`google.gax.CallOptions`): Overrides the - default settings for this call, e.g, timeout, retries, etc. + max_results (int): + Number of results to return, does not apply for + TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS. + retry (int): Number of retries to do before giving up. + timeout (int): Number of seconds before timing out. kwargs (dict): Additional properties to be set on the :class:`~.{module}.types.AnnotateImageRequest`. @@ -96,18 +99,23 @@ feature_value = {'type': enum.__dict__[feature]} # Define the function to be returned. - def inner(self, image, retry=None, timeout=None, **kwargs): + def inner(self, image, max_results=None, + retry=None, timeout=None, **kwargs): """Return a single feature annotation for the given image. Intended for use with functools.partial, to create the particular single-feature methods. """ + copied_features = feature_value.copy() + if max_results is not None: + copied_features['max_results'] = max_results request = dict( image=image, - features=[feature_value], + features=[copied_features], **kwargs ) - return self.annotate_image(request, retry=retry, timeout=timeout) + response = self.annotate_image(request, retry=retry, timeout=timeout) + return response # Set the appropriate function metadata. inner.__name__ = fx_name
{"golden_diff": "diff --git a/vision/google/cloud/vision_helpers/decorators.py b/vision/google/cloud/vision_helpers/decorators.py\n--- a/vision/google/cloud/vision_helpers/decorators.py\n+++ b/vision/google/cloud/vision_helpers/decorators.py\n@@ -83,8 +83,11 @@\n \n Args:\n image (:class:`~.{module}.types.Image`): The image to analyze.\n- options (:class:`google.gax.CallOptions`): Overrides the\n- default settings for this call, e.g, timeout, retries, etc.\n+ max_results (int):\n+ Number of results to return, does not apply for\n+ TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS.\n+ retry (int): Number of retries to do before giving up.\n+ timeout (int): Number of seconds before timing out.\n kwargs (dict): Additional properties to be set on the\n :class:`~.{module}.types.AnnotateImageRequest`.\n \n@@ -96,18 +99,23 @@\n feature_value = {'type': enum.__dict__[feature]}\n \n # Define the function to be returned.\n- def inner(self, image, retry=None, timeout=None, **kwargs):\n+ def inner(self, image, max_results=None,\n+ retry=None, timeout=None, **kwargs):\n \"\"\"Return a single feature annotation for the given image.\n \n Intended for use with functools.partial, to create the particular\n single-feature methods.\n \"\"\"\n+ copied_features = feature_value.copy()\n+ if max_results is not None:\n+ copied_features['max_results'] = max_results\n request = dict(\n image=image,\n- features=[feature_value],\n+ features=[copied_features],\n **kwargs\n )\n- return self.annotate_image(request, retry=retry, timeout=timeout)\n+ response = self.annotate_image(request, retry=retry, timeout=timeout)\n+ return response\n \n # Set the appropriate function metadata.\n inner.__name__ = fx_name\n", "issue": "Vision: Single feature functions generated by cloud vision client library does not support parameter max_results\nAs specified in [the gRPC reference](https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.AnnotateImageRequest), AnnotateImageRequest message have three fields, _image_, _features[]_ and _image_context_, in which the _features[]_ field determines what feature user is request (_type_) and max number of returned results (_max_results_). The code for generating single-feature functions (for example, _face_detection()_), however, does not allow user to specify _max_results_:\r\n\r\n```\r\nfeature_value = {'type': enum.__dict__[feature]}\r\ndef inner(self, image, options=None, **kwargs):\r\n request = dict(\r\n image=image,\r\n features=[feature_value],\r\n **kwargs\r\n )\r\n return self.annotate_image(request, options=options)\r\n```\r\n\r\nReported in https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1173\n", "before_files": [{"content": "# Copyright 2017, Google LLC All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\n\ndef add_single_feature_methods(cls):\n \"\"\"Custom decorator intended for :class:`~vision.helpers.VisionHelpers`.\n\n This metaclass adds a `{feature}` method for every feature\n defined on the Feature enum.\n \"\"\"\n # Sanity check: This only makes sense if we are building the GAPIC\n # subclass and have enums already attached.\n if not hasattr(cls, 'enums'):\n return cls\n\n # Iterate over the Feature.Type enum and add get a list of\n # features which will receive single-feature detection methods.\n features = [k for k in cls.enums.Feature.Type.__dict__.keys()\n if k.replace('_', '').isalpha() and k.upper() == k]\n\n # Add each single-feature method to the class.\n for feature in features:\n # Sanity check: Do not make a method for the falsy feature.\n if feature == 'TYPE_UNSPECIFIED':\n continue\n\n # Assign the appropriate metadata to the function.\n detect = _create_single_feature_method(feature, cls.enums.Feature.Type)\n\n # Assign a qualified name to the function, and perform module\n # replacement on the docstring.\n detect.__qualname__ = '{cls}.{name}'.format(\n cls=cls.__name__,\n name=detect.__name__,\n )\n detect.__doc__ = detect.__doc__.format(\n module=cls.__module__,\n )\n\n # Place the function on the class being created.\n setattr(cls, detect.__name__, detect)\n\n # Done; return the class.\n return cls\n\n\ndef _create_single_feature_method(feature, enum):\n \"\"\"Return a function that will detect a single feature.\n\n Args:\n feature (str): A specific feature defined as an attribute on\n :class:`~enums.Feature.Type`.\n enum (class): The :class:`~enums.Feature.Type` class.\n\n Returns:\n function: A helper function to detect just that feature.\n \"\"\"\n # Define the function properties.\n fx_name = feature.lower()\n if 'detection' in fx_name:\n fx_doc = 'Perform {0}.'.format(fx_name.replace('_', ' '))\n else:\n fx_doc = 'Return {desc} information.'.format(\n desc=fx_name.replace('_', ' '),\n )\n\n # Provide a complete docstring with argument and return value\n # information.\n fx_doc += \"\"\"\n\n Args:\n image (:class:`~.{module}.types.Image`): The image to analyze.\n options (:class:`google.gax.CallOptions`): Overrides the\n default settings for this call, e.g, timeout, retries, etc.\n kwargs (dict): Additional properties to be set on the\n :class:`~.{module}.types.AnnotateImageRequest`.\n\n Returns:\n :class:`~.{module}.types.AnnotateImageResponse`: The API response.\n \"\"\"\n\n # Get the actual feature value to send.\n feature_value = {'type': enum.__dict__[feature]}\n\n # Define the function to be returned.\n def inner(self, image, retry=None, timeout=None, **kwargs):\n \"\"\"Return a single feature annotation for the given image.\n\n Intended for use with functools.partial, to create the particular\n single-feature methods.\n \"\"\"\n request = dict(\n image=image,\n features=[feature_value],\n **kwargs\n )\n return self.annotate_image(request, retry=retry, timeout=timeout)\n\n # Set the appropriate function metadata.\n inner.__name__ = fx_name\n inner.__doc__ = fx_doc\n\n # Return the final function.\n return inner\n", "path": "vision/google/cloud/vision_helpers/decorators.py"}], "after_files": [{"content": "# Copyright 2017, Google LLC All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\n\ndef add_single_feature_methods(cls):\n \"\"\"Custom decorator intended for :class:`~vision.helpers.VisionHelpers`.\n\n This metaclass adds a `{feature}` method for every feature\n defined on the Feature enum.\n \"\"\"\n # Sanity check: This only makes sense if we are building the GAPIC\n # subclass and have enums already attached.\n if not hasattr(cls, 'enums'):\n return cls\n\n # Iterate over the Feature.Type enum and add get a list of\n # features which will receive single-feature detection methods.\n features = [k for k in cls.enums.Feature.Type.__dict__.keys()\n if k.replace('_', '').isalpha() and k.upper() == k]\n\n # Add each single-feature method to the class.\n for feature in features:\n # Sanity check: Do not make a method for the falsy feature.\n if feature == 'TYPE_UNSPECIFIED':\n continue\n\n # Assign the appropriate metadata to the function.\n detect = _create_single_feature_method(feature, cls.enums.Feature.Type)\n\n # Assign a qualified name to the function, and perform module\n # replacement on the docstring.\n detect.__qualname__ = '{cls}.{name}'.format(\n cls=cls.__name__,\n name=detect.__name__,\n )\n detect.__doc__ = detect.__doc__.format(\n module=cls.__module__,\n )\n\n # Place the function on the class being created.\n setattr(cls, detect.__name__, detect)\n\n # Done; return the class.\n return cls\n\n\ndef _create_single_feature_method(feature, enum):\n \"\"\"Return a function that will detect a single feature.\n\n Args:\n feature (str): A specific feature defined as an attribute on\n :class:`~enums.Feature.Type`.\n enum (class): The :class:`~enums.Feature.Type` class.\n\n Returns:\n function: A helper function to detect just that feature.\n \"\"\"\n # Define the function properties.\n fx_name = feature.lower()\n if 'detection' in fx_name:\n fx_doc = 'Perform {0}.'.format(fx_name.replace('_', ' '))\n else:\n fx_doc = 'Return {desc} information.'.format(\n desc=fx_name.replace('_', ' '),\n )\n\n # Provide a complete docstring with argument and return value\n # information.\n fx_doc += \"\"\"\n\n Args:\n image (:class:`~.{module}.types.Image`): The image to analyze.\n max_results (int):\n Number of results to return, does not apply for\n TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS.\n retry (int): Number of retries to do before giving up.\n timeout (int): Number of seconds before timing out.\n kwargs (dict): Additional properties to be set on the\n :class:`~.{module}.types.AnnotateImageRequest`.\n\n Returns:\n :class:`~.{module}.types.AnnotateImageResponse`: The API response.\n \"\"\"\n\n # Get the actual feature value to send.\n feature_value = {'type': enum.__dict__[feature]}\n\n # Define the function to be returned.\n def inner(self, image, max_results=None,\n retry=None, timeout=None, **kwargs):\n \"\"\"Return a single feature annotation for the given image.\n\n Intended for use with functools.partial, to create the particular\n single-feature methods.\n \"\"\"\n copied_features = feature_value.copy()\n if max_results is not None:\n copied_features['max_results'] = max_results\n request = dict(\n image=image,\n features=[copied_features],\n **kwargs\n )\n response = self.annotate_image(request, retry=retry, timeout=timeout)\n return response\n\n # Set the appropriate function metadata.\n inner.__name__ = fx_name\n inner.__doc__ = fx_doc\n\n # Return the final function.\n return inner\n", "path": "vision/google/cloud/vision_helpers/decorators.py"}]}
1,639
442
gh_patches_debug_25483
rasdani/github-patches
git_diff
aio-libs-abandoned__aioredis-py-355
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Fixed ConnectionsPool.[pubsub_channels/pubsub_patterns] Fixed bug in `commands.pubsub.PubSubCommandsMixin.subscribe` (and psubscribe). `ConnectionsPool.pubsub_channles` code was called before `ConnectionsPool._pubsub_conn` creation, and therefore `pubsub_channles` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `aioredis/commands/pubsub.py` Content: ``` 1 import json 2 3 from aioredis.util import wait_make_dict 4 5 6 class PubSubCommandsMixin: 7 """Pub/Sub commands mixin. 8 9 For commands details see: http://redis.io/commands/#pubsub 10 """ 11 12 def publish(self, channel, message): 13 """Post a message to channel.""" 14 return self.execute(b'PUBLISH', channel, message) 15 16 def publish_json(self, channel, obj): 17 """Post a JSON-encoded message to channel.""" 18 return self.publish(channel, json.dumps(obj)) 19 20 def subscribe(self, channel, *channels): 21 """Switch connection to Pub/Sub mode and 22 subscribe to specified channels. 23 24 Arguments can be instances of :class:`~aioredis.Channel`. 25 26 Returns :func:`asyncio.gather()` coroutine which when done will return 27 a list of :class:`~aioredis.Channel` objects. 28 """ 29 conn = self._pool_or_conn 30 return wait_return_channels( 31 conn.execute_pubsub(b'SUBSCRIBE', channel, *channels), 32 conn.pubsub_channels) 33 34 def unsubscribe(self, channel, *channels): 35 """Unsubscribe from specific channels. 36 37 Arguments can be instances of :class:`~aioredis.Channel`. 38 """ 39 conn = self._pool_or_conn 40 return conn.execute_pubsub(b'UNSUBSCRIBE', channel, *channels) 41 42 def psubscribe(self, pattern, *patterns): 43 """Switch connection to Pub/Sub mode and 44 subscribe to specified patterns. 45 46 Arguments can be instances of :class:`~aioredis.Channel`. 47 48 Returns :func:`asyncio.gather()` coroutine which when done will return 49 a list of subscribed :class:`~aioredis.Channel` objects with 50 ``is_pattern`` property set to ``True``. 51 """ 52 conn = self._pool_or_conn 53 return wait_return_channels( 54 conn.execute_pubsub(b'PSUBSCRIBE', pattern, *patterns), 55 conn.pubsub_patterns) 56 57 def punsubscribe(self, pattern, *patterns): 58 """Unsubscribe from specific patterns. 59 60 Arguments can be instances of :class:`~aioredis.Channel`. 61 """ 62 conn = self._pool_or_conn 63 return conn.execute_pubsub(b'PUNSUBSCRIBE', pattern, *patterns) 64 65 def pubsub_channels(self, pattern=None): 66 """Lists the currently active channels.""" 67 args = [b'PUBSUB', b'CHANNELS'] 68 if pattern is not None: 69 args.append(pattern) 70 return self.execute(*args) 71 72 def pubsub_numsub(self, *channels): 73 """Returns the number of subscribers for the specified channels.""" 74 return wait_make_dict(self.execute( 75 b'PUBSUB', b'NUMSUB', *channels)) 76 77 def pubsub_numpat(self): 78 """Returns the number of subscriptions to patterns.""" 79 return self.execute(b'PUBSUB', b'NUMPAT') 80 81 @property 82 def channels(self): 83 """Returns read-only channels dict. 84 85 See :attr:`~aioredis.RedisConnection.pubsub_channels` 86 """ 87 return self._pool_or_conn.pubsub_channels 88 89 @property 90 def patterns(self): 91 """Returns read-only patterns dict. 92 93 See :attr:`~aioredis.RedisConnection.pubsub_patterns` 94 """ 95 return self._pool_or_conn.pubsub_patterns 96 97 @property 98 def in_pubsub(self): 99 """Indicates that connection is in PUB/SUB mode. 100 101 Provides the number of subscribed channels. 102 """ 103 return self._pool_or_conn.in_pubsub 104 105 106 async def wait_return_channels(fut, channels_dict): 107 return [channels_dict[name] 108 for cmd, name, count in await fut] 109 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/aioredis/commands/pubsub.py b/aioredis/commands/pubsub.py --- a/aioredis/commands/pubsub.py +++ b/aioredis/commands/pubsub.py @@ -29,7 +29,7 @@ conn = self._pool_or_conn return wait_return_channels( conn.execute_pubsub(b'SUBSCRIBE', channel, *channels), - conn.pubsub_channels) + conn, 'pubsub_channels') def unsubscribe(self, channel, *channels): """Unsubscribe from specific channels. @@ -52,7 +52,7 @@ conn = self._pool_or_conn return wait_return_channels( conn.execute_pubsub(b'PSUBSCRIBE', pattern, *patterns), - conn.pubsub_patterns) + conn, 'pubsub_patterns') def punsubscribe(self, pattern, *patterns): """Unsubscribe from specific patterns. @@ -103,6 +103,7 @@ return self._pool_or_conn.in_pubsub -async def wait_return_channels(fut, channels_dict): - return [channels_dict[name] - for cmd, name, count in await fut] +async def wait_return_channels(fut, conn, field): + res = await fut + channels_dict = getattr(conn, field) + return [channels_dict[name] for cmd, name, count in res]
{"golden_diff": "diff --git a/aioredis/commands/pubsub.py b/aioredis/commands/pubsub.py\n--- a/aioredis/commands/pubsub.py\n+++ b/aioredis/commands/pubsub.py\n@@ -29,7 +29,7 @@\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'SUBSCRIBE', channel, *channels),\n- conn.pubsub_channels)\n+ conn, 'pubsub_channels')\n \n def unsubscribe(self, channel, *channels):\n \"\"\"Unsubscribe from specific channels.\n@@ -52,7 +52,7 @@\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'PSUBSCRIBE', pattern, *patterns),\n- conn.pubsub_patterns)\n+ conn, 'pubsub_patterns')\n \n def punsubscribe(self, pattern, *patterns):\n \"\"\"Unsubscribe from specific patterns.\n@@ -103,6 +103,7 @@\n return self._pool_or_conn.in_pubsub\n \n \n-async def wait_return_channels(fut, channels_dict):\n- return [channels_dict[name]\n- for cmd, name, count in await fut]\n+async def wait_return_channels(fut, conn, field):\n+ res = await fut\n+ channels_dict = getattr(conn, field)\n+ return [channels_dict[name] for cmd, name, count in res]\n", "issue": "Fixed ConnectionsPool.[pubsub_channels/pubsub_patterns]\nFixed bug in `commands.pubsub.PubSubCommandsMixin.subscribe` (and psubscribe). `ConnectionsPool.pubsub_channles` code was called before `ConnectionsPool._pubsub_conn` creation, and therefore `pubsub_channles` \n", "before_files": [{"content": "import json\n\nfrom aioredis.util import wait_make_dict\n\n\nclass PubSubCommandsMixin:\n \"\"\"Pub/Sub commands mixin.\n\n For commands details see: http://redis.io/commands/#pubsub\n \"\"\"\n\n def publish(self, channel, message):\n \"\"\"Post a message to channel.\"\"\"\n return self.execute(b'PUBLISH', channel, message)\n\n def publish_json(self, channel, obj):\n \"\"\"Post a JSON-encoded message to channel.\"\"\"\n return self.publish(channel, json.dumps(obj))\n\n def subscribe(self, channel, *channels):\n \"\"\"Switch connection to Pub/Sub mode and\n subscribe to specified channels.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n\n Returns :func:`asyncio.gather()` coroutine which when done will return\n a list of :class:`~aioredis.Channel` objects.\n \"\"\"\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'SUBSCRIBE', channel, *channels),\n conn.pubsub_channels)\n\n def unsubscribe(self, channel, *channels):\n \"\"\"Unsubscribe from specific channels.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n \"\"\"\n conn = self._pool_or_conn\n return conn.execute_pubsub(b'UNSUBSCRIBE', channel, *channels)\n\n def psubscribe(self, pattern, *patterns):\n \"\"\"Switch connection to Pub/Sub mode and\n subscribe to specified patterns.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n\n Returns :func:`asyncio.gather()` coroutine which when done will return\n a list of subscribed :class:`~aioredis.Channel` objects with\n ``is_pattern`` property set to ``True``.\n \"\"\"\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'PSUBSCRIBE', pattern, *patterns),\n conn.pubsub_patterns)\n\n def punsubscribe(self, pattern, *patterns):\n \"\"\"Unsubscribe from specific patterns.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n \"\"\"\n conn = self._pool_or_conn\n return conn.execute_pubsub(b'PUNSUBSCRIBE', pattern, *patterns)\n\n def pubsub_channels(self, pattern=None):\n \"\"\"Lists the currently active channels.\"\"\"\n args = [b'PUBSUB', b'CHANNELS']\n if pattern is not None:\n args.append(pattern)\n return self.execute(*args)\n\n def pubsub_numsub(self, *channels):\n \"\"\"Returns the number of subscribers for the specified channels.\"\"\"\n return wait_make_dict(self.execute(\n b'PUBSUB', b'NUMSUB', *channels))\n\n def pubsub_numpat(self):\n \"\"\"Returns the number of subscriptions to patterns.\"\"\"\n return self.execute(b'PUBSUB', b'NUMPAT')\n\n @property\n def channels(self):\n \"\"\"Returns read-only channels dict.\n\n See :attr:`~aioredis.RedisConnection.pubsub_channels`\n \"\"\"\n return self._pool_or_conn.pubsub_channels\n\n @property\n def patterns(self):\n \"\"\"Returns read-only patterns dict.\n\n See :attr:`~aioredis.RedisConnection.pubsub_patterns`\n \"\"\"\n return self._pool_or_conn.pubsub_patterns\n\n @property\n def in_pubsub(self):\n \"\"\"Indicates that connection is in PUB/SUB mode.\n\n Provides the number of subscribed channels.\n \"\"\"\n return self._pool_or_conn.in_pubsub\n\n\nasync def wait_return_channels(fut, channels_dict):\n return [channels_dict[name]\n for cmd, name, count in await fut]\n", "path": "aioredis/commands/pubsub.py"}], "after_files": [{"content": "import json\n\nfrom aioredis.util import wait_make_dict\n\n\nclass PubSubCommandsMixin:\n \"\"\"Pub/Sub commands mixin.\n\n For commands details see: http://redis.io/commands/#pubsub\n \"\"\"\n\n def publish(self, channel, message):\n \"\"\"Post a message to channel.\"\"\"\n return self.execute(b'PUBLISH', channel, message)\n\n def publish_json(self, channel, obj):\n \"\"\"Post a JSON-encoded message to channel.\"\"\"\n return self.publish(channel, json.dumps(obj))\n\n def subscribe(self, channel, *channels):\n \"\"\"Switch connection to Pub/Sub mode and\n subscribe to specified channels.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n\n Returns :func:`asyncio.gather()` coroutine which when done will return\n a list of :class:`~aioredis.Channel` objects.\n \"\"\"\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'SUBSCRIBE', channel, *channels),\n conn, 'pubsub_channels')\n\n def unsubscribe(self, channel, *channels):\n \"\"\"Unsubscribe from specific channels.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n \"\"\"\n conn = self._pool_or_conn\n return conn.execute_pubsub(b'UNSUBSCRIBE', channel, *channels)\n\n def psubscribe(self, pattern, *patterns):\n \"\"\"Switch connection to Pub/Sub mode and\n subscribe to specified patterns.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n\n Returns :func:`asyncio.gather()` coroutine which when done will return\n a list of subscribed :class:`~aioredis.Channel` objects with\n ``is_pattern`` property set to ``True``.\n \"\"\"\n conn = self._pool_or_conn\n return wait_return_channels(\n conn.execute_pubsub(b'PSUBSCRIBE', pattern, *patterns),\n conn, 'pubsub_patterns')\n\n def punsubscribe(self, pattern, *patterns):\n \"\"\"Unsubscribe from specific patterns.\n\n Arguments can be instances of :class:`~aioredis.Channel`.\n \"\"\"\n conn = self._pool_or_conn\n return conn.execute_pubsub(b'PUNSUBSCRIBE', pattern, *patterns)\n\n def pubsub_channels(self, pattern=None):\n \"\"\"Lists the currently active channels.\"\"\"\n args = [b'PUBSUB', b'CHANNELS']\n if pattern is not None:\n args.append(pattern)\n return self.execute(*args)\n\n def pubsub_numsub(self, *channels):\n \"\"\"Returns the number of subscribers for the specified channels.\"\"\"\n return wait_make_dict(self.execute(\n b'PUBSUB', b'NUMSUB', *channels))\n\n def pubsub_numpat(self):\n \"\"\"Returns the number of subscriptions to patterns.\"\"\"\n return self.execute(b'PUBSUB', b'NUMPAT')\n\n @property\n def channels(self):\n \"\"\"Returns read-only channels dict.\n\n See :attr:`~aioredis.RedisConnection.pubsub_channels`\n \"\"\"\n return self._pool_or_conn.pubsub_channels\n\n @property\n def patterns(self):\n \"\"\"Returns read-only patterns dict.\n\n See :attr:`~aioredis.RedisConnection.pubsub_patterns`\n \"\"\"\n return self._pool_or_conn.pubsub_patterns\n\n @property\n def in_pubsub(self):\n \"\"\"Indicates that connection is in PUB/SUB mode.\n\n Provides the number of subscribed channels.\n \"\"\"\n return self._pool_or_conn.in_pubsub\n\n\nasync def wait_return_channels(fut, conn, field):\n res = await fut\n channels_dict = getattr(conn, field)\n return [channels_dict[name] for cmd, name, count in res]\n", "path": "aioredis/commands/pubsub.py"}]}
1,325
309
gh_patches_debug_13881
rasdani/github-patches
git_diff
praw-dev__praw-939
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Provide "best" sort for front page (models.Front) The new "best" sort for the front page isn't currently available via PRAW. See [this Reddit thread](https://www.reddit.com/r/redditdev/comments/8h8ijn/how_do_you_sort_best_via_the_api/). --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `praw/models/front.py` Content: ``` 1 """Provide the Front class.""" 2 from .listing.mixins import SubredditListingMixin 3 4 5 class Front(SubredditListingMixin): 6 """Front is a Listing class that represents the front page.""" 7 8 def __init__(self, reddit): 9 """Initialize a Front instance.""" 10 super(Front, self).__init__(reddit, None) 11 self._path = '/' 12 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/praw/models/front.py b/praw/models/front.py --- a/praw/models/front.py +++ b/praw/models/front.py @@ -1,4 +1,6 @@ """Provide the Front class.""" +from ..const import urljoin +from .listing.generator import ListingGenerator from .listing.mixins import SubredditListingMixin @@ -9,3 +11,13 @@ """Initialize a Front instance.""" super(Front, self).__init__(reddit, None) self._path = '/' + + def best(self, **generator_kwargs): + """Return a ListingGenerator for best items. + + Additional keyword arguments are passed in the initialization of + :class:`.ListingGenerator`. + + """ + return ListingGenerator(self._reddit, urljoin(self._path, 'best'), + **generator_kwargs)
{"golden_diff": "diff --git a/praw/models/front.py b/praw/models/front.py\n--- a/praw/models/front.py\n+++ b/praw/models/front.py\n@@ -1,4 +1,6 @@\n \"\"\"Provide the Front class.\"\"\"\n+from ..const import urljoin\n+from .listing.generator import ListingGenerator\n from .listing.mixins import SubredditListingMixin\n \n \n@@ -9,3 +11,13 @@\n \"\"\"Initialize a Front instance.\"\"\"\n super(Front, self).__init__(reddit, None)\n self._path = '/'\n+\n+ def best(self, **generator_kwargs):\n+ \"\"\"Return a ListingGenerator for best items.\n+\n+ Additional keyword arguments are passed in the initialization of\n+ :class:`.ListingGenerator`.\n+\n+ \"\"\"\n+ return ListingGenerator(self._reddit, urljoin(self._path, 'best'),\n+ **generator_kwargs)\n", "issue": "Provide \"best\" sort for front page (models.Front)\nThe new \"best\" sort for the front page isn't currently available via PRAW. See [this Reddit thread](https://www.reddit.com/r/redditdev/comments/8h8ijn/how_do_you_sort_best_via_the_api/).\n", "before_files": [{"content": "\"\"\"Provide the Front class.\"\"\"\nfrom .listing.mixins import SubredditListingMixin\n\n\nclass Front(SubredditListingMixin):\n \"\"\"Front is a Listing class that represents the front page.\"\"\"\n\n def __init__(self, reddit):\n \"\"\"Initialize a Front instance.\"\"\"\n super(Front, self).__init__(reddit, None)\n self._path = '/'\n", "path": "praw/models/front.py"}], "after_files": [{"content": "\"\"\"Provide the Front class.\"\"\"\nfrom ..const import urljoin\nfrom .listing.generator import ListingGenerator\nfrom .listing.mixins import SubredditListingMixin\n\n\nclass Front(SubredditListingMixin):\n \"\"\"Front is a Listing class that represents the front page.\"\"\"\n\n def __init__(self, reddit):\n \"\"\"Initialize a Front instance.\"\"\"\n super(Front, self).__init__(reddit, None)\n self._path = '/'\n\n def best(self, **generator_kwargs):\n \"\"\"Return a ListingGenerator for best items.\n\n Additional keyword arguments are passed in the initialization of\n :class:`.ListingGenerator`.\n\n \"\"\"\n return ListingGenerator(self._reddit, urljoin(self._path, 'best'),\n **generator_kwargs)\n", "path": "praw/models/front.py"}]}
411
187
gh_patches_debug_40979
rasdani/github-patches
git_diff
dotkom__onlineweb4-599
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- (Event) Minimum length on event description and ingress Possibly we should also limit the text to exclude words like TBA. Events in ow4 demand some text in order to look good, so let's put a minimum requirement on length for the event texts. Making up a description of 200 characters should be no big deal. I've really had it with "INFO: TBA" --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `apps/events/admin.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 3 from apps.events.models import Event 4 from apps.events.models import AttendanceEvent 5 from apps.events.models import Attendee 6 from apps.events.models import CompanyEvent 7 from apps.events.models import RuleBundle 8 from apps.events.models import FieldOfStudyRule 9 from apps.events.models import GradeRule 10 from apps.events.models import UserGroupRule 11 12 from apps.feedback.admin import FeedbackRelationInline 13 14 from django.contrib import admin 15 16 17 class AttendeeInline(admin.TabularInline): 18 model = Attendee 19 extra = 1 20 21 22 class CompanyInline(admin.TabularInline): 23 model = CompanyEvent 24 max_num = 20 25 extra = 0 26 27 class RuleBundleInline(admin.TabularInline): 28 model = RuleBundle 29 extra = 1 30 max_num = 20 31 32 33 class AttendanceEventAdmin(admin.ModelAdmin): 34 model = AttendanceEvent 35 inlines = (AttendeeInline, RuleBundleInline) 36 37 class AttendeeAdmin(admin.ModelAdmin): 38 model = Attendee 39 list_display = ('user', 'event') 40 41 class CompanyEventAdmin(admin.ModelAdmin): 42 model = CompanyEvent 43 inlines = (CompanyInline,) 44 45 class RuleBundleAdmin(admin.ModelAdmin): 46 model = RuleBundle 47 48 class FieldOfStudyRuleAdmin(admin.ModelAdmin): 49 model = FieldOfStudyRule 50 51 class GradeRuleAdmin(admin.ModelAdmin): 52 model = GradeRule 53 54 class UserGroupRuleAdmin(admin.ModelAdmin): 55 model = UserGroupRule 56 57 class AttendanceEventInline(admin.StackedInline): 58 model = AttendanceEvent 59 max_num = 1 60 extra = 0 61 filter_horizontal = ('rule_bundles',) 62 63 64 class EventAdmin(admin.ModelAdmin): 65 inlines = (AttendanceEventInline, FeedbackRelationInline, CompanyInline) 66 exclude = ("author", ) 67 68 def save_model(self, request, obj, form, change): 69 if not change: # created 70 obj.author = request.user 71 obj.save() 72 73 def save_formset(self, request, form, formset, change): 74 instances = formset.save(commit=False) 75 for instance in instances: 76 instance.save() 77 formset.save_m2m() 78 79 admin.site.register(Event, EventAdmin) 80 admin.site.register(Attendee, AttendeeAdmin) 81 admin.site.register(AttendanceEvent, AttendanceEventAdmin) 82 admin.site.register(RuleBundle, RuleBundleAdmin) 83 admin.site.register(GradeRule, GradeRuleAdmin) 84 admin.site.register(UserGroupRule, UserGroupRuleAdmin) 85 admin.site.register(FieldOfStudyRule, FieldOfStudyRuleAdmin) 86 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/apps/events/admin.py b/apps/events/admin.py --- a/apps/events/admin.py +++ b/apps/events/admin.py @@ -1,5 +1,10 @@ # -*- coding: utf-8 -*- +from django import forms +from django.contrib import admin +from django.core import validators +from django.utils.translation import ugettext as _ + from apps.events.models import Event from apps.events.models import AttendanceEvent from apps.events.models import Attendee @@ -8,10 +13,8 @@ from apps.events.models import FieldOfStudyRule from apps.events.models import GradeRule from apps.events.models import UserGroupRule - from apps.feedback.admin import FeedbackRelationInline -from django.contrib import admin class AttendeeInline(admin.TabularInline): @@ -24,6 +27,7 @@ max_num = 20 extra = 0 + class RuleBundleInline(admin.TabularInline): model = RuleBundle extra = 1 @@ -34,32 +38,39 @@ model = AttendanceEvent inlines = (AttendeeInline, RuleBundleInline) + class AttendeeAdmin(admin.ModelAdmin): model = Attendee list_display = ('user', 'event') + class CompanyEventAdmin(admin.ModelAdmin): model = CompanyEvent inlines = (CompanyInline,) + class RuleBundleAdmin(admin.ModelAdmin): model = RuleBundle - + + class FieldOfStudyRuleAdmin(admin.ModelAdmin): model = FieldOfStudyRule + class GradeRuleAdmin(admin.ModelAdmin): model = GradeRule + class UserGroupRuleAdmin(admin.ModelAdmin): model = UserGroupRule + class AttendanceEventInline(admin.StackedInline): model = AttendanceEvent max_num = 1 extra = 0 filter_horizontal = ('rule_bundles',) - + class EventAdmin(admin.ModelAdmin): inlines = (AttendanceEventInline, FeedbackRelationInline, CompanyInline) @@ -76,6 +87,16 @@ instance.save() formset.save_m2m() + def get_form(self, request, obj=None, **kwargs): + form = super(EventAdmin, self).get_form(request, obj, **kwargs) + form.base_fields['ingress_short'].validators=[validators.MinLengthValidator(75)] + form.base_fields['ingress'].validators=[validators.MinLengthValidator(100)] + form.base_fields['description'].validators=[ + validators.MinLengthValidator(200), + validators.RegexValidator("^(?:(?!TBA).)*$", _("Beskrivelsen kan ikke inneholde 'TBA'."), "ulovlig"), + ] + return form + admin.site.register(Event, EventAdmin) admin.site.register(Attendee, AttendeeAdmin) admin.site.register(AttendanceEvent, AttendanceEventAdmin)
{"golden_diff": "diff --git a/apps/events/admin.py b/apps/events/admin.py\n--- a/apps/events/admin.py\n+++ b/apps/events/admin.py\n@@ -1,5 +1,10 @@\n # -*- coding: utf-8 -*-\n \n+from django import forms\n+from django.contrib import admin\n+from django.core import validators\n+from django.utils.translation import ugettext as _\n+\n from apps.events.models import Event\n from apps.events.models import AttendanceEvent\n from apps.events.models import Attendee\n@@ -8,10 +13,8 @@\n from apps.events.models import FieldOfStudyRule\n from apps.events.models import GradeRule\n from apps.events.models import UserGroupRule\n-\n from apps.feedback.admin import FeedbackRelationInline\n \n-from django.contrib import admin\n \n \n class AttendeeInline(admin.TabularInline):\n@@ -24,6 +27,7 @@\n max_num = 20\n extra = 0\n \n+\n class RuleBundleInline(admin.TabularInline):\n model = RuleBundle\n extra = 1\n@@ -34,32 +38,39 @@\n model = AttendanceEvent\n inlines = (AttendeeInline, RuleBundleInline)\n \n+\n class AttendeeAdmin(admin.ModelAdmin):\n model = Attendee\n list_display = ('user', 'event')\n \n+\n class CompanyEventAdmin(admin.ModelAdmin):\n model = CompanyEvent\n inlines = (CompanyInline,)\n \n+\n class RuleBundleAdmin(admin.ModelAdmin):\n model = RuleBundle\n- \n+\n+\n class FieldOfStudyRuleAdmin(admin.ModelAdmin):\n model = FieldOfStudyRule\n \n+\n class GradeRuleAdmin(admin.ModelAdmin):\n model = GradeRule\n \n+\n class UserGroupRuleAdmin(admin.ModelAdmin):\n model = UserGroupRule\n \n+\n class AttendanceEventInline(admin.StackedInline):\n model = AttendanceEvent\n max_num = 1\n extra = 0\n filter_horizontal = ('rule_bundles',)\n- \n+\n \n class EventAdmin(admin.ModelAdmin):\n inlines = (AttendanceEventInline, FeedbackRelationInline, CompanyInline)\n@@ -76,6 +87,16 @@\n instance.save()\n formset.save_m2m()\n \n+ def get_form(self, request, obj=None, **kwargs):\n+ form = super(EventAdmin, self).get_form(request, obj, **kwargs)\n+ form.base_fields['ingress_short'].validators=[validators.MinLengthValidator(75)]\n+ form.base_fields['ingress'].validators=[validators.MinLengthValidator(100)]\n+ form.base_fields['description'].validators=[\n+ validators.MinLengthValidator(200),\n+ validators.RegexValidator(\"^(?:(?!TBA).)*$\", _(\"Beskrivelsen kan ikke inneholde 'TBA'.\"), \"ulovlig\"),\n+ ]\n+ return form\n+\n admin.site.register(Event, EventAdmin)\n admin.site.register(Attendee, AttendeeAdmin)\n admin.site.register(AttendanceEvent, AttendanceEventAdmin)\n", "issue": "(Event) Minimum length on event description and ingress\nPossibly we should also limit the text to exclude words like TBA.\n\nEvents in ow4 demand some text in order to look good, so let's put a minimum requirement on length for the event texts. Making up a description of 200 characters should be no big deal.\n\nI've really had it with \"INFO: TBA\"\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\nfrom apps.events.models import Event\nfrom apps.events.models import AttendanceEvent\nfrom apps.events.models import Attendee\nfrom apps.events.models import CompanyEvent\nfrom apps.events.models import RuleBundle\nfrom apps.events.models import FieldOfStudyRule\nfrom apps.events.models import GradeRule\nfrom apps.events.models import UserGroupRule\n\nfrom apps.feedback.admin import FeedbackRelationInline\n\nfrom django.contrib import admin\n\n\nclass AttendeeInline(admin.TabularInline):\n model = Attendee\n extra = 1\n\n\nclass CompanyInline(admin.TabularInline):\n model = CompanyEvent\n max_num = 20\n extra = 0\n\nclass RuleBundleInline(admin.TabularInline):\n model = RuleBundle\n extra = 1\n max_num = 20\n\n\nclass AttendanceEventAdmin(admin.ModelAdmin):\n model = AttendanceEvent\n inlines = (AttendeeInline, RuleBundleInline)\n\nclass AttendeeAdmin(admin.ModelAdmin):\n model = Attendee\n list_display = ('user', 'event')\n\nclass CompanyEventAdmin(admin.ModelAdmin):\n model = CompanyEvent\n inlines = (CompanyInline,)\n\nclass RuleBundleAdmin(admin.ModelAdmin):\n model = RuleBundle\n \nclass FieldOfStudyRuleAdmin(admin.ModelAdmin):\n model = FieldOfStudyRule\n\nclass GradeRuleAdmin(admin.ModelAdmin):\n model = GradeRule\n\nclass UserGroupRuleAdmin(admin.ModelAdmin):\n model = UserGroupRule\n\nclass AttendanceEventInline(admin.StackedInline):\n model = AttendanceEvent\n max_num = 1\n extra = 0\n filter_horizontal = ('rule_bundles',)\n \n\nclass EventAdmin(admin.ModelAdmin):\n inlines = (AttendanceEventInline, FeedbackRelationInline, CompanyInline)\n exclude = (\"author\", )\n\n def save_model(self, request, obj, form, change):\n if not change: # created\n obj.author = request.user\n obj.save()\n\n def save_formset(self, request, form, formset, change):\n instances = formset.save(commit=False)\n for instance in instances:\n instance.save()\n formset.save_m2m()\n\nadmin.site.register(Event, EventAdmin)\nadmin.site.register(Attendee, AttendeeAdmin)\nadmin.site.register(AttendanceEvent, AttendanceEventAdmin)\nadmin.site.register(RuleBundle, RuleBundleAdmin)\nadmin.site.register(GradeRule, GradeRuleAdmin)\nadmin.site.register(UserGroupRule, UserGroupRuleAdmin)\nadmin.site.register(FieldOfStudyRule, FieldOfStudyRuleAdmin)\n", "path": "apps/events/admin.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.contrib import admin\nfrom django.core import validators\nfrom django.utils.translation import ugettext as _\n\nfrom apps.events.models import Event\nfrom apps.events.models import AttendanceEvent\nfrom apps.events.models import Attendee\nfrom apps.events.models import CompanyEvent\nfrom apps.events.models import RuleBundle\nfrom apps.events.models import FieldOfStudyRule\nfrom apps.events.models import GradeRule\nfrom apps.events.models import UserGroupRule\nfrom apps.feedback.admin import FeedbackRelationInline\n\n\n\nclass AttendeeInline(admin.TabularInline):\n model = Attendee\n extra = 1\n\n\nclass CompanyInline(admin.TabularInline):\n model = CompanyEvent\n max_num = 20\n extra = 0\n\n\nclass RuleBundleInline(admin.TabularInline):\n model = RuleBundle\n extra = 1\n max_num = 20\n\n\nclass AttendanceEventAdmin(admin.ModelAdmin):\n model = AttendanceEvent\n inlines = (AttendeeInline, RuleBundleInline)\n\n\nclass AttendeeAdmin(admin.ModelAdmin):\n model = Attendee\n list_display = ('user', 'event')\n\n\nclass CompanyEventAdmin(admin.ModelAdmin):\n model = CompanyEvent\n inlines = (CompanyInline,)\n\n\nclass RuleBundleAdmin(admin.ModelAdmin):\n model = RuleBundle\n\n\nclass FieldOfStudyRuleAdmin(admin.ModelAdmin):\n model = FieldOfStudyRule\n\n\nclass GradeRuleAdmin(admin.ModelAdmin):\n model = GradeRule\n\n\nclass UserGroupRuleAdmin(admin.ModelAdmin):\n model = UserGroupRule\n\n\nclass AttendanceEventInline(admin.StackedInline):\n model = AttendanceEvent\n max_num = 1\n extra = 0\n filter_horizontal = ('rule_bundles',)\n\n\nclass EventAdmin(admin.ModelAdmin):\n inlines = (AttendanceEventInline, FeedbackRelationInline, CompanyInline)\n exclude = (\"author\", )\n\n def save_model(self, request, obj, form, change):\n if not change: # created\n obj.author = request.user\n obj.save()\n\n def save_formset(self, request, form, formset, change):\n instances = formset.save(commit=False)\n for instance in instances:\n instance.save()\n formset.save_m2m()\n\n def get_form(self, request, obj=None, **kwargs):\n form = super(EventAdmin, self).get_form(request, obj, **kwargs)\n form.base_fields['ingress_short'].validators=[validators.MinLengthValidator(75)]\n form.base_fields['ingress'].validators=[validators.MinLengthValidator(100)]\n form.base_fields['description'].validators=[\n validators.MinLengthValidator(200),\n validators.RegexValidator(\"^(?:(?!TBA).)*$\", _(\"Beskrivelsen kan ikke inneholde 'TBA'.\"), \"ulovlig\"),\n ]\n return form\n\nadmin.site.register(Event, EventAdmin)\nadmin.site.register(Attendee, AttendeeAdmin)\nadmin.site.register(AttendanceEvent, AttendanceEventAdmin)\nadmin.site.register(RuleBundle, RuleBundleAdmin)\nadmin.site.register(GradeRule, GradeRuleAdmin)\nadmin.site.register(UserGroupRule, UserGroupRuleAdmin)\nadmin.site.register(FieldOfStudyRule, FieldOfStudyRuleAdmin)\n", "path": "apps/events/admin.py"}]}
1,039
622
gh_patches_debug_30808
rasdani/github-patches
git_diff
PrefectHQ__prefect-3008
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `unittest` framework raises `ResourceWarning` ## Description <!-- A clear description of the bug --> I'm using [`unittest`](https://docs.python.org/3/library/unittest.html) framework for testing purposes and then a task is running inside a `unittest.TestCase`, a `ResourceWarning` is raised. ## Expected Behavior <!-- What did you expect to happen instead? --> Run testcase without raising any warnings. ## Reproduction <!-- A minimal example that exhibits the behavior. --> `test.py` file: ```python import typing import unittest from prefect.engine.task_runner import TaskRunner from prefect.tasks.shell import ShellTask class ShellTestCase(unittest.TestCase): def test_shell_command(self) -> typing.NoReturn: runner = TaskRunner(ShellTask('ls')) runner.run() self.assertTrue(True) ``` execution: ```bash $ python -m unittest test.py [2020-07-20 16:13:20] INFO - prefect.TaskRunner | Task 'ShellTask': Starting task run... /home/psimakis/.local/share/virtualenvs/data-workflows-GfPV92cZ/lib/python3.7/site-packages/prefect/utilities/tasks.py:444: ResourceWarning: unclosed file <_io.BufferedReader name=9> return run_method(self, *args, **kwargs) ResourceWarning: Enable tracemalloc to get the object allocation traceback [2020-07-20 16:13:21] INFO - prefect.TaskRunner | Task 'ShellTask': finished task run for task with final state: 'Success' . ---------------------------------------------------------------------- Ran 1 test in 0.026s ``` ## Environment <!-- Any additional information about your environment Optionally run `prefect diagnostics` from the command line and paste the information here. --> ```json { "config_overrides": {}, "env_vars": [ "PREFECT__CONTEXT__SECRETS__....", "PREFECT__CONTEXT__SECRETS__...." ], "system_information": { "platform": "Linux-5.3.0-28-generic-x86_64-with-debian-buster-sid", "prefect_version": "0.12.3", "python_version": "3.7.3" } } ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/prefect/tasks/shell.py` Content: ``` 1 import os 2 import tempfile 3 from subprocess import PIPE, STDOUT, Popen 4 from typing import Any 5 6 import prefect 7 from prefect.utilities.tasks import defaults_from_attrs 8 9 10 class ShellTask(prefect.Task): 11 """ 12 Task for running arbitrary shell commands. 13 14 Args: 15 - command (string, optional): shell command to be executed; can also be 16 provided post-initialization by calling this task instance 17 - env (dict, optional): dictionary of environment variables to use for 18 the subprocess; can also be provided at runtime 19 - helper_script (str, optional): a string representing a shell script, which 20 will be executed prior to the `command` in the same process. Can be used to 21 change directories, define helper functions, etc. when re-using this Task 22 for different commands in a Flow 23 - shell (string, optional): shell to run the command with; defaults to "bash" 24 - return_all (bool, optional): boolean specifying whether this task 25 should return all lines of stdout as a list, or just the last line 26 as a string; defaults to `False` 27 - log_stderr (bool, optional): boolean specifying whether this task 28 should log the output from stderr in the case of a non-zero exit code; 29 defaults to `False` 30 - **kwargs: additional keyword arguments to pass to the Task constructor 31 32 Example: 33 ```python 34 from prefect import Flow 35 from prefect.tasks.shell import ShellTask 36 37 task = ShellTask(helper_script="cd ~") 38 with Flow("My Flow") as f: 39 # both tasks will be executed in home directory 40 contents = task(command='ls') 41 mv_file = task(command='mv .vimrc /.vimrc') 42 43 out = f.run() 44 ``` 45 """ 46 47 def __init__( 48 self, 49 command: str = None, 50 env: dict = None, 51 helper_script: str = None, 52 shell: str = "bash", 53 return_all: bool = False, 54 log_stderr: bool = False, 55 **kwargs: Any 56 ): 57 self.command = command 58 self.env = env 59 self.helper_script = helper_script 60 self.shell = shell 61 self.return_all = return_all 62 self.log_stderr = log_stderr 63 super().__init__(**kwargs) 64 65 @defaults_from_attrs("command", "env") 66 def run(self, command: str = None, env: dict = None) -> str: 67 """ 68 Run the shell command. 69 70 Args: 71 - command (string): shell command to be executed; can also be 72 provided at task initialization. Any variables / functions defined in 73 `self.helper_script` will be available in the same process this command 74 runs in 75 - env (dict, optional): dictionary of environment variables to use for 76 the subprocess 77 78 Returns: 79 - stdout (string): if `return_all` is `False` (the default), only 80 the last line of stdout is returned, otherwise all lines are 81 returned, which is useful for passing result of shell command 82 to other downstream tasks. If there is no output, `None` is 83 returned. 84 85 Raises: 86 - prefect.engine.signals.FAIL: if command has an exit code other 87 than 0 88 """ 89 if command is None: 90 raise TypeError("run() missing required argument: 'command'") 91 92 current_env = os.environ.copy() 93 current_env.update(env or {}) 94 with tempfile.NamedTemporaryFile(prefix="prefect-") as tmp: 95 if self.helper_script: 96 tmp.write(self.helper_script.encode()) 97 tmp.write("\n".encode()) 98 tmp.write(command.encode()) 99 tmp.flush() 100 sub_process = Popen( 101 [self.shell, tmp.name], stdout=PIPE, stderr=STDOUT, env=current_env 102 ) 103 lines = [] 104 line = None 105 for raw_line in iter(sub_process.stdout.readline, b""): 106 line = raw_line.decode("utf-8").rstrip() 107 if self.return_all: 108 lines.append(line) 109 else: 110 # if we're returning all, we don't log every line 111 self.logger.debug(line) 112 sub_process.wait() 113 if sub_process.returncode: 114 msg = "Command failed with exit code {}".format(sub_process.returncode,) 115 self.logger.error(msg) 116 117 if self.log_stderr: 118 self.logger.error("\n".join(lines)) 119 120 raise prefect.engine.signals.FAIL(msg) from None # type: ignore 121 if self.return_all: 122 return lines 123 else: 124 return line 125 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/prefect/tasks/shell.py b/src/prefect/tasks/shell.py --- a/src/prefect/tasks/shell.py +++ b/src/prefect/tasks/shell.py @@ -97,27 +97,29 @@ tmp.write("\n".encode()) tmp.write(command.encode()) tmp.flush() - sub_process = Popen( + with Popen( [self.shell, tmp.name], stdout=PIPE, stderr=STDOUT, env=current_env - ) - lines = [] - line = None - for raw_line in iter(sub_process.stdout.readline, b""): - line = raw_line.decode("utf-8").rstrip() - if self.return_all: - lines.append(line) - else: - # if we're returning all, we don't log every line - self.logger.debug(line) - sub_process.wait() - if sub_process.returncode: - msg = "Command failed with exit code {}".format(sub_process.returncode,) - self.logger.error(msg) + ) as sub_process: + lines = [] + line = None + for raw_line in iter(sub_process.stdout.readline, b""): + line = raw_line.decode("utf-8").rstrip() + if self.return_all: + lines.append(line) + else: + # if we're returning all, we don't log every line + self.logger.debug(line) + sub_process.wait() + if sub_process.returncode: + msg = "Command failed with exit code {}".format( + sub_process.returncode, + ) + self.logger.error(msg) - if self.log_stderr: - self.logger.error("\n".join(lines)) + if self.log_stderr: + self.logger.error("\n".join(lines)) - raise prefect.engine.signals.FAIL(msg) from None # type: ignore + raise prefect.engine.signals.FAIL(msg) from None # type: ignore if self.return_all: return lines else:
{"golden_diff": "diff --git a/src/prefect/tasks/shell.py b/src/prefect/tasks/shell.py\n--- a/src/prefect/tasks/shell.py\n+++ b/src/prefect/tasks/shell.py\n@@ -97,27 +97,29 @@\n tmp.write(\"\\n\".encode())\n tmp.write(command.encode())\n tmp.flush()\n- sub_process = Popen(\n+ with Popen(\n [self.shell, tmp.name], stdout=PIPE, stderr=STDOUT, env=current_env\n- )\n- lines = []\n- line = None\n- for raw_line in iter(sub_process.stdout.readline, b\"\"):\n- line = raw_line.decode(\"utf-8\").rstrip()\n- if self.return_all:\n- lines.append(line)\n- else:\n- # if we're returning all, we don't log every line\n- self.logger.debug(line)\n- sub_process.wait()\n- if sub_process.returncode:\n- msg = \"Command failed with exit code {}\".format(sub_process.returncode,)\n- self.logger.error(msg)\n+ ) as sub_process:\n+ lines = []\n+ line = None\n+ for raw_line in iter(sub_process.stdout.readline, b\"\"):\n+ line = raw_line.decode(\"utf-8\").rstrip()\n+ if self.return_all:\n+ lines.append(line)\n+ else:\n+ # if we're returning all, we don't log every line\n+ self.logger.debug(line)\n+ sub_process.wait()\n+ if sub_process.returncode:\n+ msg = \"Command failed with exit code {}\".format(\n+ sub_process.returncode,\n+ )\n+ self.logger.error(msg)\n \n- if self.log_stderr:\n- self.logger.error(\"\\n\".join(lines))\n+ if self.log_stderr:\n+ self.logger.error(\"\\n\".join(lines))\n \n- raise prefect.engine.signals.FAIL(msg) from None # type: ignore\n+ raise prefect.engine.signals.FAIL(msg) from None # type: ignore\n if self.return_all:\n return lines\n else:\n", "issue": "`unittest` framework raises `ResourceWarning`\n## Description\r\n<!-- A clear description of the bug -->\r\nI'm using [`unittest`](https://docs.python.org/3/library/unittest.html) framework for testing purposes and then a task is running inside a `unittest.TestCase`, a `ResourceWarning` is raised. \r\n\r\n\r\n## Expected Behavior\r\n<!-- What did you expect to happen instead? -->\r\nRun testcase without raising any warnings.\r\n\r\n\r\n\r\n\r\n## Reproduction\r\n<!-- A minimal example that exhibits the behavior. -->\r\n\r\n`test.py` file:\r\n\r\n```python\r\nimport typing\r\nimport unittest\r\n\r\nfrom prefect.engine.task_runner import TaskRunner\r\nfrom prefect.tasks.shell import ShellTask\r\n\r\n\r\nclass ShellTestCase(unittest.TestCase):\r\n def test_shell_command(self) -> typing.NoReturn:\r\n runner = TaskRunner(ShellTask('ls'))\r\n runner.run()\r\n self.assertTrue(True)\r\n```\r\n\r\nexecution:\r\n\r\n```bash\r\n$ python -m unittest test.py \r\n[2020-07-20 16:13:20] INFO - prefect.TaskRunner | Task 'ShellTask': Starting task run...\r\n/home/psimakis/.local/share/virtualenvs/data-workflows-GfPV92cZ/lib/python3.7/site-packages/prefect/utilities/tasks.py:444: ResourceWarning: unclosed file <_io.BufferedReader name=9>\r\n return run_method(self, *args, **kwargs)\r\nResourceWarning: Enable tracemalloc to get the object allocation traceback\r\n[2020-07-20 16:13:21] INFO - prefect.TaskRunner | Task 'ShellTask': finished task run for task with final state: 'Success'\r\n.\r\n----------------------------------------------------------------------\r\nRan 1 test in 0.026s\r\n```\r\n\r\n\r\n\r\n\r\n## Environment\r\n<!-- Any additional information about your environment\r\n\r\nOptionally run `prefect diagnostics` from the command line and paste the information here. -->\r\n```json\r\n{\r\n \"config_overrides\": {},\r\n \"env_vars\": [\r\n \"PREFECT__CONTEXT__SECRETS__....\",\r\n \"PREFECT__CONTEXT__SECRETS__....\"\r\n ],\r\n \"system_information\": {\r\n \"platform\": \"Linux-5.3.0-28-generic-x86_64-with-debian-buster-sid\",\r\n \"prefect_version\": \"0.12.3\",\r\n \"python_version\": \"3.7.3\"\r\n }\r\n}\r\n```\n", "before_files": [{"content": "import os\nimport tempfile\nfrom subprocess import PIPE, STDOUT, Popen\nfrom typing import Any\n\nimport prefect\nfrom prefect.utilities.tasks import defaults_from_attrs\n\n\nclass ShellTask(prefect.Task):\n \"\"\"\n Task for running arbitrary shell commands.\n\n Args:\n - command (string, optional): shell command to be executed; can also be\n provided post-initialization by calling this task instance\n - env (dict, optional): dictionary of environment variables to use for\n the subprocess; can also be provided at runtime\n - helper_script (str, optional): a string representing a shell script, which\n will be executed prior to the `command` in the same process. Can be used to\n change directories, define helper functions, etc. when re-using this Task\n for different commands in a Flow\n - shell (string, optional): shell to run the command with; defaults to \"bash\"\n - return_all (bool, optional): boolean specifying whether this task\n should return all lines of stdout as a list, or just the last line\n as a string; defaults to `False`\n - log_stderr (bool, optional): boolean specifying whether this task\n should log the output from stderr in the case of a non-zero exit code;\n defaults to `False`\n - **kwargs: additional keyword arguments to pass to the Task constructor\n\n Example:\n ```python\n from prefect import Flow\n from prefect.tasks.shell import ShellTask\n\n task = ShellTask(helper_script=\"cd ~\")\n with Flow(\"My Flow\") as f:\n # both tasks will be executed in home directory\n contents = task(command='ls')\n mv_file = task(command='mv .vimrc /.vimrc')\n\n out = f.run()\n ```\n \"\"\"\n\n def __init__(\n self,\n command: str = None,\n env: dict = None,\n helper_script: str = None,\n shell: str = \"bash\",\n return_all: bool = False,\n log_stderr: bool = False,\n **kwargs: Any\n ):\n self.command = command\n self.env = env\n self.helper_script = helper_script\n self.shell = shell\n self.return_all = return_all\n self.log_stderr = log_stderr\n super().__init__(**kwargs)\n\n @defaults_from_attrs(\"command\", \"env\")\n def run(self, command: str = None, env: dict = None) -> str:\n \"\"\"\n Run the shell command.\n\n Args:\n - command (string): shell command to be executed; can also be\n provided at task initialization. Any variables / functions defined in\n `self.helper_script` will be available in the same process this command\n runs in\n - env (dict, optional): dictionary of environment variables to use for\n the subprocess\n\n Returns:\n - stdout (string): if `return_all` is `False` (the default), only\n the last line of stdout is returned, otherwise all lines are\n returned, which is useful for passing result of shell command\n to other downstream tasks. If there is no output, `None` is\n returned.\n\n Raises:\n - prefect.engine.signals.FAIL: if command has an exit code other\n than 0\n \"\"\"\n if command is None:\n raise TypeError(\"run() missing required argument: 'command'\")\n\n current_env = os.environ.copy()\n current_env.update(env or {})\n with tempfile.NamedTemporaryFile(prefix=\"prefect-\") as tmp:\n if self.helper_script:\n tmp.write(self.helper_script.encode())\n tmp.write(\"\\n\".encode())\n tmp.write(command.encode())\n tmp.flush()\n sub_process = Popen(\n [self.shell, tmp.name], stdout=PIPE, stderr=STDOUT, env=current_env\n )\n lines = []\n line = None\n for raw_line in iter(sub_process.stdout.readline, b\"\"):\n line = raw_line.decode(\"utf-8\").rstrip()\n if self.return_all:\n lines.append(line)\n else:\n # if we're returning all, we don't log every line\n self.logger.debug(line)\n sub_process.wait()\n if sub_process.returncode:\n msg = \"Command failed with exit code {}\".format(sub_process.returncode,)\n self.logger.error(msg)\n\n if self.log_stderr:\n self.logger.error(\"\\n\".join(lines))\n\n raise prefect.engine.signals.FAIL(msg) from None # type: ignore\n if self.return_all:\n return lines\n else:\n return line\n", "path": "src/prefect/tasks/shell.py"}], "after_files": [{"content": "import os\nimport tempfile\nfrom subprocess import PIPE, STDOUT, Popen\nfrom typing import Any\n\nimport prefect\nfrom prefect.utilities.tasks import defaults_from_attrs\n\n\nclass ShellTask(prefect.Task):\n \"\"\"\n Task for running arbitrary shell commands.\n\n Args:\n - command (string, optional): shell command to be executed; can also be\n provided post-initialization by calling this task instance\n - env (dict, optional): dictionary of environment variables to use for\n the subprocess; can also be provided at runtime\n - helper_script (str, optional): a string representing a shell script, which\n will be executed prior to the `command` in the same process. Can be used to\n change directories, define helper functions, etc. when re-using this Task\n for different commands in a Flow\n - shell (string, optional): shell to run the command with; defaults to \"bash\"\n - return_all (bool, optional): boolean specifying whether this task\n should return all lines of stdout as a list, or just the last line\n as a string; defaults to `False`\n - log_stderr (bool, optional): boolean specifying whether this task\n should log the output from stderr in the case of a non-zero exit code;\n defaults to `False`\n - **kwargs: additional keyword arguments to pass to the Task constructor\n\n Example:\n ```python\n from prefect import Flow\n from prefect.tasks.shell import ShellTask\n\n task = ShellTask(helper_script=\"cd ~\")\n with Flow(\"My Flow\") as f:\n # both tasks will be executed in home directory\n contents = task(command='ls')\n mv_file = task(command='mv .vimrc /.vimrc')\n\n out = f.run()\n ```\n \"\"\"\n\n def __init__(\n self,\n command: str = None,\n env: dict = None,\n helper_script: str = None,\n shell: str = \"bash\",\n return_all: bool = False,\n log_stderr: bool = False,\n **kwargs: Any\n ):\n self.command = command\n self.env = env\n self.helper_script = helper_script\n self.shell = shell\n self.return_all = return_all\n self.log_stderr = log_stderr\n super().__init__(**kwargs)\n\n @defaults_from_attrs(\"command\", \"env\")\n def run(self, command: str = None, env: dict = None) -> str:\n \"\"\"\n Run the shell command.\n\n Args:\n - command (string): shell command to be executed; can also be\n provided at task initialization. Any variables / functions defined in\n `self.helper_script` will be available in the same process this command\n runs in\n - env (dict, optional): dictionary of environment variables to use for\n the subprocess\n\n Returns:\n - stdout (string): if `return_all` is `False` (the default), only\n the last line of stdout is returned, otherwise all lines are\n returned, which is useful for passing result of shell command\n to other downstream tasks. If there is no output, `None` is\n returned.\n\n Raises:\n - prefect.engine.signals.FAIL: if command has an exit code other\n than 0\n \"\"\"\n if command is None:\n raise TypeError(\"run() missing required argument: 'command'\")\n\n current_env = os.environ.copy()\n current_env.update(env or {})\n with tempfile.NamedTemporaryFile(prefix=\"prefect-\") as tmp:\n if self.helper_script:\n tmp.write(self.helper_script.encode())\n tmp.write(\"\\n\".encode())\n tmp.write(command.encode())\n tmp.flush()\n with Popen(\n [self.shell, tmp.name], stdout=PIPE, stderr=STDOUT, env=current_env\n ) as sub_process:\n lines = []\n line = None\n for raw_line in iter(sub_process.stdout.readline, b\"\"):\n line = raw_line.decode(\"utf-8\").rstrip()\n if self.return_all:\n lines.append(line)\n else:\n # if we're returning all, we don't log every line\n self.logger.debug(line)\n sub_process.wait()\n if sub_process.returncode:\n msg = \"Command failed with exit code {}\".format(\n sub_process.returncode,\n )\n self.logger.error(msg)\n\n if self.log_stderr:\n self.logger.error(\"\\n\".join(lines))\n\n raise prefect.engine.signals.FAIL(msg) from None # type: ignore\n if self.return_all:\n return lines\n else:\n return line\n", "path": "src/prefect/tasks/shell.py"}]}
2,012
447
gh_patches_debug_593
rasdani/github-patches
git_diff
projectmesa__mesa-1437
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- v1.1.0 Safford Release Milestone: https://github.com/projectmesa/mesa/milestone/31 Highlighted changes: - #1376 > 6x perf speedup for add/remove agent in `ContinuousSpace` - #1391 correctness fix for `SimultaneousActivation` and `StagedActivation` - #1399 make `self.running = True` optional. We need to tell existing users that initializing this is no longer necessary, and so, reducing the boilerplate code - #1435 Allow user-specified local dir to be served by Tornado. Needed by Mesa-Geo - #1413 Allow batch_run to take arbitrary parameters --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mesa/__init__.py` Content: ``` 1 """ 2 Mesa Agent-Based Modeling Framework 3 4 Core Objects: Model, and Agent. 5 6 """ 7 import datetime 8 9 from mesa.model import Model 10 from mesa.agent import Agent 11 12 import mesa.time as time 13 import mesa.space as space 14 import mesa.flat.visualization as visualization 15 from mesa.datacollection import DataCollector 16 from mesa.batchrunner import batch_run # noqa 17 18 __all__ = [ 19 "Model", 20 "Agent", 21 "time", 22 "space", 23 "visualization", 24 "DataCollector", 25 "batch_run", 26 ] 27 28 __title__ = "mesa" 29 __version__ = "1.0.0" 30 __license__ = "Apache 2.0" 31 __copyright__ = f"Copyright {datetime.date.today().year} Project Mesa Team" 32 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/mesa/__init__.py b/mesa/__init__.py --- a/mesa/__init__.py +++ b/mesa/__init__.py @@ -26,6 +26,6 @@ ] __title__ = "mesa" -__version__ = "1.0.0" +__version__ = "1.1.0" __license__ = "Apache 2.0" __copyright__ = f"Copyright {datetime.date.today().year} Project Mesa Team"
{"golden_diff": "diff --git a/mesa/__init__.py b/mesa/__init__.py\n--- a/mesa/__init__.py\n+++ b/mesa/__init__.py\n@@ -26,6 +26,6 @@\n ]\n \n __title__ = \"mesa\"\n-__version__ = \"1.0.0\"\n+__version__ = \"1.1.0\"\n __license__ = \"Apache 2.0\"\n __copyright__ = f\"Copyright {datetime.date.today().year} Project Mesa Team\"\n", "issue": "v1.1.0 Safford Release\nMilestone: https://github.com/projectmesa/mesa/milestone/31\r\n\r\nHighlighted changes:\r\n- #1376 > 6x perf speedup for add/remove agent in `ContinuousSpace`\r\n- #1391 correctness fix for `SimultaneousActivation` and `StagedActivation`\r\n- #1399 make `self.running = True` optional. We need to tell existing users that initializing this is no longer necessary, and so, reducing the boilerplate code\r\n- #1435 Allow user-specified local dir to be served by Tornado. Needed by Mesa-Geo\r\n- #1413 Allow batch_run to take arbitrary parameters\n", "before_files": [{"content": "\"\"\"\nMesa Agent-Based Modeling Framework\n\nCore Objects: Model, and Agent.\n\n\"\"\"\nimport datetime\n\nfrom mesa.model import Model\nfrom mesa.agent import Agent\n\nimport mesa.time as time\nimport mesa.space as space\nimport mesa.flat.visualization as visualization\nfrom mesa.datacollection import DataCollector\nfrom mesa.batchrunner import batch_run # noqa\n\n__all__ = [\n \"Model\",\n \"Agent\",\n \"time\",\n \"space\",\n \"visualization\",\n \"DataCollector\",\n \"batch_run\",\n]\n\n__title__ = \"mesa\"\n__version__ = \"1.0.0\"\n__license__ = \"Apache 2.0\"\n__copyright__ = f\"Copyright {datetime.date.today().year} Project Mesa Team\"\n", "path": "mesa/__init__.py"}], "after_files": [{"content": "\"\"\"\nMesa Agent-Based Modeling Framework\n\nCore Objects: Model, and Agent.\n\n\"\"\"\nimport datetime\n\nfrom mesa.model import Model\nfrom mesa.agent import Agent\n\nimport mesa.time as time\nimport mesa.space as space\nimport mesa.flat.visualization as visualization\nfrom mesa.datacollection import DataCollector\nfrom mesa.batchrunner import batch_run # noqa\n\n__all__ = [\n \"Model\",\n \"Agent\",\n \"time\",\n \"space\",\n \"visualization\",\n \"DataCollector\",\n \"batch_run\",\n]\n\n__title__ = \"mesa\"\n__version__ = \"1.1.0\"\n__license__ = \"Apache 2.0\"\n__copyright__ = f\"Copyright {datetime.date.today().year} Project Mesa Team\"\n", "path": "mesa/__init__.py"}]}
626
111
gh_patches_debug_31948
rasdani/github-patches
git_diff
redis__redis-py-1791
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- redis-py version attribute should be decoupled from the redis module Following the conversation from https://github.com/redis/redis-py/issues/1625#issuecomment-991744836 looks like importing `redis` module prior to installation in `setup.py` for `version` attribute is not ideal. Currently there are two places where module version is required. - `setup.py` for module installation - `redis/__init__.py` for module level `__version__` attribute One way to fix this is to maintain a `version.py` file in top level directory and using that as source of truth in both the above places. @chayim @hartwork What do you think? I can create a PR for this :) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 #!/usr/bin/env python 2 from setuptools import find_packages, setup 3 4 import redis 5 6 setup( 7 name="redis", 8 description="Python client for Redis database and key-value store", 9 long_description=open("README.md").read().strip(), 10 long_description_content_type="text/markdown", 11 keywords=["Redis", "key-value store", "database"], 12 license="MIT", 13 version=redis.__version__, 14 packages=find_packages( 15 include=[ 16 "redis", 17 "redis.commands", 18 "redis.commands.bf", 19 "redis.commands.json", 20 "redis.commands.search", 21 "redis.commands.timeseries", 22 "redis.commands.graph", 23 ] 24 ), 25 url="https://github.com/redis/redis-py", 26 author="Redis Inc.", 27 author_email="[email protected]", 28 python_requires=">=3.6", 29 setup_requires=[ 30 "packaging>=21.3", 31 ], 32 install_requires=[ 33 "deprecated>=1.2.3", 34 "packaging>=21.3", 35 ], 36 classifiers=[ 37 "Development Status :: 5 - Production/Stable", 38 "Environment :: Console", 39 "Intended Audience :: Developers", 40 "License :: OSI Approved :: MIT License", 41 "Operating System :: OS Independent", 42 "Programming Language :: Python", 43 "Programming Language :: Python :: 3", 44 "Programming Language :: Python :: 3 :: Only", 45 "Programming Language :: Python :: 3.6", 46 "Programming Language :: Python :: 3.7", 47 "Programming Language :: Python :: 3.8", 48 "Programming Language :: Python :: 3.9", 49 "Programming Language :: Python :: 3.10", 50 "Programming Language :: Python :: Implementation :: CPython", 51 "Programming Language :: Python :: Implementation :: PyPy", 52 ], 53 extras_require={ 54 "hiredis": ["hiredis>=1.0.0"], 55 }, 56 ) 57 ``` Path: `redis/__init__.py` Content: ``` 1 from redis.client import Redis, StrictRedis 2 from redis.cluster import RedisCluster 3 from redis.connection import ( 4 BlockingConnectionPool, 5 Connection, 6 ConnectionPool, 7 SSLConnection, 8 UnixDomainSocketConnection, 9 ) 10 from redis.exceptions import ( 11 AuthenticationError, 12 AuthenticationWrongNumberOfArgsError, 13 BusyLoadingError, 14 ChildDeadlockedError, 15 ConnectionError, 16 DataError, 17 InvalidResponse, 18 PubSubError, 19 ReadOnlyError, 20 RedisError, 21 ResponseError, 22 TimeoutError, 23 WatchError, 24 ) 25 from redis.sentinel import ( 26 Sentinel, 27 SentinelConnectionPool, 28 SentinelManagedConnection, 29 SentinelManagedSSLConnection, 30 ) 31 from redis.utils import from_url 32 33 34 def int_or_str(value): 35 try: 36 return int(value) 37 except ValueError: 38 return value 39 40 41 __version__ = "4.1.0rc2" 42 43 44 VERSION = tuple(map(int_or_str, __version__.split("."))) 45 46 __all__ = [ 47 "AuthenticationError", 48 "AuthenticationWrongNumberOfArgsError", 49 "BlockingConnectionPool", 50 "BusyLoadingError", 51 "ChildDeadlockedError", 52 "Connection", 53 "ConnectionError", 54 "ConnectionPool", 55 "DataError", 56 "from_url", 57 "InvalidResponse", 58 "PubSubError", 59 "ReadOnlyError", 60 "Redis", 61 "RedisCluster", 62 "RedisError", 63 "ResponseError", 64 "Sentinel", 65 "SentinelConnectionPool", 66 "SentinelManagedConnection", 67 "SentinelManagedSSLConnection", 68 "SSLConnection", 69 "StrictRedis", 70 "TimeoutError", 71 "UnixDomainSocketConnection", 72 "WatchError", 73 ] 74 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/redis/__init__.py b/redis/__init__.py --- a/redis/__init__.py +++ b/redis/__init__.py @@ -1,3 +1,10 @@ +import sys + +if sys.version_info >= (3, 8): + from importlib import metadata +else: + import importlib_metadata as metadata + from redis.client import Redis, StrictRedis from redis.cluster import RedisCluster from redis.connection import ( @@ -38,7 +45,10 @@ return value -__version__ = "4.1.0rc2" +try: + __version__ = metadata.version("redis") +except metadata.PackageNotFoundError: + __version__ = "99.99.99" VERSION = tuple(map(int_or_str, __version__.split("."))) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,8 +1,6 @@ #!/usr/bin/env python from setuptools import find_packages, setup -import redis - setup( name="redis", description="Python client for Redis database and key-value store", @@ -10,7 +8,7 @@ long_description_content_type="text/markdown", keywords=["Redis", "key-value store", "database"], license="MIT", - version=redis.__version__, + version="4.1.0rc2", packages=find_packages( include=[ "redis", @@ -26,12 +24,10 @@ author="Redis Inc.", author_email="[email protected]", python_requires=">=3.6", - setup_requires=[ - "packaging>=21.3", - ], install_requires=[ "deprecated>=1.2.3", "packaging>=21.3", + 'importlib-metadata >= 1.0; python_version < "3.8"', ], classifiers=[ "Development Status :: 5 - Production/Stable",
{"golden_diff": "diff --git a/redis/__init__.py b/redis/__init__.py\n--- a/redis/__init__.py\n+++ b/redis/__init__.py\n@@ -1,3 +1,10 @@\n+import sys\n+\n+if sys.version_info >= (3, 8):\n+ from importlib import metadata\n+else:\n+ import importlib_metadata as metadata\n+\n from redis.client import Redis, StrictRedis\n from redis.cluster import RedisCluster\n from redis.connection import (\n@@ -38,7 +45,10 @@\n return value\n \n \n-__version__ = \"4.1.0rc2\"\n+try:\n+ __version__ = metadata.version(\"redis\")\n+except metadata.PackageNotFoundError:\n+ __version__ = \"99.99.99\"\n \n \n VERSION = tuple(map(int_or_str, __version__.split(\".\")))\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -1,8 +1,6 @@\n #!/usr/bin/env python\n from setuptools import find_packages, setup\n \n-import redis\n-\n setup(\n name=\"redis\",\n description=\"Python client for Redis database and key-value store\",\n@@ -10,7 +8,7 @@\n long_description_content_type=\"text/markdown\",\n keywords=[\"Redis\", \"key-value store\", \"database\"],\n license=\"MIT\",\n- version=redis.__version__,\n+ version=\"4.1.0rc2\",\n packages=find_packages(\n include=[\n \"redis\",\n@@ -26,12 +24,10 @@\n author=\"Redis Inc.\",\n author_email=\"[email protected]\",\n python_requires=\">=3.6\",\n- setup_requires=[\n- \"packaging>=21.3\",\n- ],\n install_requires=[\n \"deprecated>=1.2.3\",\n \"packaging>=21.3\",\n+ 'importlib-metadata >= 1.0; python_version < \"3.8\"',\n ],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n", "issue": "redis-py version attribute should be decoupled from the redis module\nFollowing the conversation from https://github.com/redis/redis-py/issues/1625#issuecomment-991744836 looks like importing `redis` module prior to installation in `setup.py` for `version` attribute is not ideal.\r\n\r\nCurrently there are two places where module version is required.\r\n- `setup.py` for module installation\r\n- `redis/__init__.py` for module level `__version__` attribute\r\n\r\nOne way to fix this is to maintain a `version.py` file in top level directory and using that as source of truth in both the above places. \r\n\r\n@chayim @hartwork What do you think? I can create a PR for this :)\n", "before_files": [{"content": "#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\nimport redis\n\nsetup(\n name=\"redis\",\n description=\"Python client for Redis database and key-value store\",\n long_description=open(\"README.md\").read().strip(),\n long_description_content_type=\"text/markdown\",\n keywords=[\"Redis\", \"key-value store\", \"database\"],\n license=\"MIT\",\n version=redis.__version__,\n packages=find_packages(\n include=[\n \"redis\",\n \"redis.commands\",\n \"redis.commands.bf\",\n \"redis.commands.json\",\n \"redis.commands.search\",\n \"redis.commands.timeseries\",\n \"redis.commands.graph\",\n ]\n ),\n url=\"https://github.com/redis/redis-py\",\n author=\"Redis Inc.\",\n author_email=\"[email protected]\",\n python_requires=\">=3.6\",\n setup_requires=[\n \"packaging>=21.3\",\n ],\n install_requires=[\n \"deprecated>=1.2.3\",\n \"packaging>=21.3\",\n ],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n ],\n extras_require={\n \"hiredis\": [\"hiredis>=1.0.0\"],\n },\n)\n", "path": "setup.py"}, {"content": "from redis.client import Redis, StrictRedis\nfrom redis.cluster import RedisCluster\nfrom redis.connection import (\n BlockingConnectionPool,\n Connection,\n ConnectionPool,\n SSLConnection,\n UnixDomainSocketConnection,\n)\nfrom redis.exceptions import (\n AuthenticationError,\n AuthenticationWrongNumberOfArgsError,\n BusyLoadingError,\n ChildDeadlockedError,\n ConnectionError,\n DataError,\n InvalidResponse,\n PubSubError,\n ReadOnlyError,\n RedisError,\n ResponseError,\n TimeoutError,\n WatchError,\n)\nfrom redis.sentinel import (\n Sentinel,\n SentinelConnectionPool,\n SentinelManagedConnection,\n SentinelManagedSSLConnection,\n)\nfrom redis.utils import from_url\n\n\ndef int_or_str(value):\n try:\n return int(value)\n except ValueError:\n return value\n\n\n__version__ = \"4.1.0rc2\"\n\n\nVERSION = tuple(map(int_or_str, __version__.split(\".\")))\n\n__all__ = [\n \"AuthenticationError\",\n \"AuthenticationWrongNumberOfArgsError\",\n \"BlockingConnectionPool\",\n \"BusyLoadingError\",\n \"ChildDeadlockedError\",\n \"Connection\",\n \"ConnectionError\",\n \"ConnectionPool\",\n \"DataError\",\n \"from_url\",\n \"InvalidResponse\",\n \"PubSubError\",\n \"ReadOnlyError\",\n \"Redis\",\n \"RedisCluster\",\n \"RedisError\",\n \"ResponseError\",\n \"Sentinel\",\n \"SentinelConnectionPool\",\n \"SentinelManagedConnection\",\n \"SentinelManagedSSLConnection\",\n \"SSLConnection\",\n \"StrictRedis\",\n \"TimeoutError\",\n \"UnixDomainSocketConnection\",\n \"WatchError\",\n]\n", "path": "redis/__init__.py"}], "after_files": [{"content": "#!/usr/bin/env python\nfrom setuptools import find_packages, setup\n\nsetup(\n name=\"redis\",\n description=\"Python client for Redis database and key-value store\",\n long_description=open(\"README.md\").read().strip(),\n long_description_content_type=\"text/markdown\",\n keywords=[\"Redis\", \"key-value store\", \"database\"],\n license=\"MIT\",\n version=\"4.1.0rc2\",\n packages=find_packages(\n include=[\n \"redis\",\n \"redis.commands\",\n \"redis.commands.bf\",\n \"redis.commands.json\",\n \"redis.commands.search\",\n \"redis.commands.timeseries\",\n \"redis.commands.graph\",\n ]\n ),\n url=\"https://github.com/redis/redis-py\",\n author=\"Redis Inc.\",\n author_email=\"[email protected]\",\n python_requires=\">=3.6\",\n install_requires=[\n \"deprecated>=1.2.3\",\n \"packaging>=21.3\",\n 'importlib-metadata >= 1.0; python_version < \"3.8\"',\n ],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Programming Language :: Python :: Implementation :: PyPy\",\n ],\n extras_require={\n \"hiredis\": [\"hiredis>=1.0.0\"],\n },\n)\n", "path": "setup.py"}, {"content": "import sys\n\nif sys.version_info >= (3, 8):\n from importlib import metadata\nelse:\n import importlib_metadata as metadata\n\nfrom redis.client import Redis, StrictRedis\nfrom redis.cluster import RedisCluster\nfrom redis.connection import (\n BlockingConnectionPool,\n Connection,\n ConnectionPool,\n SSLConnection,\n UnixDomainSocketConnection,\n)\nfrom redis.exceptions import (\n AuthenticationError,\n AuthenticationWrongNumberOfArgsError,\n BusyLoadingError,\n ChildDeadlockedError,\n ConnectionError,\n DataError,\n InvalidResponse,\n PubSubError,\n ReadOnlyError,\n RedisError,\n ResponseError,\n TimeoutError,\n WatchError,\n)\nfrom redis.sentinel import (\n Sentinel,\n SentinelConnectionPool,\n SentinelManagedConnection,\n SentinelManagedSSLConnection,\n)\nfrom redis.utils import from_url\n\n\ndef int_or_str(value):\n try:\n return int(value)\n except ValueError:\n return value\n\n\ntry:\n __version__ = metadata.version(\"redis\")\nexcept metadata.PackageNotFoundError:\n __version__ = \"99.99.99\"\n\n\nVERSION = tuple(map(int_or_str, __version__.split(\".\")))\n\n__all__ = [\n \"AuthenticationError\",\n \"AuthenticationWrongNumberOfArgsError\",\n \"BlockingConnectionPool\",\n \"BusyLoadingError\",\n \"ChildDeadlockedError\",\n \"Connection\",\n \"ConnectionError\",\n \"ConnectionPool\",\n \"DataError\",\n \"from_url\",\n \"InvalidResponse\",\n \"PubSubError\",\n \"ReadOnlyError\",\n \"Redis\",\n \"RedisCluster\",\n \"RedisError\",\n \"ResponseError\",\n \"Sentinel\",\n \"SentinelConnectionPool\",\n \"SentinelManagedConnection\",\n \"SentinelManagedSSLConnection\",\n \"SSLConnection\",\n \"StrictRedis\",\n \"TimeoutError\",\n \"UnixDomainSocketConnection\",\n \"WatchError\",\n]\n", "path": "redis/__init__.py"}]}
1,434
447
gh_patches_debug_32341
rasdani/github-patches
git_diff
zulip__zulip-3217
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- contrib_bots: Prevent runaway bots with rate limiting It's possible to create a runaway bot if you have a bot send a message to certain stimuli that in turns becomes a stimulus for the bot to send another message and so on and so forth. We can prevent that in `contrib_bots/run.py` by adding some logic to prevent runaway bots. Right now RestrictedClient make self.send_message just be client.send_message, but we can instead have a wrapper like this: ``` def send_message(self, *args, **kwargs): self.rate_limit() self.client.send_message(*args, **kwargs) ``` And then have appropriate logic in `rate_limit()` and some state variable to make sure less than N messages have been sent in the last second. It might make sense to have a small class for rate limiting that RestrictedClient uses an instance of. You can do a pretty naive rate limiting scheme where you just keep the last N timestamps in a Python list and truncate it off the front as new sends come in and the list grows to size N+1. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `contrib_bots/run.py` Content: ``` 1 #!/usr/bin/env python 2 from __future__ import print_function 3 4 import importlib 5 import logging 6 import optparse 7 import os 8 import sys 9 10 our_dir = os.path.dirname(os.path.abspath(__file__)) 11 12 # For dev setups, we can find the API in the repo itself. 13 if os.path.exists(os.path.join(our_dir, '../api/zulip')): 14 sys.path.insert(0, '../api') 15 16 from zulip import Client 17 18 class RestrictedClient(object): 19 def __init__(self, client): 20 # Only expose a subset of our Client's functionality 21 user_profile = client.get_profile() 22 self.send_message = client.send_message 23 try: 24 self.full_name = user_profile['full_name'] 25 self.email = user_profile['email'] 26 except KeyError: 27 logging.error('Cannot fetch user profile, make sure you have set' 28 ' up the zuliprc file correctly.') 29 sys.exit(1) 30 31 def get_lib_module(lib_fn): 32 lib_fn = os.path.abspath(lib_fn) 33 if not os.path.dirname(lib_fn).startswith(os.path.join(our_dir, 'lib')): 34 print('Sorry, we will only import code from contrib_bots/lib.') 35 sys.exit(1) 36 37 if not lib_fn.endswith('.py'): 38 print('Please use a .py extension for library files.') 39 sys.exit(1) 40 41 sys.path.append('lib') 42 base_lib_fn = os.path.basename(os.path.splitext(lib_fn)[0]) 43 module_name = 'lib.' + base_lib_fn 44 module = importlib.import_module(module_name) 45 return module 46 47 def run_message_handler_for_bot(lib_module, quiet, config_file): 48 # Make sure you set up your ~/.zuliprc 49 client = Client(config_file=config_file) 50 restricted_client = RestrictedClient(client) 51 52 message_handler = lib_module.handler_class() 53 54 class StateHandler(object): 55 def __init__(self): 56 self.state = None 57 58 def set_state(self, state): 59 self.state = state 60 61 def get_state(self): 62 return self.state 63 64 state_handler = StateHandler() 65 66 if not quiet: 67 print(message_handler.usage()) 68 69 def handle_message(message): 70 logging.info('waiting for next message') 71 if message_handler.triage_message(message=message, 72 client=restricted_client): 73 message_handler.handle_message( 74 message=message, 75 client=restricted_client, 76 state_handler=state_handler 77 ) 78 79 logging.info('starting message handling...') 80 client.call_on_each_message(handle_message) 81 82 def run(): 83 usage = ''' 84 ./run.py <lib file> 85 86 Example: ./run.py lib/followup.py 87 88 (This program loads bot-related code from the 89 library code and then runs a message loop, 90 feeding messages to the library code to handle.) 91 92 Please make sure you have a current ~/.zuliprc 93 file with the credentials you want to use for 94 this bot. 95 96 See lib/readme.md for more context. 97 ''' 98 99 parser = optparse.OptionParser(usage=usage) 100 parser.add_option('--quiet', '-q', 101 action='store_true', 102 help='Turn off logging output.') 103 parser.add_option('--config-file', 104 action='store', 105 help='(alternate config file to ~/.zuliprc)') 106 (options, args) = parser.parse_args() 107 108 if len(args) == 0: 109 print('You must specify a library!') 110 sys.exit(1) 111 112 lib_module = get_lib_module(lib_fn=args[0]) 113 114 if not options.quiet: 115 logging.basicConfig(stream=sys.stdout, level=logging.INFO) 116 117 run_message_handler_for_bot( 118 lib_module=lib_module, 119 config_file=options.config_file, 120 quiet=options.quiet 121 ) 122 123 if __name__ == '__main__': 124 run() 125 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/contrib_bots/run.py b/contrib_bots/run.py --- a/contrib_bots/run.py +++ b/contrib_bots/run.py @@ -6,6 +6,7 @@ import optparse import os import sys +import time our_dir = os.path.dirname(os.path.abspath(__file__)) @@ -15,11 +16,27 @@ from zulip import Client +class RateLimit(object): + def __init__(self, message_limit, interval_limit): + self.message_limit = message_limit + self.interval_limit = interval_limit + self.message_list = [] + + def is_legal(self): + self.message_list.append(time.time()) + if len(self.message_list) > self.message_limit: + self.message_list.pop(0) + time_diff = self.message_list[-1] - self.message_list[0] + return time_diff >= self.interval_limit + else: + return True + class RestrictedClient(object): def __init__(self, client): # Only expose a subset of our Client's functionality user_profile = client.get_profile() - self.send_message = client.send_message + self.rate_limit = RateLimit(20, 5) + self.client = client try: self.full_name = user_profile['full_name'] self.email = user_profile['email'] @@ -28,6 +45,15 @@ ' up the zuliprc file correctly.') sys.exit(1) + def send_message(self, *args, **kwargs): + if self.rate_limit.is_legal(): + self.client.send_message(*args, **kwargs) + else: + logging.error('-----> !*!*!*MESSAGE RATE LIMIT REACHED, EXITING*!*!*! <-----\n' + 'Is your bot trapped in an infinite loop by reacting to' + ' its own messages?') + sys.exit(1) + def get_lib_module(lib_fn): lib_fn = os.path.abspath(lib_fn) if not os.path.dirname(lib_fn).startswith(os.path.join(our_dir, 'lib')):
{"golden_diff": "diff --git a/contrib_bots/run.py b/contrib_bots/run.py\n--- a/contrib_bots/run.py\n+++ b/contrib_bots/run.py\n@@ -6,6 +6,7 @@\n import optparse\n import os\n import sys\n+import time\n \n our_dir = os.path.dirname(os.path.abspath(__file__))\n \n@@ -15,11 +16,27 @@\n \n from zulip import Client\n \n+class RateLimit(object):\n+ def __init__(self, message_limit, interval_limit):\n+ self.message_limit = message_limit\n+ self.interval_limit = interval_limit\n+ self.message_list = []\n+\n+ def is_legal(self):\n+ self.message_list.append(time.time())\n+ if len(self.message_list) > self.message_limit:\n+ self.message_list.pop(0)\n+ time_diff = self.message_list[-1] - self.message_list[0]\n+ return time_diff >= self.interval_limit\n+ else:\n+ return True\n+\n class RestrictedClient(object):\n def __init__(self, client):\n # Only expose a subset of our Client's functionality\n user_profile = client.get_profile()\n- self.send_message = client.send_message\n+ self.rate_limit = RateLimit(20, 5)\n+ self.client = client\n try:\n self.full_name = user_profile['full_name']\n self.email = user_profile['email']\n@@ -28,6 +45,15 @@\n ' up the zuliprc file correctly.')\n sys.exit(1)\n \n+ def send_message(self, *args, **kwargs):\n+ if self.rate_limit.is_legal():\n+ self.client.send_message(*args, **kwargs)\n+ else:\n+ logging.error('-----> !*!*!*MESSAGE RATE LIMIT REACHED, EXITING*!*!*! <-----\\n'\n+ 'Is your bot trapped in an infinite loop by reacting to'\n+ ' its own messages?')\n+ sys.exit(1)\n+\n def get_lib_module(lib_fn):\n lib_fn = os.path.abspath(lib_fn)\n if not os.path.dirname(lib_fn).startswith(os.path.join(our_dir, 'lib')):\n", "issue": "contrib_bots: Prevent runaway bots with rate limiting\nIt's possible to create a runaway bot if you have a bot send a message to certain stimuli that in turns becomes a stimulus for the bot to send another message and so on and so forth.\r\n\r\nWe can prevent that in `contrib_bots/run.py` by adding some logic to prevent runaway bots.\r\n\r\nRight now RestrictedClient make self.send_message just be client.send_message, but we can instead have a wrapper like this:\r\n\r\n```\r\ndef send_message(self, *args, **kwargs):\r\n self.rate_limit()\r\n self.client.send_message(*args, **kwargs)\r\n```\r\n\r\nAnd then have appropriate logic in `rate_limit()` and some state variable to make sure less than N messages have been sent in the last second. It might make sense to have a small class for rate limiting that RestrictedClient uses an instance of.\r\n\r\nYou can do a pretty naive rate limiting scheme where you just keep the last N timestamps in a Python list and truncate it off the front as new sends come in and the list grows to size N+1.\n", "before_files": [{"content": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport importlib\nimport logging\nimport optparse\nimport os\nimport sys\n\nour_dir = os.path.dirname(os.path.abspath(__file__))\n\n# For dev setups, we can find the API in the repo itself.\nif os.path.exists(os.path.join(our_dir, '../api/zulip')):\n sys.path.insert(0, '../api')\n\nfrom zulip import Client\n\nclass RestrictedClient(object):\n def __init__(self, client):\n # Only expose a subset of our Client's functionality\n user_profile = client.get_profile()\n self.send_message = client.send_message\n try:\n self.full_name = user_profile['full_name']\n self.email = user_profile['email']\n except KeyError:\n logging.error('Cannot fetch user profile, make sure you have set'\n ' up the zuliprc file correctly.')\n sys.exit(1)\n\ndef get_lib_module(lib_fn):\n lib_fn = os.path.abspath(lib_fn)\n if not os.path.dirname(lib_fn).startswith(os.path.join(our_dir, 'lib')):\n print('Sorry, we will only import code from contrib_bots/lib.')\n sys.exit(1)\n\n if not lib_fn.endswith('.py'):\n print('Please use a .py extension for library files.')\n sys.exit(1)\n\n sys.path.append('lib')\n base_lib_fn = os.path.basename(os.path.splitext(lib_fn)[0])\n module_name = 'lib.' + base_lib_fn\n module = importlib.import_module(module_name)\n return module\n\ndef run_message_handler_for_bot(lib_module, quiet, config_file):\n # Make sure you set up your ~/.zuliprc\n client = Client(config_file=config_file)\n restricted_client = RestrictedClient(client)\n\n message_handler = lib_module.handler_class()\n\n class StateHandler(object):\n def __init__(self):\n self.state = None\n\n def set_state(self, state):\n self.state = state\n\n def get_state(self):\n return self.state\n\n state_handler = StateHandler()\n\n if not quiet:\n print(message_handler.usage())\n\n def handle_message(message):\n logging.info('waiting for next message')\n if message_handler.triage_message(message=message,\n client=restricted_client):\n message_handler.handle_message(\n message=message,\n client=restricted_client,\n state_handler=state_handler\n )\n\n logging.info('starting message handling...')\n client.call_on_each_message(handle_message)\n\ndef run():\n usage = '''\n ./run.py <lib file>\n\n Example: ./run.py lib/followup.py\n\n (This program loads bot-related code from the\n library code and then runs a message loop,\n feeding messages to the library code to handle.)\n\n Please make sure you have a current ~/.zuliprc\n file with the credentials you want to use for\n this bot.\n\n See lib/readme.md for more context.\n '''\n\n parser = optparse.OptionParser(usage=usage)\n parser.add_option('--quiet', '-q',\n action='store_true',\n help='Turn off logging output.')\n parser.add_option('--config-file',\n action='store',\n help='(alternate config file to ~/.zuliprc)')\n (options, args) = parser.parse_args()\n\n if len(args) == 0:\n print('You must specify a library!')\n sys.exit(1)\n\n lib_module = get_lib_module(lib_fn=args[0])\n\n if not options.quiet:\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n run_message_handler_for_bot(\n lib_module=lib_module,\n config_file=options.config_file,\n quiet=options.quiet\n )\n\nif __name__ == '__main__':\n run()\n", "path": "contrib_bots/run.py"}], "after_files": [{"content": "#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport importlib\nimport logging\nimport optparse\nimport os\nimport sys\nimport time\n\nour_dir = os.path.dirname(os.path.abspath(__file__))\n\n# For dev setups, we can find the API in the repo itself.\nif os.path.exists(os.path.join(our_dir, '../api/zulip')):\n sys.path.insert(0, '../api')\n\nfrom zulip import Client\n\nclass RateLimit(object):\n def __init__(self, message_limit, interval_limit):\n self.message_limit = message_limit\n self.interval_limit = interval_limit\n self.message_list = []\n\n def is_legal(self):\n self.message_list.append(time.time())\n if len(self.message_list) > self.message_limit:\n self.message_list.pop(0)\n time_diff = self.message_list[-1] - self.message_list[0]\n return time_diff >= self.interval_limit\n else:\n return True\n\nclass RestrictedClient(object):\n def __init__(self, client):\n # Only expose a subset of our Client's functionality\n user_profile = client.get_profile()\n self.rate_limit = RateLimit(20, 5)\n self.client = client\n try:\n self.full_name = user_profile['full_name']\n self.email = user_profile['email']\n except KeyError:\n logging.error('Cannot fetch user profile, make sure you have set'\n ' up the zuliprc file correctly.')\n sys.exit(1)\n\n def send_message(self, *args, **kwargs):\n if self.rate_limit.is_legal():\n self.client.send_message(*args, **kwargs)\n else:\n logging.error('-----> !*!*!*MESSAGE RATE LIMIT REACHED, EXITING*!*!*! <-----\\n'\n 'Is your bot trapped in an infinite loop by reacting to'\n ' its own messages?')\n sys.exit(1)\n\ndef get_lib_module(lib_fn):\n lib_fn = os.path.abspath(lib_fn)\n if not os.path.dirname(lib_fn).startswith(os.path.join(our_dir, 'lib')):\n print('Sorry, we will only import code from contrib_bots/lib.')\n sys.exit(1)\n\n if not lib_fn.endswith('.py'):\n print('Please use a .py extension for library files.')\n sys.exit(1)\n\n sys.path.append('lib')\n base_lib_fn = os.path.basename(os.path.splitext(lib_fn)[0])\n module_name = 'lib.' + base_lib_fn\n module = importlib.import_module(module_name)\n return module\n\ndef run_message_handler_for_bot(lib_module, quiet, config_file):\n # Make sure you set up your ~/.zuliprc\n client = Client(config_file=config_file)\n restricted_client = RestrictedClient(client)\n\n message_handler = lib_module.handler_class()\n\n class StateHandler(object):\n def __init__(self):\n self.state = None\n\n def set_state(self, state):\n self.state = state\n\n def get_state(self):\n return self.state\n\n state_handler = StateHandler()\n\n if not quiet:\n print(message_handler.usage())\n\n def handle_message(message):\n logging.info('waiting for next message')\n if message_handler.triage_message(message=message,\n client=restricted_client):\n message_handler.handle_message(\n message=message,\n client=restricted_client,\n state_handler=state_handler\n )\n\n logging.info('starting message handling...')\n client.call_on_each_message(handle_message)\n\ndef run():\n usage = '''\n ./run.py <lib file>\n\n Example: ./run.py lib/followup.py\n\n (This program loads bot-related code from the\n library code and then runs a message loop,\n feeding messages to the library code to handle.)\n\n Please make sure you have a current ~/.zuliprc\n file with the credentials you want to use for\n this bot.\n\n See lib/readme.md for more context.\n '''\n\n parser = optparse.OptionParser(usage=usage)\n parser.add_option('--quiet', '-q',\n action='store_true',\n help='Turn off logging output.')\n parser.add_option('--config-file',\n action='store',\n help='(alternate config file to ~/.zuliprc)')\n (options, args) = parser.parse_args()\n\n if len(args) == 0:\n print('You must specify a library!')\n sys.exit(1)\n\n lib_module = get_lib_module(lib_fn=args[0])\n\n if not options.quiet:\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n\n run_message_handler_for_bot(\n lib_module=lib_module,\n config_file=options.config_file,\n quiet=options.quiet\n )\n\nif __name__ == '__main__':\n run()\n", "path": "contrib_bots/run.py"}]}
1,560
471
gh_patches_debug_38222
rasdani/github-patches
git_diff
getredash__redash-1394
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Share access permissions for add/remove widgets Hi @arikfr , in our PR #1113 we focused primarily on sharing access permissions for queries, and for dashboards we currently only allow to modify basic info of the dashboard. What is still missing is ability to allow other users to add and remove widgets. Is that something you are planning to add, or should we give it a shot? Another thing that came up - we're currently enforcing `require_admin_or_owner(...)` for managing access permissions (e.g., https://github.com/getredash/redash/blob/master/redash/handlers/permissions.py#L42). This is actually a very restrictive limitation, and we believe that anybody with permissions (owner, admin, other permitted users) should be able to add/remove users. For instance, if you consider person A creating a dashboard, then giving access to persons B and C who are actively maintaining that dashboard. Then, if person A leaves the company, B and C would not be able to make the required changes to add another person D. What do you think? /cc @rohanpd --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `redash/handlers/widgets.py` Content: ``` 1 import json 2 3 from flask import request 4 5 from redash import models 6 from redash.permissions import require_permission, require_admin_or_owner, require_access, view_only 7 from redash.handlers.base import BaseResource 8 9 10 class WidgetListResource(BaseResource): 11 @require_permission('edit_dashboard') 12 def post(self): 13 widget_properties = request.get_json(force=True) 14 dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org) 15 require_admin_or_owner(dashboard.user_id) 16 17 widget_properties['options'] = json.dumps(widget_properties['options']) 18 widget_properties.pop('id', None) 19 widget_properties['dashboard'] = dashboard 20 21 visualization_id = widget_properties.pop('visualization_id') 22 if visualization_id: 23 visualization = models.Visualization.get_by_id_and_org(visualization_id, self.current_org) 24 require_access(visualization.query.groups, self.current_user, view_only) 25 else: 26 visualization = None 27 28 widget_properties['visualization'] = visualization 29 30 widget = models.Widget.create(**widget_properties) 31 32 layout = json.loads(widget.dashboard.layout) 33 new_row = True 34 35 if len(layout) == 0 or widget.width == 2: 36 layout.append([widget.id]) 37 elif len(layout[-1]) == 1: 38 neighbour_widget = models.Widget.get(models.Widget.id == layout[-1][0]) 39 if neighbour_widget.width == 1: 40 layout[-1].append(widget.id) 41 new_row = False 42 else: 43 layout.append([widget.id]) 44 else: 45 layout.append([widget.id]) 46 47 widget.dashboard.layout = json.dumps(layout) 48 widget.dashboard.save() 49 50 return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row} 51 52 53 class WidgetResource(BaseResource): 54 @require_permission('edit_dashboard') 55 def post(self, widget_id): 56 # This method currently handles Text Box widgets only. 57 widget = models.Widget.get_by_id_and_org(widget_id, self.current_org) 58 require_admin_or_owner(widget.dashboard.user_id) 59 widget_properties = request.get_json(force=True) 60 widget.text = widget_properties['text'] 61 widget.save() 62 63 return widget.to_dict() 64 65 @require_permission('edit_dashboard') 66 def delete(self, widget_id): 67 widget = models.Widget.get_by_id_and_org(widget_id, self.current_org) 68 require_admin_or_owner(widget.dashboard.user_id) 69 widget.delete_instance() 70 71 return {'layout': widget.dashboard.layout} 72 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/redash/handlers/widgets.py b/redash/handlers/widgets.py --- a/redash/handlers/widgets.py +++ b/redash/handlers/widgets.py @@ -1,10 +1,11 @@ import json from flask import request - from redash import models -from redash.permissions import require_permission, require_admin_or_owner, require_access, view_only from redash.handlers.base import BaseResource +from redash.permissions import (require_access, + require_object_modify_permission, + require_permission, view_only) class WidgetListResource(BaseResource): @@ -12,7 +13,7 @@ def post(self): widget_properties = request.get_json(force=True) dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org) - require_admin_or_owner(dashboard.user_id) + require_object_modify_permission(dashboard, self.current_user) widget_properties['options'] = json.dumps(widget_properties['options']) widget_properties.pop('id', None) @@ -47,7 +48,7 @@ widget.dashboard.layout = json.dumps(layout) widget.dashboard.save() - return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row} + return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row, 'version': dashboard.version} class WidgetResource(BaseResource): @@ -55,7 +56,7 @@ def post(self, widget_id): # This method currently handles Text Box widgets only. widget = models.Widget.get_by_id_and_org(widget_id, self.current_org) - require_admin_or_owner(widget.dashboard.user_id) + require_object_modify_permission(widget.dashboard, self.current_user) widget_properties = request.get_json(force=True) widget.text = widget_properties['text'] widget.save() @@ -65,7 +66,7 @@ @require_permission('edit_dashboard') def delete(self, widget_id): widget = models.Widget.get_by_id_and_org(widget_id, self.current_org) - require_admin_or_owner(widget.dashboard.user_id) + require_object_modify_permission(widget.dashboard, self.current_user) widget.delete_instance() - return {'layout': widget.dashboard.layout} + return {'layout': widget.dashboard.layout, 'version': widget.dashboard.version}
{"golden_diff": "diff --git a/redash/handlers/widgets.py b/redash/handlers/widgets.py\n--- a/redash/handlers/widgets.py\n+++ b/redash/handlers/widgets.py\n@@ -1,10 +1,11 @@\n import json\n \n from flask import request\n-\n from redash import models\n-from redash.permissions import require_permission, require_admin_or_owner, require_access, view_only\n from redash.handlers.base import BaseResource\n+from redash.permissions import (require_access,\n+ require_object_modify_permission,\n+ require_permission, view_only)\n \n \n class WidgetListResource(BaseResource):\n@@ -12,7 +13,7 @@\n def post(self):\n widget_properties = request.get_json(force=True)\n dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org)\n- require_admin_or_owner(dashboard.user_id)\n+ require_object_modify_permission(dashboard, self.current_user)\n \n widget_properties['options'] = json.dumps(widget_properties['options'])\n widget_properties.pop('id', None)\n@@ -47,7 +48,7 @@\n widget.dashboard.layout = json.dumps(layout)\n widget.dashboard.save()\n \n- return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row}\n+ return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row, 'version': dashboard.version}\n \n \n class WidgetResource(BaseResource):\n@@ -55,7 +56,7 @@\n def post(self, widget_id):\n # This method currently handles Text Box widgets only.\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n- require_admin_or_owner(widget.dashboard.user_id)\n+ require_object_modify_permission(widget.dashboard, self.current_user)\n widget_properties = request.get_json(force=True)\n widget.text = widget_properties['text']\n widget.save()\n@@ -65,7 +66,7 @@\n @require_permission('edit_dashboard')\n def delete(self, widget_id):\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n- require_admin_or_owner(widget.dashboard.user_id)\n+ require_object_modify_permission(widget.dashboard, self.current_user)\n widget.delete_instance()\n \n- return {'layout': widget.dashboard.layout}\n+ return {'layout': widget.dashboard.layout, 'version': widget.dashboard.version}\n", "issue": "Share access permissions for add/remove widgets\nHi @arikfr ,\r\n\r\nin our PR #1113 we focused primarily on sharing access permissions for queries, and for dashboards we currently only allow to modify basic info of the dashboard. What is still missing is ability to allow other users to add and remove widgets. Is that something you are planning to add, or should we give it a shot?\r\n\r\nAnother thing that came up - we're currently enforcing `require_admin_or_owner(...)` for managing access permissions (e.g., https://github.com/getredash/redash/blob/master/redash/handlers/permissions.py#L42). This is actually a very restrictive limitation, and we believe that anybody with permissions (owner, admin, other permitted users) should be able to add/remove users. For instance, if you consider person A creating a dashboard, then giving access to persons B and C who are actively maintaining that dashboard. Then, if person A leaves the company, B and C would not be able to make the required changes to add another person D. What do you think?\r\n\r\n/cc @rohanpd\n", "before_files": [{"content": "import json\n\nfrom flask import request\n\nfrom redash import models\nfrom redash.permissions import require_permission, require_admin_or_owner, require_access, view_only\nfrom redash.handlers.base import BaseResource\n\n\nclass WidgetListResource(BaseResource):\n @require_permission('edit_dashboard')\n def post(self):\n widget_properties = request.get_json(force=True)\n dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org)\n require_admin_or_owner(dashboard.user_id)\n\n widget_properties['options'] = json.dumps(widget_properties['options'])\n widget_properties.pop('id', None)\n widget_properties['dashboard'] = dashboard\n\n visualization_id = widget_properties.pop('visualization_id')\n if visualization_id:\n visualization = models.Visualization.get_by_id_and_org(visualization_id, self.current_org)\n require_access(visualization.query.groups, self.current_user, view_only)\n else:\n visualization = None\n\n widget_properties['visualization'] = visualization\n\n widget = models.Widget.create(**widget_properties)\n\n layout = json.loads(widget.dashboard.layout)\n new_row = True\n\n if len(layout) == 0 or widget.width == 2:\n layout.append([widget.id])\n elif len(layout[-1]) == 1:\n neighbour_widget = models.Widget.get(models.Widget.id == layout[-1][0])\n if neighbour_widget.width == 1:\n layout[-1].append(widget.id)\n new_row = False\n else:\n layout.append([widget.id])\n else:\n layout.append([widget.id])\n\n widget.dashboard.layout = json.dumps(layout)\n widget.dashboard.save()\n\n return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row}\n\n\nclass WidgetResource(BaseResource):\n @require_permission('edit_dashboard')\n def post(self, widget_id):\n # This method currently handles Text Box widgets only.\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n require_admin_or_owner(widget.dashboard.user_id)\n widget_properties = request.get_json(force=True)\n widget.text = widget_properties['text']\n widget.save()\n\n return widget.to_dict()\n\n @require_permission('edit_dashboard')\n def delete(self, widget_id):\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n require_admin_or_owner(widget.dashboard.user_id)\n widget.delete_instance()\n\n return {'layout': widget.dashboard.layout}\n", "path": "redash/handlers/widgets.py"}], "after_files": [{"content": "import json\n\nfrom flask import request\nfrom redash import models\nfrom redash.handlers.base import BaseResource\nfrom redash.permissions import (require_access,\n require_object_modify_permission,\n require_permission, view_only)\n\n\nclass WidgetListResource(BaseResource):\n @require_permission('edit_dashboard')\n def post(self):\n widget_properties = request.get_json(force=True)\n dashboard = models.Dashboard.get_by_id_and_org(widget_properties.pop('dashboard_id'), self.current_org)\n require_object_modify_permission(dashboard, self.current_user)\n\n widget_properties['options'] = json.dumps(widget_properties['options'])\n widget_properties.pop('id', None)\n widget_properties['dashboard'] = dashboard\n\n visualization_id = widget_properties.pop('visualization_id')\n if visualization_id:\n visualization = models.Visualization.get_by_id_and_org(visualization_id, self.current_org)\n require_access(visualization.query.groups, self.current_user, view_only)\n else:\n visualization = None\n\n widget_properties['visualization'] = visualization\n\n widget = models.Widget.create(**widget_properties)\n\n layout = json.loads(widget.dashboard.layout)\n new_row = True\n\n if len(layout) == 0 or widget.width == 2:\n layout.append([widget.id])\n elif len(layout[-1]) == 1:\n neighbour_widget = models.Widget.get(models.Widget.id == layout[-1][0])\n if neighbour_widget.width == 1:\n layout[-1].append(widget.id)\n new_row = False\n else:\n layout.append([widget.id])\n else:\n layout.append([widget.id])\n\n widget.dashboard.layout = json.dumps(layout)\n widget.dashboard.save()\n\n return {'widget': widget.to_dict(), 'layout': layout, 'new_row': new_row, 'version': dashboard.version}\n\n\nclass WidgetResource(BaseResource):\n @require_permission('edit_dashboard')\n def post(self, widget_id):\n # This method currently handles Text Box widgets only.\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n require_object_modify_permission(widget.dashboard, self.current_user)\n widget_properties = request.get_json(force=True)\n widget.text = widget_properties['text']\n widget.save()\n\n return widget.to_dict()\n\n @require_permission('edit_dashboard')\n def delete(self, widget_id):\n widget = models.Widget.get_by_id_and_org(widget_id, self.current_org)\n require_object_modify_permission(widget.dashboard, self.current_user)\n widget.delete_instance()\n\n return {'layout': widget.dashboard.layout, 'version': widget.dashboard.version}\n", "path": "redash/handlers/widgets.py"}]}
1,146
506
gh_patches_debug_25840
rasdani/github-patches
git_diff
lnbits__lnbits-690
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Split payments shares <1% Trying to set a payment share <1% will result in 500 INTERNAL SERVER ERROR. This should work as it would be very useful as a fee for hosting lnbits but 1% is too much. ![grafik](https://user-images.githubusercontent.com/51097237/174864872-55ed946c-ce0a-4dc6-8c90-ec2e70c29f54.png) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `lnbits/extensions/splitpayments/migrations.py` Content: ``` 1 async def m001_initial(db): 2 """ 3 Initial split payment table. 4 """ 5 await db.execute( 6 """ 7 CREATE TABLE splitpayments.targets ( 8 wallet TEXT NOT NULL, 9 source TEXT NOT NULL, 10 percent INTEGER NOT NULL CHECK (percent >= 0 AND percent <= 100), 11 alias TEXT, 12 13 UNIQUE (source, wallet) 14 ); 15 """ 16 ) 17 ``` Path: `lnbits/extensions/splitpayments/models.py` Content: ``` 1 from typing import List, Optional 2 3 from fastapi.param_functions import Query 4 from pydantic import BaseModel 5 6 7 class Target(BaseModel): 8 wallet: str 9 source: str 10 percent: int 11 alias: Optional[str] 12 13 14 class TargetPutList(BaseModel): 15 wallet: str = Query(...) 16 alias: str = Query("") 17 percent: int = Query(..., ge=1) 18 19 20 class TargetPut(BaseModel): 21 __root__: List[TargetPutList] 22 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/lnbits/extensions/splitpayments/migrations.py b/lnbits/extensions/splitpayments/migrations.py --- a/lnbits/extensions/splitpayments/migrations.py +++ b/lnbits/extensions/splitpayments/migrations.py @@ -14,3 +14,41 @@ ); """ ) + + +async def m002_float_percent(db): + """ + Add float percent and migrates the existing data. + """ + await db.execute("ALTER TABLE splitpayments.targets RENAME TO splitpayments_old") + await db.execute( + """ + CREATE TABLE splitpayments.targets ( + wallet TEXT NOT NULL, + source TEXT NOT NULL, + percent REAL NOT NULL CHECK (percent >= 0 AND percent <= 100), + alias TEXT, + + UNIQUE (source, wallet) + ); + """ + ) + + for row in [ + list(row) + for row in await db.fetchall("SELECT * FROM splitpayments.splitpayments_old") + ]: + await db.execute( + """ + INSERT INTO splitpayments.targets ( + wallet, + source, + percent, + alias + ) + VALUES (?, ?, ?, ?) + """, + (row[0], row[1], row[2], row[3]), + ) + + await db.execute("DROP TABLE splitpayments.splitpayments_old") diff --git a/lnbits/extensions/splitpayments/models.py b/lnbits/extensions/splitpayments/models.py --- a/lnbits/extensions/splitpayments/models.py +++ b/lnbits/extensions/splitpayments/models.py @@ -7,14 +7,14 @@ class Target(BaseModel): wallet: str source: str - percent: int + percent: float alias: Optional[str] class TargetPutList(BaseModel): wallet: str = Query(...) alias: str = Query("") - percent: int = Query(..., ge=1) + percent: float = Query(..., ge=0.01) class TargetPut(BaseModel):
{"golden_diff": "diff --git a/lnbits/extensions/splitpayments/migrations.py b/lnbits/extensions/splitpayments/migrations.py\n--- a/lnbits/extensions/splitpayments/migrations.py\n+++ b/lnbits/extensions/splitpayments/migrations.py\n@@ -14,3 +14,41 @@\n );\n \"\"\"\n )\n+\n+\n+async def m002_float_percent(db):\n+ \"\"\"\n+ Add float percent and migrates the existing data.\n+ \"\"\"\n+ await db.execute(\"ALTER TABLE splitpayments.targets RENAME TO splitpayments_old\")\n+ await db.execute(\n+ \"\"\"\n+ CREATE TABLE splitpayments.targets (\n+ wallet TEXT NOT NULL,\n+ source TEXT NOT NULL,\n+ percent REAL NOT NULL CHECK (percent >= 0 AND percent <= 100),\n+ alias TEXT,\n+\n+ UNIQUE (source, wallet)\n+ );\n+ \"\"\"\n+ )\n+\n+ for row in [\n+ list(row)\n+ for row in await db.fetchall(\"SELECT * FROM splitpayments.splitpayments_old\")\n+ ]:\n+ await db.execute(\n+ \"\"\"\n+ INSERT INTO splitpayments.targets (\n+ wallet,\n+ source,\n+ percent,\n+ alias\n+ )\n+ VALUES (?, ?, ?, ?)\n+ \"\"\",\n+ (row[0], row[1], row[2], row[3]),\n+ )\n+\n+ await db.execute(\"DROP TABLE splitpayments.splitpayments_old\")\ndiff --git a/lnbits/extensions/splitpayments/models.py b/lnbits/extensions/splitpayments/models.py\n--- a/lnbits/extensions/splitpayments/models.py\n+++ b/lnbits/extensions/splitpayments/models.py\n@@ -7,14 +7,14 @@\n class Target(BaseModel):\n wallet: str\n source: str\n- percent: int\n+ percent: float\n alias: Optional[str]\n \n \n class TargetPutList(BaseModel):\n wallet: str = Query(...)\n alias: str = Query(\"\")\n- percent: int = Query(..., ge=1)\n+ percent: float = Query(..., ge=0.01)\n \n \n class TargetPut(BaseModel):\n", "issue": "Split payments shares <1%\nTrying to set a payment share <1% will result in 500 INTERNAL SERVER ERROR.\r\nThis should work as it would be very useful as a fee for hosting lnbits but 1% is too much.\r\n![grafik](https://user-images.githubusercontent.com/51097237/174864872-55ed946c-ce0a-4dc6-8c90-ec2e70c29f54.png)\r\n\n", "before_files": [{"content": "async def m001_initial(db):\n \"\"\"\n Initial split payment table.\n \"\"\"\n await db.execute(\n \"\"\"\n CREATE TABLE splitpayments.targets (\n wallet TEXT NOT NULL,\n source TEXT NOT NULL,\n percent INTEGER NOT NULL CHECK (percent >= 0 AND percent <= 100),\n alias TEXT,\n\n UNIQUE (source, wallet)\n );\n \"\"\"\n )\n", "path": "lnbits/extensions/splitpayments/migrations.py"}, {"content": "from typing import List, Optional\n\nfrom fastapi.param_functions import Query\nfrom pydantic import BaseModel\n\n\nclass Target(BaseModel):\n wallet: str\n source: str\n percent: int\n alias: Optional[str]\n\n\nclass TargetPutList(BaseModel):\n wallet: str = Query(...)\n alias: str = Query(\"\")\n percent: int = Query(..., ge=1)\n\n\nclass TargetPut(BaseModel):\n __root__: List[TargetPutList]\n", "path": "lnbits/extensions/splitpayments/models.py"}], "after_files": [{"content": "async def m001_initial(db):\n \"\"\"\n Initial split payment table.\n \"\"\"\n await db.execute(\n \"\"\"\n CREATE TABLE splitpayments.targets (\n wallet TEXT NOT NULL,\n source TEXT NOT NULL,\n percent INTEGER NOT NULL CHECK (percent >= 0 AND percent <= 100),\n alias TEXT,\n\n UNIQUE (source, wallet)\n );\n \"\"\"\n )\n\n\nasync def m002_float_percent(db):\n \"\"\"\n Add float percent and migrates the existing data.\n \"\"\"\n await db.execute(\"ALTER TABLE splitpayments.targets RENAME TO splitpayments_old\")\n await db.execute(\n \"\"\"\n CREATE TABLE splitpayments.targets (\n wallet TEXT NOT NULL,\n source TEXT NOT NULL,\n percent REAL NOT NULL CHECK (percent >= 0 AND percent <= 100),\n alias TEXT,\n\n UNIQUE (source, wallet)\n );\n \"\"\"\n )\n\n for row in [\n list(row)\n for row in await db.fetchall(\"SELECT * FROM splitpayments.splitpayments_old\")\n ]:\n await db.execute(\n \"\"\"\n INSERT INTO splitpayments.targets (\n wallet,\n source,\n percent,\n alias\n )\n VALUES (?, ?, ?, ?)\n \"\"\",\n (row[0], row[1], row[2], row[3]),\n )\n\n await db.execute(\"DROP TABLE splitpayments.splitpayments_old\")\n", "path": "lnbits/extensions/splitpayments/migrations.py"}, {"content": "from typing import List, Optional\n\nfrom fastapi.param_functions import Query\nfrom pydantic import BaseModel\n\n\nclass Target(BaseModel):\n wallet: str\n source: str\n percent: float\n alias: Optional[str]\n\n\nclass TargetPutList(BaseModel):\n wallet: str = Query(...)\n alias: str = Query(\"\")\n percent: float = Query(..., ge=0.01)\n\n\nclass TargetPut(BaseModel):\n __root__: List[TargetPutList]\n", "path": "lnbits/extensions/splitpayments/models.py"}]}
643
464
gh_patches_debug_24470
rasdani/github-patches
git_diff
talonhub__community-889
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Improve VSCode draft editor robustness Users can lose drafts if window switch is too slow. To address this issue, we propose the following: - [x] Increase sleep timeout in https://github.com/knausj85/knausj_talon/blob/0d4ad8523b87c2fe10457b7fae7f2ba2f22ad735/draft_editor/draft_editor.py#L112 - [x] Keep last draft in memory, and have "draft submit" when outside of VSCode just submit the most recent draft. That way if initial draft submit doesn't work, user can just say "draft submit" again - [x] While we're here, add "draft top", which selects from cursor to start of document --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `draft_editor/draft_editor.py` Content: ``` 1 from talon import Context, Module, actions, ui 2 3 mod = Module() 4 mod.tag("draft_editor_active", "Indicates whether the draft editor has been activated") 5 mod.tag( 6 "draft_editor_app_focused", 7 "Indicates that the draft editor app currently has focus", 8 ) 9 10 ctx = Context() 11 tags: set[str] = set() 12 13 14 def add_tag(tag: str): 15 tags.add(tag) 16 ctx.tags = list(tags) 17 18 19 def remove_tag(tag: str): 20 tags.discard(tag) 21 ctx.tags = list(tags) 22 23 24 default_names = ["Visual Studio Code", "Code", "VSCodium", "Codium", "code-oss"] 25 26 setting_editor_names = mod.setting( 27 "draft_editor", 28 type=str, 29 default=None, 30 desc="List of application names to use for draft editor", 31 ) 32 33 34 def get_editor_names(): 35 names_csv = setting_editor_names.get() 36 return names_csv.split(", ") if names_csv else default_names 37 38 39 @mod.scope 40 def scope(): 41 editor_names = get_editor_names() 42 43 for app in ui.apps(background=False): 44 if app.name in editor_names: 45 return {"draft_editor_running": True} 46 47 return {"draft_editor_running": False} 48 49 50 def handle_app_activate(app): 51 if app.name in get_editor_names(): 52 add_tag("user.draft_editor_app_focused") 53 else: 54 remove_tag("user.draft_editor_app_focused") 55 56 57 ui.register("app_launch", scope.update) 58 ui.register("app_close", scope.update) 59 ui.register("app_activate", handle_app_activate) 60 61 62 original_window = None 63 64 65 @mod.action_class 66 class Actions: 67 def draft_editor_open(): 68 """Open draft editor""" 69 global original_window 70 original_window = ui.active_window() 71 editor_app = get_editor_app() 72 selected_text = actions.edit.selected_text() 73 actions.user.switcher_focus_app(editor_app) 74 # Wait additional time for talon context to update. 75 actions.sleep("200ms") 76 actions.app.tab_open() 77 if selected_text != "": 78 actions.user.paste(selected_text) 79 add_tag("user.draft_editor_active") 80 81 def draft_editor_submit(): 82 """Submit/save draft editor""" 83 close_editor(submit_draft=True) 84 85 def draft_editor_discard(): 86 """Discard draft editor""" 87 close_editor(submit_draft=False) 88 89 90 def get_editor_app() -> ui.App: 91 editor_names = get_editor_names() 92 93 for app in ui.apps(background=False): 94 if app.name in editor_names: 95 return app 96 97 raise RuntimeError("Draft editor is not running") 98 99 100 def close_editor(submit_draft: bool): 101 remove_tag("user.draft_editor_active") 102 actions.edit.select_all() 103 selected_text = actions.edit.selected_text() 104 actions.edit.delete() 105 actions.app.tab_close() 106 actions.user.switcher_focus_window(original_window) 107 actions.sleep("200ms") 108 if submit_draft: 109 actions.user.paste(selected_text) 110 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/draft_editor/draft_editor.py b/draft_editor/draft_editor.py --- a/draft_editor/draft_editor.py +++ b/draft_editor/draft_editor.py @@ -61,6 +61,8 @@ original_window = None +last_draft = None + @mod.action_class class Actions: @@ -86,6 +88,11 @@ """Discard draft editor""" close_editor(submit_draft=False) + def draft_editor_paste_last(): + """Paste last submitted draft""" + if last_draft: + actions.user.paste(last_draft) + def get_editor_app() -> ui.App: editor_names = get_editor_names() @@ -98,12 +105,14 @@ def close_editor(submit_draft: bool): + global last_draft remove_tag("user.draft_editor_active") actions.edit.select_all() selected_text = actions.edit.selected_text() actions.edit.delete() actions.app.tab_close() actions.user.switcher_focus_window(original_window) - actions.sleep("200ms") + actions.sleep("300ms") if submit_draft: + last_draft = selected_text actions.user.paste(selected_text)
{"golden_diff": "diff --git a/draft_editor/draft_editor.py b/draft_editor/draft_editor.py\n--- a/draft_editor/draft_editor.py\n+++ b/draft_editor/draft_editor.py\n@@ -61,6 +61,8 @@\n \n original_window = None\n \n+last_draft = None\n+\n \n @mod.action_class\n class Actions:\n@@ -86,6 +88,11 @@\n \"\"\"Discard draft editor\"\"\"\n close_editor(submit_draft=False)\n \n+ def draft_editor_paste_last():\n+ \"\"\"Paste last submitted draft\"\"\"\n+ if last_draft:\n+ actions.user.paste(last_draft)\n+\n \n def get_editor_app() -> ui.App:\n editor_names = get_editor_names()\n@@ -98,12 +105,14 @@\n \n \n def close_editor(submit_draft: bool):\n+ global last_draft\n remove_tag(\"user.draft_editor_active\")\n actions.edit.select_all()\n selected_text = actions.edit.selected_text()\n actions.edit.delete()\n actions.app.tab_close()\n actions.user.switcher_focus_window(original_window)\n- actions.sleep(\"200ms\")\n+ actions.sleep(\"300ms\")\n if submit_draft:\n+ last_draft = selected_text\n actions.user.paste(selected_text)\n", "issue": "Improve VSCode draft editor robustness\nUsers can lose drafts if window switch is too slow. To address this issue, we propose the following:\r\n\r\n- [x] Increase sleep timeout in https://github.com/knausj85/knausj_talon/blob/0d4ad8523b87c2fe10457b7fae7f2ba2f22ad735/draft_editor/draft_editor.py#L112\r\n- [x] Keep last draft in memory, and have \"draft submit\" when outside of VSCode just submit the most recent draft. That way if initial draft submit doesn't work, user can just say \"draft submit\" again\r\n- [x] While we're here, add \"draft top\", which selects from cursor to start of document\n", "before_files": [{"content": "from talon import Context, Module, actions, ui\n\nmod = Module()\nmod.tag(\"draft_editor_active\", \"Indicates whether the draft editor has been activated\")\nmod.tag(\n \"draft_editor_app_focused\",\n \"Indicates that the draft editor app currently has focus\",\n)\n\nctx = Context()\ntags: set[str] = set()\n\n\ndef add_tag(tag: str):\n tags.add(tag)\n ctx.tags = list(tags)\n\n\ndef remove_tag(tag: str):\n tags.discard(tag)\n ctx.tags = list(tags)\n\n\ndefault_names = [\"Visual Studio Code\", \"Code\", \"VSCodium\", \"Codium\", \"code-oss\"]\n\nsetting_editor_names = mod.setting(\n \"draft_editor\",\n type=str,\n default=None,\n desc=\"List of application names to use for draft editor\",\n)\n\n\ndef get_editor_names():\n names_csv = setting_editor_names.get()\n return names_csv.split(\", \") if names_csv else default_names\n\n\[email protected]\ndef scope():\n editor_names = get_editor_names()\n\n for app in ui.apps(background=False):\n if app.name in editor_names:\n return {\"draft_editor_running\": True}\n\n return {\"draft_editor_running\": False}\n\n\ndef handle_app_activate(app):\n if app.name in get_editor_names():\n add_tag(\"user.draft_editor_app_focused\")\n else:\n remove_tag(\"user.draft_editor_app_focused\")\n\n\nui.register(\"app_launch\", scope.update)\nui.register(\"app_close\", scope.update)\nui.register(\"app_activate\", handle_app_activate)\n\n\noriginal_window = None\n\n\[email protected]_class\nclass Actions:\n def draft_editor_open():\n \"\"\"Open draft editor\"\"\"\n global original_window\n original_window = ui.active_window()\n editor_app = get_editor_app()\n selected_text = actions.edit.selected_text()\n actions.user.switcher_focus_app(editor_app)\n # Wait additional time for talon context to update.\n actions.sleep(\"200ms\")\n actions.app.tab_open()\n if selected_text != \"\":\n actions.user.paste(selected_text)\n add_tag(\"user.draft_editor_active\")\n\n def draft_editor_submit():\n \"\"\"Submit/save draft editor\"\"\"\n close_editor(submit_draft=True)\n\n def draft_editor_discard():\n \"\"\"Discard draft editor\"\"\"\n close_editor(submit_draft=False)\n\n\ndef get_editor_app() -> ui.App:\n editor_names = get_editor_names()\n\n for app in ui.apps(background=False):\n if app.name in editor_names:\n return app\n\n raise RuntimeError(\"Draft editor is not running\")\n\n\ndef close_editor(submit_draft: bool):\n remove_tag(\"user.draft_editor_active\")\n actions.edit.select_all()\n selected_text = actions.edit.selected_text()\n actions.edit.delete()\n actions.app.tab_close()\n actions.user.switcher_focus_window(original_window)\n actions.sleep(\"200ms\")\n if submit_draft:\n actions.user.paste(selected_text)\n", "path": "draft_editor/draft_editor.py"}], "after_files": [{"content": "from talon import Context, Module, actions, ui\n\nmod = Module()\nmod.tag(\"draft_editor_active\", \"Indicates whether the draft editor has been activated\")\nmod.tag(\n \"draft_editor_app_focused\",\n \"Indicates that the draft editor app currently has focus\",\n)\n\nctx = Context()\ntags: set[str] = set()\n\n\ndef add_tag(tag: str):\n tags.add(tag)\n ctx.tags = list(tags)\n\n\ndef remove_tag(tag: str):\n tags.discard(tag)\n ctx.tags = list(tags)\n\n\ndefault_names = [\"Visual Studio Code\", \"Code\", \"VSCodium\", \"Codium\", \"code-oss\"]\n\nsetting_editor_names = mod.setting(\n \"draft_editor\",\n type=str,\n default=None,\n desc=\"List of application names to use for draft editor\",\n)\n\n\ndef get_editor_names():\n names_csv = setting_editor_names.get()\n return names_csv.split(\", \") if names_csv else default_names\n\n\[email protected]\ndef scope():\n editor_names = get_editor_names()\n\n for app in ui.apps(background=False):\n if app.name in editor_names:\n return {\"draft_editor_running\": True}\n\n return {\"draft_editor_running\": False}\n\n\ndef handle_app_activate(app):\n if app.name in get_editor_names():\n add_tag(\"user.draft_editor_app_focused\")\n else:\n remove_tag(\"user.draft_editor_app_focused\")\n\n\nui.register(\"app_launch\", scope.update)\nui.register(\"app_close\", scope.update)\nui.register(\"app_activate\", handle_app_activate)\n\n\noriginal_window = None\n\nlast_draft = None\n\n\[email protected]_class\nclass Actions:\n def draft_editor_open():\n \"\"\"Open draft editor\"\"\"\n global original_window\n original_window = ui.active_window()\n editor_app = get_editor_app()\n selected_text = actions.edit.selected_text()\n actions.user.switcher_focus_app(editor_app)\n # Wait additional time for talon context to update.\n actions.sleep(\"200ms\")\n actions.app.tab_open()\n if selected_text != \"\":\n actions.user.paste(selected_text)\n add_tag(\"user.draft_editor_active\")\n\n def draft_editor_submit():\n \"\"\"Submit/save draft editor\"\"\"\n close_editor(submit_draft=True)\n\n def draft_editor_discard():\n \"\"\"Discard draft editor\"\"\"\n close_editor(submit_draft=False)\n\n def draft_editor_paste_last():\n \"\"\"Paste last submitted draft\"\"\"\n if last_draft:\n actions.user.paste(last_draft)\n\n\ndef get_editor_app() -> ui.App:\n editor_names = get_editor_names()\n\n for app in ui.apps(background=False):\n if app.name in editor_names:\n return app\n\n raise RuntimeError(\"Draft editor is not running\")\n\n\ndef close_editor(submit_draft: bool):\n global last_draft\n remove_tag(\"user.draft_editor_active\")\n actions.edit.select_all()\n selected_text = actions.edit.selected_text()\n actions.edit.delete()\n actions.app.tab_close()\n actions.user.switcher_focus_window(original_window)\n actions.sleep(\"300ms\")\n if submit_draft:\n last_draft = selected_text\n actions.user.paste(selected_text)\n", "path": "draft_editor/draft_editor.py"}]}
1,291
272
gh_patches_debug_5922
rasdani/github-patches
git_diff
bridgecrewio__checkov-3130
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- CKV2 cloudformation checks are not packaged into the whl file **Describe the issue** CKV2 cloudformation checks are not packaged into the whl file. I don't see them in the list command or the policy index. Checks are stored at: https://github.com/bridgecrewio/checkov/tree/master/checkov/cloudformation/checks/graph_checks/aws **Additional context** A solution should be similar to https://github.com/bridgecrewio/checkov/pull/2255 The impact is that ckv2 cfn policies are not running --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 #!/usr/bin/env python 2 import logging 3 import os 4 from importlib import util 5 from os import path 6 7 import setuptools 8 from setuptools import setup 9 10 # read the contents of your README file 11 this_directory = path.abspath(path.dirname(__file__)) 12 with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: 13 long_description = f.read() 14 15 logger = logging.getLogger(__name__) 16 spec = util.spec_from_file_location( 17 "checkov.version", os.path.join("checkov", "version.py") 18 ) 19 # noinspection PyUnresolvedReferences 20 mod = util.module_from_spec(spec) 21 spec.loader.exec_module(mod) # type: ignore 22 version = mod.version # type: ignore 23 24 setup( 25 extras_require={ 26 "dev": [ 27 "pytest==5.3.1", 28 "coverage==5.5", 29 "coverage-badge", 30 "GitPython==3.1.7", 31 "bandit", 32 "jsonschema", 33 ] 34 }, 35 install_requires=[ 36 "bc-python-hcl2==0.3.42", 37 "cloudsplaining>=0.4.1", 38 "deep_merge", 39 "tabulate", 40 "colorama", 41 "termcolor", 42 "junit-xml>=1.9", 43 "dpath>=1.5.0,<2", 44 "pyyaml>=5.4.1", 45 "boto3>=1.17", 46 "GitPython", 47 "jmespath", 48 "tqdm", 49 "update_checker", 50 "semantic_version", 51 "packaging", 52 "networkx", 53 "dockerfile-parse", 54 "docker", 55 "configargparse", 56 "argcomplete", 57 "detect-secrets", 58 "policyuniverse", 59 "typing-extensions>=4.1.0", 60 "cachetools", 61 "cyclonedx-python-lib>=2.4.0", 62 "click>=8.0.0", 63 "aiohttp", 64 "aiodns", 65 "aiomultiprocess", 66 "jsonpath_ng", 67 "jsonschema~=3.0", 68 "prettytable>=3.0.0", 69 "pycep-parser==0.3.7", 70 "charset-normalizer", 71 ], 72 license="Apache License 2.0", 73 name="checkov", 74 version=version, 75 python_requires=">=3.7", 76 description="Infrastructure as code static analysis", 77 author="bridgecrew", 78 author_email="[email protected]", 79 url="https://github.com/bridgecrewio/checkov", 80 packages=setuptools.find_packages(exclude=["tests*", "integration_tests*"]), 81 include_package_data=True, 82 package_dir={ 83 "checkov.bicep.checks.graph_checks": "checkov/bicep/checks/graph_checks", 84 "checkov.terraform.checks.graph_checks": "checkov/terraform/checks/graph_checks", 85 }, 86 package_data={ 87 "checkov": ["py.typed"], 88 "checkov.bicep.checks.graph_checks": ["*.yaml"], 89 "checkov.common.util.templates": ["*.jinja2"], 90 "checkov.terraform.checks.graph_checks": [ 91 "aws/*.yaml", 92 "gcp/*.yaml", 93 "azure/*.yaml", 94 ], 95 }, 96 scripts=["bin/checkov", "bin/checkov.cmd"], 97 long_description=long_description, 98 long_description_content_type="text/markdown", 99 classifiers=[ 100 "Environment :: Console", 101 "Intended Audience :: Developers", 102 "Intended Audience :: System Administrators", 103 "License :: OSI Approved :: Apache Software License", 104 "Programming Language :: Python :: 3 :: Only", 105 "Programming Language :: Python :: 3.7", 106 "Programming Language :: Python :: 3.8", 107 "Programming Language :: Python :: 3.9", 108 "Programming Language :: Python :: 3.10", 109 "Topic :: Security", 110 "Topic :: Software Development :: Build Tools", 111 "Typing :: Typed", 112 ], 113 ) 114 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -81,6 +81,7 @@ include_package_data=True, package_dir={ "checkov.bicep.checks.graph_checks": "checkov/bicep/checks/graph_checks", + "checkov.cloudformation.checks.graph_checks": "checkov/cloudformation/checks/graph_checks", "checkov.terraform.checks.graph_checks": "checkov/terraform/checks/graph_checks", }, package_data={
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -81,6 +81,7 @@\n include_package_data=True,\n package_dir={\n \"checkov.bicep.checks.graph_checks\": \"checkov/bicep/checks/graph_checks\",\n+ \"checkov.cloudformation.checks.graph_checks\": \"checkov/cloudformation/checks/graph_checks\",\n \"checkov.terraform.checks.graph_checks\": \"checkov/terraform/checks/graph_checks\",\n },\n package_data={\n", "issue": "CKV2 cloudformation checks are not packaged into the whl file \n**Describe the issue**\r\nCKV2 cloudformation checks are not packaged into the whl file.\r\nI don't see them in the list command or the policy index.\r\nChecks are stored at: https://github.com/bridgecrewio/checkov/tree/master/checkov/cloudformation/checks/graph_checks/aws\r\n**Additional context**\r\nA solution should be similar to https://github.com/bridgecrewio/checkov/pull/2255\r\n\r\nThe impact is that ckv2 cfn policies are not running\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\nimport logging\nimport os\nfrom importlib import util\nfrom os import path\n\nimport setuptools\nfrom setuptools import setup\n\n# read the contents of your README file\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = f.read()\n\nlogger = logging.getLogger(__name__)\nspec = util.spec_from_file_location(\n \"checkov.version\", os.path.join(\"checkov\", \"version.py\")\n)\n# noinspection PyUnresolvedReferences\nmod = util.module_from_spec(spec)\nspec.loader.exec_module(mod) # type: ignore\nversion = mod.version # type: ignore\n\nsetup(\n extras_require={\n \"dev\": [\n \"pytest==5.3.1\",\n \"coverage==5.5\",\n \"coverage-badge\",\n \"GitPython==3.1.7\",\n \"bandit\",\n \"jsonschema\",\n ]\n },\n install_requires=[\n \"bc-python-hcl2==0.3.42\",\n \"cloudsplaining>=0.4.1\",\n \"deep_merge\",\n \"tabulate\",\n \"colorama\",\n \"termcolor\",\n \"junit-xml>=1.9\",\n \"dpath>=1.5.0,<2\",\n \"pyyaml>=5.4.1\",\n \"boto3>=1.17\",\n \"GitPython\",\n \"jmespath\",\n \"tqdm\",\n \"update_checker\",\n \"semantic_version\",\n \"packaging\",\n \"networkx\",\n \"dockerfile-parse\",\n \"docker\",\n \"configargparse\",\n \"argcomplete\",\n \"detect-secrets\",\n \"policyuniverse\",\n \"typing-extensions>=4.1.0\",\n \"cachetools\",\n \"cyclonedx-python-lib>=2.4.0\",\n \"click>=8.0.0\",\n \"aiohttp\",\n \"aiodns\",\n \"aiomultiprocess\",\n \"jsonpath_ng\",\n \"jsonschema~=3.0\",\n \"prettytable>=3.0.0\",\n \"pycep-parser==0.3.7\",\n \"charset-normalizer\",\n ],\n license=\"Apache License 2.0\",\n name=\"checkov\",\n version=version,\n python_requires=\">=3.7\",\n description=\"Infrastructure as code static analysis\",\n author=\"bridgecrew\",\n author_email=\"[email protected]\",\n url=\"https://github.com/bridgecrewio/checkov\",\n packages=setuptools.find_packages(exclude=[\"tests*\", \"integration_tests*\"]),\n include_package_data=True,\n package_dir={\n \"checkov.bicep.checks.graph_checks\": \"checkov/bicep/checks/graph_checks\",\n \"checkov.terraform.checks.graph_checks\": \"checkov/terraform/checks/graph_checks\",\n },\n package_data={\n \"checkov\": [\"py.typed\"],\n \"checkov.bicep.checks.graph_checks\": [\"*.yaml\"],\n \"checkov.common.util.templates\": [\"*.jinja2\"],\n \"checkov.terraform.checks.graph_checks\": [\n \"aws/*.yaml\",\n \"gcp/*.yaml\",\n \"azure/*.yaml\",\n ],\n },\n scripts=[\"bin/checkov\", \"bin/checkov.cmd\"],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Topic :: Security\",\n \"Topic :: Software Development :: Build Tools\",\n \"Typing :: Typed\",\n ],\n)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python\nimport logging\nimport os\nfrom importlib import util\nfrom os import path\n\nimport setuptools\nfrom setuptools import setup\n\n# read the contents of your README file\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = f.read()\n\nlogger = logging.getLogger(__name__)\nspec = util.spec_from_file_location(\n \"checkov.version\", os.path.join(\"checkov\", \"version.py\")\n)\n# noinspection PyUnresolvedReferences\nmod = util.module_from_spec(spec)\nspec.loader.exec_module(mod) # type: ignore\nversion = mod.version # type: ignore\n\nsetup(\n extras_require={\n \"dev\": [\n \"pytest==5.3.1\",\n \"coverage==5.5\",\n \"coverage-badge\",\n \"GitPython==3.1.7\",\n \"bandit\",\n \"jsonschema\",\n ]\n },\n install_requires=[\n \"bc-python-hcl2==0.3.42\",\n \"cloudsplaining>=0.4.1\",\n \"deep_merge\",\n \"tabulate\",\n \"colorama\",\n \"termcolor\",\n \"junit-xml>=1.9\",\n \"dpath>=1.5.0,<2\",\n \"pyyaml>=5.4.1\",\n \"boto3>=1.17\",\n \"GitPython\",\n \"jmespath\",\n \"tqdm\",\n \"update_checker\",\n \"semantic_version\",\n \"packaging\",\n \"networkx\",\n \"dockerfile-parse\",\n \"docker\",\n \"configargparse\",\n \"argcomplete\",\n \"detect-secrets\",\n \"policyuniverse\",\n \"typing-extensions>=4.1.0\",\n \"cachetools\",\n \"cyclonedx-python-lib>=2.4.0\",\n \"click>=8.0.0\",\n \"aiohttp\",\n \"aiodns\",\n \"aiomultiprocess\",\n \"jsonpath_ng\",\n \"jsonschema~=3.0\",\n \"prettytable>=3.0.0\",\n \"pycep-parser==0.3.7\",\n \"charset-normalizer\",\n ],\n license=\"Apache License 2.0\",\n name=\"checkov\",\n version=version,\n python_requires=\">=3.7\",\n description=\"Infrastructure as code static analysis\",\n author=\"bridgecrew\",\n author_email=\"[email protected]\",\n url=\"https://github.com/bridgecrewio/checkov\",\n packages=setuptools.find_packages(exclude=[\"tests*\", \"integration_tests*\"]),\n include_package_data=True,\n package_dir={\n \"checkov.bicep.checks.graph_checks\": \"checkov/bicep/checks/graph_checks\",\n \"checkov.cloudformation.checks.graph_checks\": \"checkov/cloudformation/checks/graph_checks\",\n \"checkov.terraform.checks.graph_checks\": \"checkov/terraform/checks/graph_checks\",\n },\n package_data={\n \"checkov\": [\"py.typed\"],\n \"checkov.bicep.checks.graph_checks\": [\"*.yaml\"],\n \"checkov.common.util.templates\": [\"*.jinja2\"],\n \"checkov.terraform.checks.graph_checks\": [\n \"aws/*.yaml\",\n \"gcp/*.yaml\",\n \"azure/*.yaml\",\n ],\n },\n scripts=[\"bin/checkov\", \"bin/checkov.cmd\"],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Topic :: Security\",\n \"Topic :: Software Development :: Build Tools\",\n \"Typing :: Typed\",\n ],\n)\n", "path": "setup.py"}]}
1,471
114
gh_patches_debug_17020
rasdani/github-patches
git_diff
pypa__pip-9779
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- pip 21.0.1 fails when run with warnings converted to errors **Environment** * pip version: 21.0.1 * Python version: 3.9.1 * OS: Windows **Description** With the latest version of packaging (vendored in 21.0.1) a DeprecationWarning is issued when parsing a "legacy version". If pip is run with warnings converted to errors, this causes a failure. **Expected behavior** No error **How to Reproduce** `py -wE -m pip --version` Or to pinpoint it further, ``` py -wE >>> from pip._vendor import pkg_resources ``` This does *not* happen with setuptools 52.0.0, it appears to be related to the version of setuptools (44.0.0) that we vendor. **Output** ``` Traceback (most recent call last): File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\packaging\version.py", line 57, in parse return Version(version) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\packaging\version.py", line 298, in __init__ raise InvalidVersion("Invalid version: '{0}'".format(version)) pip._vendor.packaging.version.InvalidVersion: Invalid version: 'pip' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3252, in <module> def _initialize_master_working_set(): File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3235, in _call_aside f(*args, **kwargs) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 3264, in _initialize_master_working_set working_set = WorkingSet._build_master() File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 574, in _build_master ws = cls() File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 567, in __init__ self.add_entry(entry) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 623, in add_entry for dist in find_distributions(entry, True): File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2061, in find_on_path path_item_entries = _by_version_descending(filtered) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2034, in _by_version_descending return sorted(names, key=_by_version, reverse=True) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2032, in _by_version return [packaging.version.parse(part) for part in parts] File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2032, in <listcomp> return [packaging.version.parse(part) for part in parts] File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\packaging\version.py", line 59, in parse return LegacyVersion(version) File "C:\Users\Gustav\AppData\Local\Programs\Python\Python39\lib\site-packages\pip\_vendor\packaging\version.py", line 127, in __init__ warnings.warn( DeprecationWarning: Creating a LegacyVersion has been deprecated and will be removed in the next major release ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/pip/__main__.py` Content: ``` 1 import os 2 import sys 3 4 # Remove '' and current working directory from the first entry 5 # of sys.path, if present to avoid using current directory 6 # in pip commands check, freeze, install, list and show, 7 # when invoked as python -m pip <command> 8 if sys.path[0] in ("", os.getcwd()): 9 sys.path.pop(0) 10 11 # If we are running from a wheel, add the wheel to sys.path 12 # This allows the usage python pip-*.whl/pip install pip-*.whl 13 if __package__ == "": 14 # __file__ is pip-*.whl/pip/__main__.py 15 # first dirname call strips of '/__main__.py', second strips off '/pip' 16 # Resulting path is the name of the wheel itself 17 # Add that to sys.path so we can import pip 18 path = os.path.dirname(os.path.dirname(__file__)) 19 sys.path.insert(0, path) 20 21 from pip._internal.cli.main import main as _main 22 23 if __name__ == "__main__": 24 sys.exit(_main()) 25 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/pip/__main__.py b/src/pip/__main__.py --- a/src/pip/__main__.py +++ b/src/pip/__main__.py @@ -1,5 +1,6 @@ import os import sys +import warnings # Remove '' and current working directory from the first entry # of sys.path, if present to avoid using current directory @@ -18,7 +19,13 @@ path = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, path) -from pip._internal.cli.main import main as _main - if __name__ == "__main__": + # Work around the error reported in #9540, pending a proper fix. + # Note: It is essential the warning filter is set *before* importing + # pip, as the deprecation happens at import time, not runtime. + warnings.filterwarnings( + "ignore", category=DeprecationWarning, module=".*packaging\\.version" + ) + from pip._internal.cli.main import main as _main + sys.exit(_main())
{"golden_diff": "diff --git a/src/pip/__main__.py b/src/pip/__main__.py\n--- a/src/pip/__main__.py\n+++ b/src/pip/__main__.py\n@@ -1,5 +1,6 @@\n import os\n import sys\n+import warnings\n \n # Remove '' and current working directory from the first entry\n # of sys.path, if present to avoid using current directory\n@@ -18,7 +19,13 @@\n path = os.path.dirname(os.path.dirname(__file__))\n sys.path.insert(0, path)\n \n-from pip._internal.cli.main import main as _main\n-\n if __name__ == \"__main__\":\n+ # Work around the error reported in #9540, pending a proper fix.\n+ # Note: It is essential the warning filter is set *before* importing\n+ # pip, as the deprecation happens at import time, not runtime.\n+ warnings.filterwarnings(\n+ \"ignore\", category=DeprecationWarning, module=\".*packaging\\\\.version\"\n+ )\n+ from pip._internal.cli.main import main as _main\n+\n sys.exit(_main())\n", "issue": "pip 21.0.1 fails when run with warnings converted to errors\n**Environment**\r\n\r\n* pip version: 21.0.1\r\n* Python version: 3.9.1\r\n* OS: Windows\r\n\r\n**Description**\r\nWith the latest version of packaging (vendored in 21.0.1) a DeprecationWarning is issued when parsing a \"legacy version\". If pip is run with warnings converted to errors, this causes a failure.\r\n\r\n**Expected behavior**\r\nNo error\r\n\r\n**How to Reproduce**\r\n`py -wE -m pip --version`\r\n\r\nOr to pinpoint it further,\r\n\r\n```\r\npy -wE\r\n>>> from pip._vendor import pkg_resources\r\n```\r\n\r\nThis does *not* happen with setuptools 52.0.0, it appears to be related to the version of setuptools (44.0.0) that we vendor.\r\n\r\n**Output**\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\packaging\\version.py\", line 57, in parse\r\n return Version(version)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\packaging\\version.py\", line 298, in __init__\r\n raise InvalidVersion(\"Invalid version: '{0}'\".format(version))\r\npip._vendor.packaging.version.InvalidVersion: Invalid version: 'pip'\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"<stdin>\", line 1, in <module>\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 3252, in <module>\r\n def _initialize_master_working_set():\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 3235, in _call_aside\r\n f(*args, **kwargs)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 3264, in _initialize_master_working_set\r\n working_set = WorkingSet._build_master()\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 574, in _build_master\r\n ws = cls()\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 567, in __init__\r\n self.add_entry(entry)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 623, in add_entry\r\n for dist in find_distributions(entry, True):\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 2061, in find_on_path\r\n path_item_entries = _by_version_descending(filtered)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 2034, in _by_version_descending\r\n return sorted(names, key=_by_version, reverse=True)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 2032, in _by_version\r\n return [packaging.version.parse(part) for part in parts]\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\pkg_resources\\__init__.py\", line 2032, in <listcomp>\r\n return [packaging.version.parse(part) for part in parts]\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\packaging\\version.py\", line 59, in parse\r\n return LegacyVersion(version)\r\n File \"C:\\Users\\Gustav\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\pip\\_vendor\\packaging\\version.py\", line 127, in __init__\r\n warnings.warn(\r\nDeprecationWarning: Creating a LegacyVersion has been deprecated and will be removed in the next major release\r\n```\r\n\n", "before_files": [{"content": "import os\nimport sys\n\n# Remove '' and current working directory from the first entry\n# of sys.path, if present to avoid using current directory\n# in pip commands check, freeze, install, list and show,\n# when invoked as python -m pip <command>\nif sys.path[0] in (\"\", os.getcwd()):\n sys.path.pop(0)\n\n# If we are running from a wheel, add the wheel to sys.path\n# This allows the usage python pip-*.whl/pip install pip-*.whl\nif __package__ == \"\":\n # __file__ is pip-*.whl/pip/__main__.py\n # first dirname call strips of '/__main__.py', second strips off '/pip'\n # Resulting path is the name of the wheel itself\n # Add that to sys.path so we can import pip\n path = os.path.dirname(os.path.dirname(__file__))\n sys.path.insert(0, path)\n\nfrom pip._internal.cli.main import main as _main\n\nif __name__ == \"__main__\":\n sys.exit(_main())\n", "path": "src/pip/__main__.py"}], "after_files": [{"content": "import os\nimport sys\nimport warnings\n\n# Remove '' and current working directory from the first entry\n# of sys.path, if present to avoid using current directory\n# in pip commands check, freeze, install, list and show,\n# when invoked as python -m pip <command>\nif sys.path[0] in (\"\", os.getcwd()):\n sys.path.pop(0)\n\n# If we are running from a wheel, add the wheel to sys.path\n# This allows the usage python pip-*.whl/pip install pip-*.whl\nif __package__ == \"\":\n # __file__ is pip-*.whl/pip/__main__.py\n # first dirname call strips of '/__main__.py', second strips off '/pip'\n # Resulting path is the name of the wheel itself\n # Add that to sys.path so we can import pip\n path = os.path.dirname(os.path.dirname(__file__))\n sys.path.insert(0, path)\n\nif __name__ == \"__main__\":\n # Work around the error reported in #9540, pending a proper fix.\n # Note: It is essential the warning filter is set *before* importing\n # pip, as the deprecation happens at import time, not runtime.\n warnings.filterwarnings(\n \"ignore\", category=DeprecationWarning, module=\".*packaging\\\\.version\"\n )\n from pip._internal.cli.main import main as _main\n\n sys.exit(_main())\n", "path": "src/pip/__main__.py"}]}
1,644
247
gh_patches_debug_33257
rasdani/github-patches
git_diff
localstack__localstack-2244
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Incorrect response content-type header from cloudwatch logs When using the .NET AWSSDK connected to localstack and querying cloudwatch logs e.g. var logClient = new AmazonCloudWatchLogsClient(new AmazonCloudWatchLogsConfig() { ServiceURL = "http://localhost:4586", UseHttp = true, AuthenticationRegion = "eu-central-1", }); var logGroupName = @"/aws/lambda/f1"; var events = logClient.FilterLogEventsAsync(new FilterLogEventsRequest() { LogGroupName = logGroupName, }).GetAwaiter().GetResult(); The response is returned from the server but cannot be parsed by the SDK client code because the response's content-type header is text/html when it should be application/x-amz-json-1.1. This confirmed using Fiddler traces comparing the response from localstack to the response from AWS in the cloud. Can this be fixed easily? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `localstack/services/logs/logs_listener.py` Content: ``` 1 import re 2 from requests.models import Request 3 from localstack.utils.common import to_str 4 from localstack.services.generic_proxy import ProxyListener 5 6 7 class ProxyListenerCloudWatchLogs(ProxyListener): 8 9 def forward_request(self, method, path, data, headers): 10 if method == 'POST' and path == '/': 11 if 'nextToken' in to_str(data or ''): 12 data = self._fix_next_token_request(data) 13 headers['content-length'] = str(len(data)) 14 return Request(data=data, headers=headers, method=method) 15 16 return True 17 18 def return_response(self, method, path, data, headers, response): 19 if 'nextToken' in to_str(response.content or ''): 20 self._fix_next_token_response(response) 21 response.headers['content-length'] = str(len(response._content)) 22 23 def _fix_next_token_request(self, data): 24 # Fix for https://github.com/localstack/localstack/issues/1527 25 pattern = r'"nextToken":\s*"([0-9]+)"' 26 replacement = r'"nextToken": \1' 27 return re.sub(pattern, replacement, to_str(data)) 28 29 def _fix_next_token_response(self, response): 30 # Fix for https://github.com/localstack/localstack/issues/1527 31 pattern = r'"nextToken":\s*([0-9]+)' 32 replacement = r'"nextToken": "\1"' 33 response._content = re.sub(pattern, replacement, to_str(response.content)) 34 35 36 # instantiate listener 37 UPDATE_LOGS = ProxyListenerCloudWatchLogs() 38 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/localstack/services/logs/logs_listener.py b/localstack/services/logs/logs_listener.py --- a/localstack/services/logs/logs_listener.py +++ b/localstack/services/logs/logs_listener.py @@ -1,11 +1,11 @@ import re from requests.models import Request from localstack.utils.common import to_str +from localstack.constants import APPLICATION_AMZ_JSON_1_1 from localstack.services.generic_proxy import ProxyListener class ProxyListenerCloudWatchLogs(ProxyListener): - def forward_request(self, method, path, data, headers): if method == 'POST' and path == '/': if 'nextToken' in to_str(data or ''): @@ -16,17 +16,22 @@ return True def return_response(self, method, path, data, headers, response): + # Fix Incorrect response content-type header from cloudwatch logs #1343 + response.headers['content-type'] = APPLICATION_AMZ_JSON_1_1 + if 'nextToken' in to_str(response.content or ''): self._fix_next_token_response(response) response.headers['content-length'] = str(len(response._content)) - def _fix_next_token_request(self, data): + @staticmethod + def _fix_next_token_request(data): # Fix for https://github.com/localstack/localstack/issues/1527 pattern = r'"nextToken":\s*"([0-9]+)"' replacement = r'"nextToken": \1' return re.sub(pattern, replacement, to_str(data)) - def _fix_next_token_response(self, response): + @staticmethod + def _fix_next_token_response(response): # Fix for https://github.com/localstack/localstack/issues/1527 pattern = r'"nextToken":\s*([0-9]+)' replacement = r'"nextToken": "\1"'
{"golden_diff": "diff --git a/localstack/services/logs/logs_listener.py b/localstack/services/logs/logs_listener.py\n--- a/localstack/services/logs/logs_listener.py\n+++ b/localstack/services/logs/logs_listener.py\n@@ -1,11 +1,11 @@\n import re\n from requests.models import Request\n from localstack.utils.common import to_str\n+from localstack.constants import APPLICATION_AMZ_JSON_1_1\n from localstack.services.generic_proxy import ProxyListener\n \n \n class ProxyListenerCloudWatchLogs(ProxyListener):\n-\n def forward_request(self, method, path, data, headers):\n if method == 'POST' and path == '/':\n if 'nextToken' in to_str(data or ''):\n@@ -16,17 +16,22 @@\n return True\n \n def return_response(self, method, path, data, headers, response):\n+ # Fix Incorrect response content-type header from cloudwatch logs #1343\n+ response.headers['content-type'] = APPLICATION_AMZ_JSON_1_1\n+\n if 'nextToken' in to_str(response.content or ''):\n self._fix_next_token_response(response)\n response.headers['content-length'] = str(len(response._content))\n \n- def _fix_next_token_request(self, data):\n+ @staticmethod\n+ def _fix_next_token_request(data):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*\"([0-9]+)\"'\n replacement = r'\"nextToken\": \\1'\n return re.sub(pattern, replacement, to_str(data))\n \n- def _fix_next_token_response(self, response):\n+ @staticmethod\n+ def _fix_next_token_response(response):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*([0-9]+)'\n replacement = r'\"nextToken\": \"\\1\"'\n", "issue": "Incorrect response content-type header from cloudwatch logs\nWhen using the .NET AWSSDK connected to localstack and querying cloudwatch logs e.g. \r\n var logClient = new AmazonCloudWatchLogsClient(new AmazonCloudWatchLogsConfig()\r\n {\r\n ServiceURL = \"http://localhost:4586\",\r\n UseHttp = true,\r\n AuthenticationRegion = \"eu-central-1\",\r\n });\r\n var logGroupName = @\"/aws/lambda/f1\";\r\n var events = logClient.FilterLogEventsAsync(new FilterLogEventsRequest()\r\n {\r\n LogGroupName = logGroupName,\r\n }).GetAwaiter().GetResult();\r\n\r\nThe response is returned from the server but cannot be parsed by the SDK client code because the response's content-type header is text/html when it should be application/x-amz-json-1.1. This confirmed using Fiddler traces comparing the response from localstack to the response from AWS in the cloud. Can this be fixed easily?\n", "before_files": [{"content": "import re\nfrom requests.models import Request\nfrom localstack.utils.common import to_str\nfrom localstack.services.generic_proxy import ProxyListener\n\n\nclass ProxyListenerCloudWatchLogs(ProxyListener):\n\n def forward_request(self, method, path, data, headers):\n if method == 'POST' and path == '/':\n if 'nextToken' in to_str(data or ''):\n data = self._fix_next_token_request(data)\n headers['content-length'] = str(len(data))\n return Request(data=data, headers=headers, method=method)\n\n return True\n\n def return_response(self, method, path, data, headers, response):\n if 'nextToken' in to_str(response.content or ''):\n self._fix_next_token_response(response)\n response.headers['content-length'] = str(len(response._content))\n\n def _fix_next_token_request(self, data):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*\"([0-9]+)\"'\n replacement = r'\"nextToken\": \\1'\n return re.sub(pattern, replacement, to_str(data))\n\n def _fix_next_token_response(self, response):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*([0-9]+)'\n replacement = r'\"nextToken\": \"\\1\"'\n response._content = re.sub(pattern, replacement, to_str(response.content))\n\n\n# instantiate listener\nUPDATE_LOGS = ProxyListenerCloudWatchLogs()\n", "path": "localstack/services/logs/logs_listener.py"}], "after_files": [{"content": "import re\nfrom requests.models import Request\nfrom localstack.utils.common import to_str\nfrom localstack.constants import APPLICATION_AMZ_JSON_1_1\nfrom localstack.services.generic_proxy import ProxyListener\n\n\nclass ProxyListenerCloudWatchLogs(ProxyListener):\n def forward_request(self, method, path, data, headers):\n if method == 'POST' and path == '/':\n if 'nextToken' in to_str(data or ''):\n data = self._fix_next_token_request(data)\n headers['content-length'] = str(len(data))\n return Request(data=data, headers=headers, method=method)\n\n return True\n\n def return_response(self, method, path, data, headers, response):\n # Fix Incorrect response content-type header from cloudwatch logs #1343\n response.headers['content-type'] = APPLICATION_AMZ_JSON_1_1\n\n if 'nextToken' in to_str(response.content or ''):\n self._fix_next_token_response(response)\n response.headers['content-length'] = str(len(response._content))\n\n @staticmethod\n def _fix_next_token_request(data):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*\"([0-9]+)\"'\n replacement = r'\"nextToken\": \\1'\n return re.sub(pattern, replacement, to_str(data))\n\n @staticmethod\n def _fix_next_token_response(response):\n # Fix for https://github.com/localstack/localstack/issues/1527\n pattern = r'\"nextToken\":\\s*([0-9]+)'\n replacement = r'\"nextToken\": \"\\1\"'\n response._content = re.sub(pattern, replacement, to_str(response.content))\n\n\n# instantiate listener\nUPDATE_LOGS = ProxyListenerCloudWatchLogs()\n", "path": "localstack/services/logs/logs_listener.py"}]}
863
418
gh_patches_debug_28173
rasdani/github-patches
git_diff
CMSgov__bluebutton-web-server-5
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- When editing an application user can select capabilities not allowed by his groups --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `apps/dot_ext/views/application.py` Content: ``` 1 from django.core.urlresolvers import reverse_lazy 2 from django.forms.models import modelform_factory 3 from django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView 4 5 from braces.views import LoginRequiredMixin 6 7 from oauth2_provider.models import get_application_model 8 9 10 class ApplicationOwnerIsUserMixin(LoginRequiredMixin): 11 """ 12 This mixin is used to provide an Application queryset filtered by the current request.user. 13 """ 14 fields = '__all__' 15 16 def get_queryset(self): 17 return get_application_model().objects.filter(user=self.request.user) 18 19 20 class ApplicationRegistration(LoginRequiredMixin, CreateView): 21 """ 22 View used to register a new Application for the request.user 23 """ 24 template_name = "application_registration_form.html" 25 26 def get_form_class(self): 27 """ 28 Returns the form class for the application model 29 """ 30 31 mff = modelform_factory( 32 get_application_model(), 33 fields=('name', 'client_id', 'client_secret', 'client_type', 34 'authorization_grant_type', 'scope', 'redirect_uris', ) 35 ) 36 return mff 37 38 39 40 def form_valid(self, form): 41 form.instance.user = self.request.user 42 return super(ApplicationRegistration, self).form_valid(form) 43 44 45 class ApplicationDetail(ApplicationOwnerIsUserMixin, DetailView): 46 """ 47 Detail view for an application instance owned by the request.user 48 """ 49 context_object_name = 'application' 50 template_name = "application_detail.html" 51 52 53 class ApplicationList(ApplicationOwnerIsUserMixin, ListView): 54 """ 55 List view for all the applications owned by the request.user 56 """ 57 context_object_name = 'applications' 58 template_name = "application_list.html" 59 60 61 class ApplicationDelete(ApplicationOwnerIsUserMixin, DeleteView): 62 """ 63 View used to delete an application owned by the request.user 64 """ 65 context_object_name = 'application' 66 success_url = reverse_lazy('dote_list') 67 template_name = "application_confirm_delete.html" 68 69 70 class ApplicationUpdate(ApplicationOwnerIsUserMixin, UpdateView): 71 """ 72 View used to update an application owned by the request.user 73 """ 74 context_object_name = 'application' 75 template_name = "application_form.html" 76 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/apps/dot_ext/views/application.py b/apps/dot_ext/views/application.py --- a/apps/dot_ext/views/application.py +++ b/apps/dot_ext/views/application.py @@ -6,6 +6,8 @@ from oauth2_provider.models import get_application_model +from ..forms import CustomRegisterApplicationForm + class ApplicationOwnerIsUserMixin(LoginRequiredMixin): """ @@ -27,15 +29,15 @@ """ Returns the form class for the application model """ - + mff = modelform_factory( get_application_model(), fields=('name', 'client_id', 'client_secret', 'client_type', 'authorization_grant_type', 'scope', 'redirect_uris', ) ) return mff - - + + def form_valid(self, form): form.instance.user = self.request.user @@ -73,3 +75,15 @@ """ context_object_name = 'application' template_name = "application_form.html" + + fields = None + form_class = CustomRegisterApplicationForm + + def get_form_kwargs(self): + """ + Add `user` to kwargs because it is required by the constructor of + CustomRegisterApplicationForm class. + """ + kwargs = super(ApplicationUpdate, self).get_form_kwargs() + kwargs['user'] = self.request.user + return kwargs
{"golden_diff": "diff --git a/apps/dot_ext/views/application.py b/apps/dot_ext/views/application.py\n--- a/apps/dot_ext/views/application.py\n+++ b/apps/dot_ext/views/application.py\n@@ -6,6 +6,8 @@\n \n from oauth2_provider.models import get_application_model\n \n+from ..forms import CustomRegisterApplicationForm\n+\n \n class ApplicationOwnerIsUserMixin(LoginRequiredMixin):\n \"\"\"\n@@ -27,15 +29,15 @@\n \"\"\"\n Returns the form class for the application model\n \"\"\"\n- \n+\n mff = modelform_factory(\n get_application_model(),\n fields=('name', 'client_id', 'client_secret', 'client_type',\n 'authorization_grant_type', 'scope', 'redirect_uris', )\n )\n return mff\n- \n- \n+\n+\n \n def form_valid(self, form):\n form.instance.user = self.request.user\n@@ -73,3 +75,15 @@\n \"\"\"\n context_object_name = 'application'\n template_name = \"application_form.html\"\n+\n+ fields = None\n+ form_class = CustomRegisterApplicationForm\n+\n+ def get_form_kwargs(self):\n+ \"\"\"\n+ Add `user` to kwargs because it is required by the constructor of\n+ CustomRegisterApplicationForm class.\n+ \"\"\"\n+ kwargs = super(ApplicationUpdate, self).get_form_kwargs()\n+ kwargs['user'] = self.request.user\n+ return kwargs\n", "issue": "When editing an application user can select capabilities not allowed by his groups\n\n", "before_files": [{"content": "from django.core.urlresolvers import reverse_lazy\nfrom django.forms.models import modelform_factory\nfrom django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView\n\nfrom braces.views import LoginRequiredMixin\n\nfrom oauth2_provider.models import get_application_model\n\n\nclass ApplicationOwnerIsUserMixin(LoginRequiredMixin):\n \"\"\"\n This mixin is used to provide an Application queryset filtered by the current request.user.\n \"\"\"\n fields = '__all__'\n\n def get_queryset(self):\n return get_application_model().objects.filter(user=self.request.user)\n\n\nclass ApplicationRegistration(LoginRequiredMixin, CreateView):\n \"\"\"\n View used to register a new Application for the request.user\n \"\"\"\n template_name = \"application_registration_form.html\"\n\n def get_form_class(self):\n \"\"\"\n Returns the form class for the application model\n \"\"\"\n \n mff = modelform_factory(\n get_application_model(),\n fields=('name', 'client_id', 'client_secret', 'client_type',\n 'authorization_grant_type', 'scope', 'redirect_uris', )\n )\n return mff\n \n \n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super(ApplicationRegistration, self).form_valid(form)\n\n\nclass ApplicationDetail(ApplicationOwnerIsUserMixin, DetailView):\n \"\"\"\n Detail view for an application instance owned by the request.user\n \"\"\"\n context_object_name = 'application'\n template_name = \"application_detail.html\"\n\n\nclass ApplicationList(ApplicationOwnerIsUserMixin, ListView):\n \"\"\"\n List view for all the applications owned by the request.user\n \"\"\"\n context_object_name = 'applications'\n template_name = \"application_list.html\"\n\n\nclass ApplicationDelete(ApplicationOwnerIsUserMixin, DeleteView):\n \"\"\"\n View used to delete an application owned by the request.user\n \"\"\"\n context_object_name = 'application'\n success_url = reverse_lazy('dote_list')\n template_name = \"application_confirm_delete.html\"\n\n\nclass ApplicationUpdate(ApplicationOwnerIsUserMixin, UpdateView):\n \"\"\"\n View used to update an application owned by the request.user\n \"\"\"\n context_object_name = 'application'\n template_name = \"application_form.html\"\n", "path": "apps/dot_ext/views/application.py"}], "after_files": [{"content": "from django.core.urlresolvers import reverse_lazy\nfrom django.forms.models import modelform_factory\nfrom django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView\n\nfrom braces.views import LoginRequiredMixin\n\nfrom oauth2_provider.models import get_application_model\n\nfrom ..forms import CustomRegisterApplicationForm\n\n\nclass ApplicationOwnerIsUserMixin(LoginRequiredMixin):\n \"\"\"\n This mixin is used to provide an Application queryset filtered by the current request.user.\n \"\"\"\n fields = '__all__'\n\n def get_queryset(self):\n return get_application_model().objects.filter(user=self.request.user)\n\n\nclass ApplicationRegistration(LoginRequiredMixin, CreateView):\n \"\"\"\n View used to register a new Application for the request.user\n \"\"\"\n template_name = \"application_registration_form.html\"\n\n def get_form_class(self):\n \"\"\"\n Returns the form class for the application model\n \"\"\"\n\n mff = modelform_factory(\n get_application_model(),\n fields=('name', 'client_id', 'client_secret', 'client_type',\n 'authorization_grant_type', 'scope', 'redirect_uris', )\n )\n return mff\n\n\n\n def form_valid(self, form):\n form.instance.user = self.request.user\n return super(ApplicationRegistration, self).form_valid(form)\n\n\nclass ApplicationDetail(ApplicationOwnerIsUserMixin, DetailView):\n \"\"\"\n Detail view for an application instance owned by the request.user\n \"\"\"\n context_object_name = 'application'\n template_name = \"application_detail.html\"\n\n\nclass ApplicationList(ApplicationOwnerIsUserMixin, ListView):\n \"\"\"\n List view for all the applications owned by the request.user\n \"\"\"\n context_object_name = 'applications'\n template_name = \"application_list.html\"\n\n\nclass ApplicationDelete(ApplicationOwnerIsUserMixin, DeleteView):\n \"\"\"\n View used to delete an application owned by the request.user\n \"\"\"\n context_object_name = 'application'\n success_url = reverse_lazy('dote_list')\n template_name = \"application_confirm_delete.html\"\n\n\nclass ApplicationUpdate(ApplicationOwnerIsUserMixin, UpdateView):\n \"\"\"\n View used to update an application owned by the request.user\n \"\"\"\n context_object_name = 'application'\n template_name = \"application_form.html\"\n\n fields = None\n form_class = CustomRegisterApplicationForm\n\n def get_form_kwargs(self):\n \"\"\"\n Add `user` to kwargs because it is required by the constructor of\n CustomRegisterApplicationForm class.\n \"\"\"\n kwargs = super(ApplicationUpdate, self).get_form_kwargs()\n kwargs['user'] = self.request.user\n return kwargs\n", "path": "apps/dot_ext/views/application.py"}]}
885
312
gh_patches_debug_34316
rasdani/github-patches
git_diff
meltano__meltano-6856
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- bug: Flaky test `tests/meltano/api/test_workers.py::TestUIAvailableWorker::test_open_browser` ### Meltano Version N/A ### Python Version NA ### Bug scope API ### Operating System N/A ### Description From https://github.com/meltano/meltano/issues/6827 - https://github.com/meltano/meltano/actions/runs/3175819389/jobs/5174350171 - https://github.com/meltano/meltano/actions/runs/3159179840/jobs/5142085679 - https://github.com/meltano/meltano/actions/runs/3056794521/jobs/4931297918 - https://github.com/meltano/meltano/actions/runs/3182662282/jobs/5188896027 - https://github.com/meltano/meltano/actions/runs/3183540252/jobs/5190883701 - https://github.com/meltano/meltano/actions/runs/3184585185/jobs/5193156601 Of the recorded instances, we observe: - They are all using `ubuntu-latest` - They are all using Python 3.7 - They are using a variety of database backends The error occurs on the assert on the last line of the following code block. We see that `requests_get` is always called 3 times, but `sleep` is called 300-500 times. ```python @mock.patch("webbrowser.open") @mock.patch("requests.get") def test_open_browser(self, requests_get, webbrowser_open, subject): error = mock.Mock(status_code=400) ok = mock.Mock(status_code=200) requests_get.side_effect = [error, error, ok] with mock.patch("time.sleep") as sleep: sleep.return_value = None subject.run() webbrowser_open.assert_called_with("http://localhost:5000") assert requests_get.call_count == sleep.call_count ``` ### Code _No response_ --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/meltano/api/workers/ui_available_worker.py` Content: ``` 1 from __future__ import annotations 2 3 import logging 4 import threading 5 import time 6 import traceback 7 import webbrowser 8 9 import click 10 import requests 11 12 from meltano.core.project_settings_service import ProjectSettingsService 13 14 logger = logging.getLogger(__name__) 15 16 SUCCESS_STATUS_CODE = 200 17 18 19 class UIAvailableWorker(threading.Thread): 20 def __init__(self, project, open_browser=False): 21 super().__init__() 22 self.project = project 23 self.open_browser = open_browser 24 self.settings_service = ProjectSettingsService(self.project) 25 self._terminate = False 26 27 def run(self): 28 url = f"http://localhost:{self.settings_service.get('ui.bind_port')}" 29 headers = {"Host": self.settings_service.get("ui.server_name")} 30 31 while not self._terminate: 32 try: 33 response = requests.get(url, headers=headers) 34 if response.status_code == SUCCESS_STATUS_CODE: 35 click.secho(f"Meltano UI is now available at {url}", fg="green") 36 if self.open_browser: 37 webbrowser.open(url) 38 self._terminate = True 39 except Exception: 40 logger.debug( 41 f"Exception encountered while trying to run Meltano UI:\n{traceback.format_exc()}" 42 ) 43 44 time.sleep(2) 45 46 def stop(self): 47 self._terminate = True 48 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/meltano/api/workers/ui_available_worker.py b/src/meltano/api/workers/ui_available_worker.py --- a/src/meltano/api/workers/ui_available_worker.py +++ b/src/meltano/api/workers/ui_available_worker.py @@ -1,10 +1,11 @@ +"""Meltano UI worker thread definition.""" + from __future__ import annotations import logging import threading import time import traceback -import webbrowser import click import requests @@ -17,14 +18,21 @@ class UIAvailableWorker(threading.Thread): - def __init__(self, project, open_browser=False): + """A thread subclass for Meltano UI workers.""" + + def __init__(self, project): + """Initialize the `UIAvailableWorker` thread. + + Args: + project: The Meltano project. + """ super().__init__() self.project = project - self.open_browser = open_browser self.settings_service = ProjectSettingsService(self.project) self._terminate = False - def run(self): + def run(self) -> None: + """Run the thread, and report when the Meltano UI becomes available.""" url = f"http://localhost:{self.settings_service.get('ui.bind_port')}" headers = {"Host": self.settings_service.get("ui.server_name")} @@ -33,8 +41,6 @@ response = requests.get(url, headers=headers) if response.status_code == SUCCESS_STATUS_CODE: click.secho(f"Meltano UI is now available at {url}", fg="green") - if self.open_browser: - webbrowser.open(url) self._terminate = True except Exception: logger.debug( @@ -44,4 +50,5 @@ time.sleep(2) def stop(self): + """Stop the thread.""" self._terminate = True
{"golden_diff": "diff --git a/src/meltano/api/workers/ui_available_worker.py b/src/meltano/api/workers/ui_available_worker.py\n--- a/src/meltano/api/workers/ui_available_worker.py\n+++ b/src/meltano/api/workers/ui_available_worker.py\n@@ -1,10 +1,11 @@\n+\"\"\"Meltano UI worker thread definition.\"\"\"\n+\n from __future__ import annotations\n \n import logging\n import threading\n import time\n import traceback\n-import webbrowser\n \n import click\n import requests\n@@ -17,14 +18,21 @@\n \n \n class UIAvailableWorker(threading.Thread):\n- def __init__(self, project, open_browser=False):\n+ \"\"\"A thread subclass for Meltano UI workers.\"\"\"\n+\n+ def __init__(self, project):\n+ \"\"\"Initialize the `UIAvailableWorker` thread.\n+\n+ Args:\n+ project: The Meltano project.\n+ \"\"\"\n super().__init__()\n self.project = project\n- self.open_browser = open_browser\n self.settings_service = ProjectSettingsService(self.project)\n self._terminate = False\n \n- def run(self):\n+ def run(self) -> None:\n+ \"\"\"Run the thread, and report when the Meltano UI becomes available.\"\"\"\n url = f\"http://localhost:{self.settings_service.get('ui.bind_port')}\"\n headers = {\"Host\": self.settings_service.get(\"ui.server_name\")}\n \n@@ -33,8 +41,6 @@\n response = requests.get(url, headers=headers)\n if response.status_code == SUCCESS_STATUS_CODE:\n click.secho(f\"Meltano UI is now available at {url}\", fg=\"green\")\n- if self.open_browser:\n- webbrowser.open(url)\n self._terminate = True\n except Exception:\n logger.debug(\n@@ -44,4 +50,5 @@\n time.sleep(2)\n \n def stop(self):\n+ \"\"\"Stop the thread.\"\"\"\n self._terminate = True\n", "issue": "bug: Flaky test `tests/meltano/api/test_workers.py::TestUIAvailableWorker::test_open_browser`\n### Meltano Version\n\nN/A\n\n### Python Version\n\nNA\n\n### Bug scope\n\nAPI\n\n### Operating System\n\nN/A\n\n### Description\n\nFrom https://github.com/meltano/meltano/issues/6827\r\n\r\n- https://github.com/meltano/meltano/actions/runs/3175819389/jobs/5174350171\r\n- https://github.com/meltano/meltano/actions/runs/3159179840/jobs/5142085679\r\n- https://github.com/meltano/meltano/actions/runs/3056794521/jobs/4931297918\r\n- https://github.com/meltano/meltano/actions/runs/3182662282/jobs/5188896027\r\n- https://github.com/meltano/meltano/actions/runs/3183540252/jobs/5190883701\r\n- https://github.com/meltano/meltano/actions/runs/3184585185/jobs/5193156601\r\n\r\nOf the recorded instances, we observe:\r\n- They are all using `ubuntu-latest`\r\n- They are all using Python 3.7\r\n- They are using a variety of database backends\r\n\r\nThe error occurs on the assert on the last line of the following code block. We see that `requests_get` is always called 3 times, but `sleep` is called 300-500 times.\r\n\r\n```python\r\n @mock.patch(\"webbrowser.open\")\r\n @mock.patch(\"requests.get\")\r\n def test_open_browser(self, requests_get, webbrowser_open, subject):\r\n error = mock.Mock(status_code=400)\r\n ok = mock.Mock(status_code=200)\r\n requests_get.side_effect = [error, error, ok]\r\n with mock.patch(\"time.sleep\") as sleep:\r\n sleep.return_value = None\r\n subject.run()\r\n webbrowser_open.assert_called_with(\"http://localhost:5000\")\r\n assert requests_get.call_count == sleep.call_count\r\n```\n\n### Code\n\n_No response_\n", "before_files": [{"content": "from __future__ import annotations\n\nimport logging\nimport threading\nimport time\nimport traceback\nimport webbrowser\n\nimport click\nimport requests\n\nfrom meltano.core.project_settings_service import ProjectSettingsService\n\nlogger = logging.getLogger(__name__)\n\nSUCCESS_STATUS_CODE = 200\n\n\nclass UIAvailableWorker(threading.Thread):\n def __init__(self, project, open_browser=False):\n super().__init__()\n self.project = project\n self.open_browser = open_browser\n self.settings_service = ProjectSettingsService(self.project)\n self._terminate = False\n\n def run(self):\n url = f\"http://localhost:{self.settings_service.get('ui.bind_port')}\"\n headers = {\"Host\": self.settings_service.get(\"ui.server_name\")}\n\n while not self._terminate:\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == SUCCESS_STATUS_CODE:\n click.secho(f\"Meltano UI is now available at {url}\", fg=\"green\")\n if self.open_browser:\n webbrowser.open(url)\n self._terminate = True\n except Exception:\n logger.debug(\n f\"Exception encountered while trying to run Meltano UI:\\n{traceback.format_exc()}\"\n )\n\n time.sleep(2)\n\n def stop(self):\n self._terminate = True\n", "path": "src/meltano/api/workers/ui_available_worker.py"}], "after_files": [{"content": "\"\"\"Meltano UI worker thread definition.\"\"\"\n\nfrom __future__ import annotations\n\nimport logging\nimport threading\nimport time\nimport traceback\n\nimport click\nimport requests\n\nfrom meltano.core.project_settings_service import ProjectSettingsService\n\nlogger = logging.getLogger(__name__)\n\nSUCCESS_STATUS_CODE = 200\n\n\nclass UIAvailableWorker(threading.Thread):\n \"\"\"A thread subclass for Meltano UI workers.\"\"\"\n\n def __init__(self, project):\n \"\"\"Initialize the `UIAvailableWorker` thread.\n\n Args:\n project: The Meltano project.\n \"\"\"\n super().__init__()\n self.project = project\n self.settings_service = ProjectSettingsService(self.project)\n self._terminate = False\n\n def run(self) -> None:\n \"\"\"Run the thread, and report when the Meltano UI becomes available.\"\"\"\n url = f\"http://localhost:{self.settings_service.get('ui.bind_port')}\"\n headers = {\"Host\": self.settings_service.get(\"ui.server_name\")}\n\n while not self._terminate:\n try:\n response = requests.get(url, headers=headers)\n if response.status_code == SUCCESS_STATUS_CODE:\n click.secho(f\"Meltano UI is now available at {url}\", fg=\"green\")\n self._terminate = True\n except Exception:\n logger.debug(\n f\"Exception encountered while trying to run Meltano UI:\\n{traceback.format_exc()}\"\n )\n\n time.sleep(2)\n\n def stop(self):\n \"\"\"Stop the thread.\"\"\"\n self._terminate = True\n", "path": "src/meltano/api/workers/ui_available_worker.py"}]}
1,159
423
gh_patches_debug_167
rasdani/github-patches
git_diff
jupyterhub__jupyterhub-1526
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Jupyterhub 0.8.0 radio buttons unclickable or ugly due to form-control class ``` jupyterhub --version 0.8.0 ``` I have some radio buttons in my spawner's `_option_form_default`: ``` return """<label for="type">Which type of instance do you want to launch?</label> <table> <tr> <td><input type="radio" name="type" value="c4.8xlarge" checked="checked"></td> <td>&nbsp;c4.8xlarge (36 CPU, 60GB RAM, $1.591/h)</td> </tr> <tr> <td><input type="radio" name="type" value="r4.8xlarge"></td> <td>&nbsp;r4.8xlarge (32 CPU, 244GB RAM, $2.341/h)</td> </tr> </table><br> """ ``` In `0.8.0` version these are unclickable. Removing `form-control` class introduced [here](https://github.com/jupyterhub/jupyterhub/blob/master/share/jupyter/hub/templates/spawn.html) fixes the issue for me. I also tried buttons like this: ``` <tr> <td><label> <input type="radio" name="type" value="c4.8xlarge"> &nbsp;c4.8xlarge (36 CPU, 60GB RAM, $1.591/h) </label></td> </tr> ``` These are clickable but look ugly with the `form-control` class. Removing the `form-control` class makes them both clickable and pretty :) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `jupyterhub/_version.py` Content: ``` 1 """JupyterHub version info""" 2 3 # Copyright (c) Jupyter Development Team. 4 # Distributed under the terms of the Modified BSD License. 5 6 version_info = ( 7 0, 8 8, 9 2, 10 'dev', 11 ) 12 13 __version__ = '.'.join(map(str, version_info)) 14 15 16 def _check_version(hub_version, singleuser_version, log): 17 """Compare Hub and single-user server versions""" 18 if not hub_version: 19 log.warning("Hub has no version header, which means it is likely < 0.8. Expected %s", __version__) 20 return 21 22 if not singleuser_version: 23 log.warning("Single-user server has no version header, which means it is likely < 0.8. Expected %s", __version__) 24 return 25 26 # compare minor X.Y versions 27 if hub_version != singleuser_version: 28 from distutils.version import LooseVersion as V 29 hub_major_minor = V(hub_version).version[:2] 30 singleuser_major_minor = V(singleuser_version).version[:2] 31 extra = "" 32 if singleuser_major_minor == hub_major_minor: 33 # patch-level mismatch or lower, log difference at debug-level 34 # because this should be fine 35 log_method = log.debug 36 else: 37 # log warning-level for more significant mismatch, such as 0.8 vs 0.9, etc. 38 log_method = log.warning 39 extra = " This could cause failure to authenticate and result in redirect loops!" 40 log_method( 41 "jupyterhub version %s != jupyterhub-singleuser version %s." + extra, 42 hub_version, 43 singleuser_version, 44 ) 45 else: 46 log.debug("jupyterhub and jupyterhub-singleuser both on version %s" % hub_version) 47 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py --- a/jupyterhub/_version.py +++ b/jupyterhub/_version.py @@ -6,8 +6,8 @@ version_info = ( 0, 8, - 1, - # 'dev', + 2, + 'dev', ) __version__ = '.'.join(map(str, version_info))
{"golden_diff": "diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py\n--- a/jupyterhub/_version.py\n+++ b/jupyterhub/_version.py\n@@ -6,8 +6,8 @@\n version_info = (\n 0,\n 8,\n- 1,\n- # 'dev',\n+ 2,\n+ 'dev',\n )\n \n __version__ = '.'.join(map(str, version_info))\n", "issue": "Jupyterhub 0.8.0 radio buttons unclickable or ugly due to form-control class\n```\r\njupyterhub --version\r\n0.8.0\r\n```\r\n\r\nI have some radio buttons in my spawner's `_option_form_default`:\r\n\r\n```\r\nreturn \"\"\"<label for=\"type\">Which type of instance do you want to launch?</label>\r\n <table>\r\n <tr>\r\n <td><input type=\"radio\" name=\"type\" value=\"c4.8xlarge\" checked=\"checked\"></td>\r\n <td>&nbsp;c4.8xlarge (36 CPU, 60GB RAM, $1.591/h)</td>\r\n </tr>\r\n <tr>\r\n <td><input type=\"radio\" name=\"type\" value=\"r4.8xlarge\"></td>\r\n <td>&nbsp;r4.8xlarge (32 CPU, 244GB RAM, $2.341/h)</td>\r\n </tr>\r\n </table><br>\r\n \"\"\"\r\n```\r\n\r\nIn `0.8.0` version these are unclickable. Removing `form-control` class introduced [here](https://github.com/jupyterhub/jupyterhub/blob/master/share/jupyter/hub/templates/spawn.html) fixes the issue for me. \r\n\r\nI also tried buttons like this:\r\n\r\n```\r\n <tr>\r\n <td><label>\r\n <input type=\"radio\" name=\"type\" value=\"c4.8xlarge\">\r\n &nbsp;c4.8xlarge (36 CPU, 60GB RAM, $1.591/h)\r\n </label></td>\r\n </tr>\r\n```\r\n\r\nThese are clickable but look ugly with the `form-control` class. \r\n\r\nRemoving the `form-control` class makes them both clickable and pretty :) \n", "before_files": [{"content": "\"\"\"JupyterHub version info\"\"\"\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nversion_info = (\n 0,\n 8,\n 2,\n 'dev',\n)\n\n__version__ = '.'.join(map(str, version_info))\n\n\ndef _check_version(hub_version, singleuser_version, log):\n \"\"\"Compare Hub and single-user server versions\"\"\"\n if not hub_version:\n log.warning(\"Hub has no version header, which means it is likely < 0.8. Expected %s\", __version__)\n return\n\n if not singleuser_version:\n log.warning(\"Single-user server has no version header, which means it is likely < 0.8. Expected %s\", __version__)\n return\n\n # compare minor X.Y versions\n if hub_version != singleuser_version:\n from distutils.version import LooseVersion as V\n hub_major_minor = V(hub_version).version[:2]\n singleuser_major_minor = V(singleuser_version).version[:2]\n extra = \"\"\n if singleuser_major_minor == hub_major_minor:\n # patch-level mismatch or lower, log difference at debug-level\n # because this should be fine\n log_method = log.debug\n else:\n # log warning-level for more significant mismatch, such as 0.8 vs 0.9, etc.\n log_method = log.warning\n extra = \" This could cause failure to authenticate and result in redirect loops!\"\n log_method(\n \"jupyterhub version %s != jupyterhub-singleuser version %s.\" + extra,\n hub_version,\n singleuser_version,\n )\n else:\n log.debug(\"jupyterhub and jupyterhub-singleuser both on version %s\" % hub_version)\n", "path": "jupyterhub/_version.py"}], "after_files": [{"content": "\"\"\"JupyterHub version info\"\"\"\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nversion_info = (\n 0,\n 8,\n 2,\n 'dev',\n)\n\n__version__ = '.'.join(map(str, version_info))\n\n\ndef _check_version(hub_version, singleuser_version, log):\n \"\"\"Compare Hub and single-user server versions\"\"\"\n if not hub_version:\n log.warning(\"Hub has no version header, which means it is likely < 0.8. Expected %s\", __version__)\n return\n\n if not singleuser_version:\n log.warning(\"Single-user server has no version header, which means it is likely < 0.8. Expected %s\", __version__)\n return\n\n # compare minor X.Y versions\n if hub_version != singleuser_version:\n from distutils.version import LooseVersion as V\n hub_major_minor = V(hub_version).version[:2]\n singleuser_major_minor = V(singleuser_version).version[:2]\n extra = \"\"\n if singleuser_major_minor == hub_major_minor:\n # patch-level mismatch or lower, log difference at debug-level\n # because this should be fine\n log_method = log.debug\n else:\n # log warning-level for more significant mismatch, such as 0.8 vs 0.9, etc.\n log_method = log.warning\n extra = \" This could cause failure to authenticate and result in redirect loops!\"\n log_method(\n \"jupyterhub version %s != jupyterhub-singleuser version %s.\" + extra,\n hub_version,\n singleuser_version,\n )\n else:\n log.debug(\"jupyterhub and jupyterhub-singleuser both on version %s\" % hub_version)\n", "path": "jupyterhub/_version.py"}]}
1,114
94
gh_patches_debug_13267
rasdani/github-patches
git_diff
PokemonGoF__PokemonGo-Bot-1025
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Bot unnecessarily walks to center of Pokestops This issue may also increase detectability since it's unlikely that users would walk to the exact center of every stop they visit. Also, most stops are spinnable from the road or other more accessible place. Once we start following roads, this will need fixed. ### Expected Behavior Bot should walk to anywhere within the range of the stop. ### Actual Behavior Bot walks to exactly the center of a stop. ### Steps to Reproduce Run the bot and observe its path. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pokemongo_bot/cell_workers/move_to_fort_worker.py` Content: ``` 1 from utils import distance, format_dist 2 from pokemongo_bot.human_behaviour import sleep 3 from pokemongo_bot import logger 4 from pokemongo_bot.step_walker import StepWalker 5 6 class MoveToFortWorker(object): 7 def __init__(self, fort, bot): 8 self.bot = bot 9 self.fort = fort 10 self.api = bot.api 11 self.config = bot.config 12 self.navigator = bot.navigator 13 self.position = bot.position 14 15 def work(self): 16 lat = self.fort['latitude'] 17 lng = self.fort['longitude'] 18 fortID = self.fort['id'] 19 unit = self.config.distance_unit # Unit to use when printing formatted distance 20 21 dist = distance(self.position[0], self.position[1], lat, lng) 22 23 # print('Found fort {} at distance {}m'.format(fortID, dist)) 24 logger.log('Found fort {} at distance {}'.format( 25 fortID, format_dist(dist, unit))) 26 27 if dist > 10: 28 logger.log('Need to move closer to Pokestop') 29 position = (lat, lng, 0.0) 30 31 if self.config.walk > 0: 32 step_walker = StepWalker( 33 self.bot, 34 self.config.walk, 35 self.api._position_lat, 36 self.api._position_lng, 37 position[0], 38 position[1] 39 ) 40 41 while True: 42 if step_walker.step(): 43 break 44 45 else: 46 self.api.set_position(*position) 47 48 self.api.player_update(latitude=lat, longitude=lng) 49 response_dict = self.api.call() 50 logger.log('Arrived at Pokestop') 51 sleep(2) 52 return response_dict 53 54 return None 55 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pokemongo_bot/cell_workers/move_to_fort_worker.py b/pokemongo_bot/cell_workers/move_to_fort_worker.py --- a/pokemongo_bot/cell_workers/move_to_fort_worker.py +++ b/pokemongo_bot/cell_workers/move_to_fort_worker.py @@ -1,4 +1,4 @@ -from utils import distance, format_dist +from utils import distance, format_dist, i2f from pokemongo_bot.human_behaviour import sleep from pokemongo_bot import logger from pokemongo_bot.step_walker import StepWalker @@ -38,7 +38,7 @@ position[1] ) - while True: + while distance(i2f(self.api._position_lat), i2f(self.api._position_lng), lat, lng) > 10: if step_walker.step(): break
{"golden_diff": "diff --git a/pokemongo_bot/cell_workers/move_to_fort_worker.py b/pokemongo_bot/cell_workers/move_to_fort_worker.py\n--- a/pokemongo_bot/cell_workers/move_to_fort_worker.py\n+++ b/pokemongo_bot/cell_workers/move_to_fort_worker.py\n@@ -1,4 +1,4 @@\n-from utils import distance, format_dist\n+from utils import distance, format_dist, i2f\n from pokemongo_bot.human_behaviour import sleep\n from pokemongo_bot import logger\n from pokemongo_bot.step_walker import StepWalker\n@@ -38,7 +38,7 @@\n position[1]\n )\n \n- while True:\n+ while distance(i2f(self.api._position_lat), i2f(self.api._position_lng), lat, lng) > 10:\n if step_walker.step():\n break\n", "issue": "Bot unnecessarily walks to center of Pokestops\nThis issue may also increase detectability since it's unlikely that users would walk to the exact center of every stop they visit.\n\nAlso, most stops are spinnable from the road or other more accessible place. Once we start following roads, this will need fixed.\n### Expected Behavior\n\nBot should walk to anywhere within the range of the stop.\n### Actual Behavior\n\nBot walks to exactly the center of a stop.\n### Steps to Reproduce\n\nRun the bot and observe its path.\n\n", "before_files": [{"content": "from utils import distance, format_dist\nfrom pokemongo_bot.human_behaviour import sleep\nfrom pokemongo_bot import logger\nfrom pokemongo_bot.step_walker import StepWalker\n\nclass MoveToFortWorker(object):\n def __init__(self, fort, bot):\n self.bot = bot\n self.fort = fort\n self.api = bot.api\n self.config = bot.config\n self.navigator = bot.navigator\n self.position = bot.position\n\n def work(self):\n lat = self.fort['latitude']\n lng = self.fort['longitude']\n fortID = self.fort['id']\n unit = self.config.distance_unit # Unit to use when printing formatted distance\n\n dist = distance(self.position[0], self.position[1], lat, lng)\n\n # print('Found fort {} at distance {}m'.format(fortID, dist))\n logger.log('Found fort {} at distance {}'.format(\n fortID, format_dist(dist, unit)))\n\n if dist > 10:\n logger.log('Need to move closer to Pokestop')\n position = (lat, lng, 0.0)\n\n if self.config.walk > 0:\n step_walker = StepWalker(\n self.bot,\n self.config.walk,\n self.api._position_lat,\n self.api._position_lng,\n position[0],\n position[1]\n )\n\n while True:\n if step_walker.step():\n break\n\n else:\n self.api.set_position(*position)\n\n self.api.player_update(latitude=lat, longitude=lng)\n response_dict = self.api.call()\n logger.log('Arrived at Pokestop')\n sleep(2)\n return response_dict\n\n return None\n", "path": "pokemongo_bot/cell_workers/move_to_fort_worker.py"}], "after_files": [{"content": "from utils import distance, format_dist, i2f\nfrom pokemongo_bot.human_behaviour import sleep\nfrom pokemongo_bot import logger\nfrom pokemongo_bot.step_walker import StepWalker\n\nclass MoveToFortWorker(object):\n def __init__(self, fort, bot):\n self.bot = bot\n self.fort = fort\n self.api = bot.api\n self.config = bot.config\n self.navigator = bot.navigator\n self.position = bot.position\n\n def work(self):\n lat = self.fort['latitude']\n lng = self.fort['longitude']\n fortID = self.fort['id']\n unit = self.config.distance_unit # Unit to use when printing formatted distance\n\n dist = distance(self.position[0], self.position[1], lat, lng)\n\n # print('Found fort {} at distance {}m'.format(fortID, dist))\n logger.log('Found fort {} at distance {}'.format(\n fortID, format_dist(dist, unit)))\n\n if dist > 10:\n logger.log('Need to move closer to Pokestop')\n position = (lat, lng, 0.0)\n\n if self.config.walk > 0:\n step_walker = StepWalker(\n self.bot,\n self.config.walk,\n self.api._position_lat,\n self.api._position_lng,\n position[0],\n position[1]\n )\n\n while distance(i2f(self.api._position_lat), i2f(self.api._position_lng), lat, lng) > 10:\n if step_walker.step():\n break\n\n else:\n self.api.set_position(*position)\n\n self.api.player_update(latitude=lat, longitude=lng)\n response_dict = self.api.call()\n logger.log('Arrived at Pokestop')\n sleep(2)\n return response_dict\n\n return None\n", "path": "pokemongo_bot/cell_workers/move_to_fort_worker.py"}]}
849
201
gh_patches_debug_48993
rasdani/github-patches
git_diff
googleapis__google-api-python-client-1030
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- googleapiclient.discovery.build fails with module 'six.moves' has no attribute 'collections_abc' since version 1.12.0 #### Environment details - OS type and version: 18.04.1-Ubuntu - Python version: Python 3.6.9 - pip version: `pip --version` pip 9.0.1 - `google-api-python-client` version: `pip show google-api-python-client`: Version: 1.12.0 #### Code example googleapiclient.discovery.build() fails with message: module 'six.moves' has no attribute 'collections_abc' We only see this problem with google-api-python-client 1.12.0. 1.11.0 is fine. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 # Copyright 2014 Google Inc. All Rights Reserved. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """Setup script for Google API Python client. 16 17 Also installs included versions of third party libraries, if those libraries 18 are not already installed. 19 """ 20 from __future__ import print_function 21 22 import sys 23 24 if sys.version_info < (2, 7): 25 print("google-api-python-client requires python version >= 2.7.", file=sys.stderr) 26 sys.exit(1) 27 if (3, 1) <= sys.version_info < (3, 4): 28 print("google-api-python-client requires python3 version >= 3.4.", file=sys.stderr) 29 sys.exit(1) 30 31 import io 32 import os 33 from setuptools import setup 34 35 packages = ["apiclient", "googleapiclient", "googleapiclient/discovery_cache"] 36 37 install_requires = [ 38 # NOTE: Apache Beam tests depend on this library and cannot 39 # currently upgrade their httplib2 version. 40 # Please see https://github.com/googleapis/google-api-python-client/pull/841 41 "httplib2>=0.9.2,<1dev", 42 "google-auth>=1.16.0", 43 "google-auth-httplib2>=0.0.3", 44 "google-api-core>=1.21.0,<2dev", 45 "six>=1.6.1,<2dev", 46 "uritemplate>=3.0.0,<4dev", 47 ] 48 49 package_root = os.path.abspath(os.path.dirname(__file__)) 50 51 readme_filename = os.path.join(package_root, "README.md") 52 with io.open(readme_filename, encoding="utf-8") as readme_file: 53 readme = readme_file.read() 54 55 version = "1.12.0" 56 57 setup( 58 name="google-api-python-client", 59 version=version, 60 description="Google API Client Library for Python", 61 long_description=readme, 62 long_description_content_type='text/markdown', 63 author="Google LLC", 64 author_email="[email protected]", 65 url="https://github.com/googleapis/google-api-python-client/", 66 install_requires=install_requires, 67 python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", 68 packages=packages, 69 package_data={}, 70 license="Apache 2.0", 71 keywords="google api client", 72 classifiers=[ 73 "Programming Language :: Python :: 2", 74 "Programming Language :: Python :: 2.7", 75 "Programming Language :: Python :: 3", 76 "Programming Language :: Python :: 3.5", 77 "Programming Language :: Python :: 3.6", 78 "Programming Language :: Python :: 3.7", 79 "Development Status :: 5 - Production/Stable", 80 "Intended Audience :: Developers", 81 "License :: OSI Approved :: Apache Software License", 82 "Operating System :: OS Independent", 83 "Topic :: Internet :: WWW/HTTP", 84 ], 85 ) 86 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -42,7 +42,7 @@ "google-auth>=1.16.0", "google-auth-httplib2>=0.0.3", "google-api-core>=1.21.0,<2dev", - "six>=1.6.1,<2dev", + "six>=1.13.0,<2dev", "uritemplate>=3.0.0,<4dev", ]
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -42,7 +42,7 @@\n \"google-auth>=1.16.0\",\n \"google-auth-httplib2>=0.0.3\",\n \"google-api-core>=1.21.0,<2dev\",\n- \"six>=1.6.1,<2dev\",\n+ \"six>=1.13.0,<2dev\",\n \"uritemplate>=3.0.0,<4dev\",\n ]\n", "issue": "googleapiclient.discovery.build fails with module 'six.moves' has no attribute 'collections_abc' since version 1.12.0\n#### Environment details\r\n\r\n - OS type and version: 18.04.1-Ubuntu\r\n - Python version: Python 3.6.9\r\n - pip version: `pip --version` pip 9.0.1\r\n - `google-api-python-client` version: `pip show google-api-python-client`: Version: 1.12.0\r\n\r\n#### Code example\r\ngoogleapiclient.discovery.build() fails with message: module 'six.moves' has no attribute 'collections_abc'\r\n\r\nWe only see this problem with google-api-python-client 1.12.0. 1.11.0 is fine.\r\n\r\n\n", "before_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Setup script for Google API Python client.\n\nAlso installs included versions of third party libraries, if those libraries\nare not already installed.\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\n\nif sys.version_info < (2, 7):\n print(\"google-api-python-client requires python version >= 2.7.\", file=sys.stderr)\n sys.exit(1)\nif (3, 1) <= sys.version_info < (3, 4):\n print(\"google-api-python-client requires python3 version >= 3.4.\", file=sys.stderr)\n sys.exit(1)\n\nimport io\nimport os\nfrom setuptools import setup\n\npackages = [\"apiclient\", \"googleapiclient\", \"googleapiclient/discovery_cache\"]\n\ninstall_requires = [\n # NOTE: Apache Beam tests depend on this library and cannot\n # currently upgrade their httplib2 version.\n # Please see https://github.com/googleapis/google-api-python-client/pull/841\n \"httplib2>=0.9.2,<1dev\",\n \"google-auth>=1.16.0\",\n \"google-auth-httplib2>=0.0.3\",\n \"google-api-core>=1.21.0,<2dev\",\n \"six>=1.6.1,<2dev\",\n \"uritemplate>=3.0.0,<4dev\",\n]\n\npackage_root = os.path.abspath(os.path.dirname(__file__))\n\nreadme_filename = os.path.join(package_root, \"README.md\")\nwith io.open(readme_filename, encoding=\"utf-8\") as readme_file:\n readme = readme_file.read()\n\nversion = \"1.12.0\"\n\nsetup(\n name=\"google-api-python-client\",\n version=version,\n description=\"Google API Client Library for Python\",\n long_description=readme,\n long_description_content_type='text/markdown',\n author=\"Google LLC\",\n author_email=\"[email protected]\",\n url=\"https://github.com/googleapis/google-api-python-client/\",\n install_requires=install_requires,\n python_requires=\">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*\",\n packages=packages,\n package_data={},\n license=\"Apache 2.0\",\n keywords=\"google api client\",\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Internet :: WWW/HTTP\",\n ],\n)\n", "path": "setup.py"}], "after_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Setup script for Google API Python client.\n\nAlso installs included versions of third party libraries, if those libraries\nare not already installed.\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\n\nif sys.version_info < (2, 7):\n print(\"google-api-python-client requires python version >= 2.7.\", file=sys.stderr)\n sys.exit(1)\nif (3, 1) <= sys.version_info < (3, 4):\n print(\"google-api-python-client requires python3 version >= 3.4.\", file=sys.stderr)\n sys.exit(1)\n\nimport io\nimport os\nfrom setuptools import setup\n\npackages = [\"apiclient\", \"googleapiclient\", \"googleapiclient/discovery_cache\"]\n\ninstall_requires = [\n # NOTE: Apache Beam tests depend on this library and cannot\n # currently upgrade their httplib2 version.\n # Please see https://github.com/googleapis/google-api-python-client/pull/841\n \"httplib2>=0.9.2,<1dev\",\n \"google-auth>=1.16.0\",\n \"google-auth-httplib2>=0.0.3\",\n \"google-api-core>=1.21.0,<2dev\",\n \"six>=1.13.0,<2dev\",\n \"uritemplate>=3.0.0,<4dev\",\n]\n\npackage_root = os.path.abspath(os.path.dirname(__file__))\n\nreadme_filename = os.path.join(package_root, \"README.md\")\nwith io.open(readme_filename, encoding=\"utf-8\") as readme_file:\n readme = readme_file.read()\n\nversion = \"1.12.0\"\n\nsetup(\n name=\"google-api-python-client\",\n version=version,\n description=\"Google API Client Library for Python\",\n long_description=readme,\n long_description_content_type='text/markdown',\n author=\"Google LLC\",\n author_email=\"[email protected]\",\n url=\"https://github.com/googleapis/google-api-python-client/\",\n install_requires=install_requires,\n python_requires=\">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*\",\n packages=packages,\n package_data={},\n license=\"Apache 2.0\",\n keywords=\"google api client\",\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Internet :: WWW/HTTP\",\n ],\n)\n", "path": "setup.py"}]}
1,344
120
gh_patches_debug_9665
rasdani/github-patches
git_diff
great-expectations__great_expectations-2958
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Use cleaner solution for non-truncating division in python 2 Prefer `from __future__ import division` to `1.*x/y` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `great_expectations/rule_based_profiler/profiler.py` Content: ``` 1 import uuid 2 from typing import Dict, List, Optional, Union 3 4 import great_expectations.exceptions as ge_exceptions 5 from great_expectations import DataContext 6 from great_expectations.core import ExpectationConfiguration, ExpectationSuite 7 from great_expectations.data_context.util import instantiate_class_from_config 8 from great_expectations.rule_based_profiler.domain_builder.domain_builder import ( 9 DomainBuilder, 10 ) 11 from great_expectations.rule_based_profiler.expectation_configuration_builder.expectation_configuration_builder import ( 12 ExpectationConfigurationBuilder, 13 ) 14 from great_expectations.rule_based_profiler.parameter_builder.parameter_builder import ( 15 ParameterBuilder, 16 ) 17 from great_expectations.rule_based_profiler.parameter_builder.parameter_container import ( 18 ParameterContainer, 19 build_parameter_container_for_variables, 20 ) 21 from great_expectations.rule_based_profiler.rule.rule import Rule 22 23 24 class Profiler: 25 """ 26 Profiler object serves to profile, or automatically evaluate a set of rules, upon a given 27 batch / multiple batches of data. 28 """ 29 30 def __init__( 31 self, 32 *, 33 profiler_config: Optional[Dict[str, Dict[str, Dict]]] = None, 34 data_context: Optional[DataContext] = None, 35 ): 36 """ 37 Create a new Profiler using configured rules. 38 For a rule or an item in a rule configuration, instantiates the following if 39 available: a domain builder, a parameter builder, and a configuration builder. 40 These will be used to define profiler computation patterns. 41 42 Args: 43 variables_configs: Variables from a profiler configuration 44 rules_configs: Rule configuration as a dictionary 45 data_context: DataContext object that defines a full runtime environment (data access, etc.) 46 """ 47 self._data_context = data_context 48 self._rules = [] 49 50 rules_configs: Dict[str, Dict] = profiler_config.get("rules", {}) 51 rule_name: str 52 rule_config: dict 53 54 for rule_name, rule_config in rules_configs.items(): 55 domain_builder_config: dict = rule_config.get("domain_builder") 56 57 if domain_builder_config is None: 58 raise ge_exceptions.ProfilerConfigurationError( 59 message=f'Invalid rule "{rule_name}": no domain_builder found.' 60 ) 61 62 domain_builder: DomainBuilder = instantiate_class_from_config( 63 config=domain_builder_config, 64 runtime_environment={"data_context": data_context}, 65 config_defaults={ 66 "module_name": "great_expectations.rule_based_profiler.domain_builder" 67 }, 68 ) 69 70 parameter_builders: List[ParameterBuilder] = [] 71 72 parameter_builder_configs: dict = rule_config.get("parameter_builders") 73 74 if parameter_builder_configs: 75 parameter_builder_config: dict 76 for parameter_builder_config in parameter_builder_configs: 77 parameter_builders.append( 78 instantiate_class_from_config( 79 config=parameter_builder_config, 80 runtime_environment={"data_context": data_context}, 81 config_defaults={ 82 "module_name": "great_expectations.rule_based_profiler.parameter_builder" 83 }, 84 ) 85 ) 86 87 expectation_configuration_builders: List[ 88 ExpectationConfigurationBuilder 89 ] = [] 90 91 expectation_configuration_builder_configs: dict = rule_config.get( 92 "expectation_configuration_builders" 93 ) 94 95 if expectation_configuration_builder_configs: 96 expectation_configuration_builder_config: dict 97 for ( 98 expectation_configuration_builder_config 99 ) in expectation_configuration_builder_configs: 100 expectation_configuration_builders.append( 101 instantiate_class_from_config( 102 config=expectation_configuration_builder_config, 103 runtime_environment={}, 104 config_defaults={ 105 "class_name": "DefaultExpectationConfigurationBuilder", 106 "module_name": "great_expectations.rule_based_profiler.expectation_configuration_builder", 107 }, 108 ) 109 ) 110 111 variables_configs: Dict[str, Dict] = profiler_config.get("variables", {}) 112 variables: Optional[ParameterContainer] = None 113 114 if variables_configs: 115 variables = build_parameter_container_for_variables( 116 variables_configs=variables_configs 117 ) 118 119 self._rules.append( 120 Rule( 121 name=rule_name, 122 domain_builder=domain_builder, 123 parameter_builders=parameter_builders, 124 expectation_configuration_builders=expectation_configuration_builders, 125 variables=variables, 126 ) 127 ) 128 129 def profile( 130 self, 131 *, 132 expectation_suite_name: Optional[str] = None, 133 ) -> ExpectationSuite: 134 """ 135 Args: 136 :param expectation_suite_name: A name for returned Expectation suite. 137 :return: Set of rule evaluation results in the form of an ExpectationSuite 138 """ 139 if expectation_suite_name is None: 140 expectation_suite_name = ( 141 f"tmp_suite_{self.__class__.__name__}_{str(uuid.uuid4())[:8]}" 142 ) 143 144 expectation_suite: ExpectationSuite = ExpectationSuite( 145 expectation_suite_name=expectation_suite_name 146 ) 147 148 rule: Rule 149 for rule in self._rules: 150 expectation_configurations: List[ExpectationConfiguration] = rule.generate() 151 expectation_configuration: ExpectationConfiguration 152 for expectation_configuration in expectation_configurations: 153 expectation_suite.add_expectation( 154 expectation_configuration=expectation_configuration 155 ) 156 157 return expectation_suite 158 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/great_expectations/rule_based_profiler/profiler.py b/great_expectations/rule_based_profiler/profiler.py --- a/great_expectations/rule_based_profiler/profiler.py +++ b/great_expectations/rule_based_profiler/profiler.py @@ -40,8 +40,7 @@ These will be used to define profiler computation patterns. Args: - variables_configs: Variables from a profiler configuration - rules_configs: Rule configuration as a dictionary + profiler_config: Variables and Rules configuration as a dictionary data_context: DataContext object that defines a full runtime environment (data access, etc.) """ self._data_context = data_context
{"golden_diff": "diff --git a/great_expectations/rule_based_profiler/profiler.py b/great_expectations/rule_based_profiler/profiler.py\n--- a/great_expectations/rule_based_profiler/profiler.py\n+++ b/great_expectations/rule_based_profiler/profiler.py\n@@ -40,8 +40,7 @@\n These will be used to define profiler computation patterns.\n \n Args:\n- variables_configs: Variables from a profiler configuration\n- rules_configs: Rule configuration as a dictionary\n+ profiler_config: Variables and Rules configuration as a dictionary\n data_context: DataContext object that defines a full runtime environment (data access, etc.)\n \"\"\"\n self._data_context = data_context\n", "issue": "Use cleaner solution for non-truncating division in python 2\nPrefer `from __future__ import division` to `1.*x/y`\n", "before_files": [{"content": "import uuid\nfrom typing import Dict, List, Optional, Union\n\nimport great_expectations.exceptions as ge_exceptions\nfrom great_expectations import DataContext\nfrom great_expectations.core import ExpectationConfiguration, ExpectationSuite\nfrom great_expectations.data_context.util import instantiate_class_from_config\nfrom great_expectations.rule_based_profiler.domain_builder.domain_builder import (\n DomainBuilder,\n)\nfrom great_expectations.rule_based_profiler.expectation_configuration_builder.expectation_configuration_builder import (\n ExpectationConfigurationBuilder,\n)\nfrom great_expectations.rule_based_profiler.parameter_builder.parameter_builder import (\n ParameterBuilder,\n)\nfrom great_expectations.rule_based_profiler.parameter_builder.parameter_container import (\n ParameterContainer,\n build_parameter_container_for_variables,\n)\nfrom great_expectations.rule_based_profiler.rule.rule import Rule\n\n\nclass Profiler:\n \"\"\"\n Profiler object serves to profile, or automatically evaluate a set of rules, upon a given\n batch / multiple batches of data.\n \"\"\"\n\n def __init__(\n self,\n *,\n profiler_config: Optional[Dict[str, Dict[str, Dict]]] = None,\n data_context: Optional[DataContext] = None,\n ):\n \"\"\"\n Create a new Profiler using configured rules.\n For a rule or an item in a rule configuration, instantiates the following if\n available: a domain builder, a parameter builder, and a configuration builder.\n These will be used to define profiler computation patterns.\n\n Args:\n variables_configs: Variables from a profiler configuration\n rules_configs: Rule configuration as a dictionary\n data_context: DataContext object that defines a full runtime environment (data access, etc.)\n \"\"\"\n self._data_context = data_context\n self._rules = []\n\n rules_configs: Dict[str, Dict] = profiler_config.get(\"rules\", {})\n rule_name: str\n rule_config: dict\n\n for rule_name, rule_config in rules_configs.items():\n domain_builder_config: dict = rule_config.get(\"domain_builder\")\n\n if domain_builder_config is None:\n raise ge_exceptions.ProfilerConfigurationError(\n message=f'Invalid rule \"{rule_name}\": no domain_builder found.'\n )\n\n domain_builder: DomainBuilder = instantiate_class_from_config(\n config=domain_builder_config,\n runtime_environment={\"data_context\": data_context},\n config_defaults={\n \"module_name\": \"great_expectations.rule_based_profiler.domain_builder\"\n },\n )\n\n parameter_builders: List[ParameterBuilder] = []\n\n parameter_builder_configs: dict = rule_config.get(\"parameter_builders\")\n\n if parameter_builder_configs:\n parameter_builder_config: dict\n for parameter_builder_config in parameter_builder_configs:\n parameter_builders.append(\n instantiate_class_from_config(\n config=parameter_builder_config,\n runtime_environment={\"data_context\": data_context},\n config_defaults={\n \"module_name\": \"great_expectations.rule_based_profiler.parameter_builder\"\n },\n )\n )\n\n expectation_configuration_builders: List[\n ExpectationConfigurationBuilder\n ] = []\n\n expectation_configuration_builder_configs: dict = rule_config.get(\n \"expectation_configuration_builders\"\n )\n\n if expectation_configuration_builder_configs:\n expectation_configuration_builder_config: dict\n for (\n expectation_configuration_builder_config\n ) in expectation_configuration_builder_configs:\n expectation_configuration_builders.append(\n instantiate_class_from_config(\n config=expectation_configuration_builder_config,\n runtime_environment={},\n config_defaults={\n \"class_name\": \"DefaultExpectationConfigurationBuilder\",\n \"module_name\": \"great_expectations.rule_based_profiler.expectation_configuration_builder\",\n },\n )\n )\n\n variables_configs: Dict[str, Dict] = profiler_config.get(\"variables\", {})\n variables: Optional[ParameterContainer] = None\n\n if variables_configs:\n variables = build_parameter_container_for_variables(\n variables_configs=variables_configs\n )\n\n self._rules.append(\n Rule(\n name=rule_name,\n domain_builder=domain_builder,\n parameter_builders=parameter_builders,\n expectation_configuration_builders=expectation_configuration_builders,\n variables=variables,\n )\n )\n\n def profile(\n self,\n *,\n expectation_suite_name: Optional[str] = None,\n ) -> ExpectationSuite:\n \"\"\"\n Args:\n :param expectation_suite_name: A name for returned Expectation suite.\n :return: Set of rule evaluation results in the form of an ExpectationSuite\n \"\"\"\n if expectation_suite_name is None:\n expectation_suite_name = (\n f\"tmp_suite_{self.__class__.__name__}_{str(uuid.uuid4())[:8]}\"\n )\n\n expectation_suite: ExpectationSuite = ExpectationSuite(\n expectation_suite_name=expectation_suite_name\n )\n\n rule: Rule\n for rule in self._rules:\n expectation_configurations: List[ExpectationConfiguration] = rule.generate()\n expectation_configuration: ExpectationConfiguration\n for expectation_configuration in expectation_configurations:\n expectation_suite.add_expectation(\n expectation_configuration=expectation_configuration\n )\n\n return expectation_suite\n", "path": "great_expectations/rule_based_profiler/profiler.py"}], "after_files": [{"content": "import uuid\nfrom typing import Dict, List, Optional, Union\n\nimport great_expectations.exceptions as ge_exceptions\nfrom great_expectations import DataContext\nfrom great_expectations.core import ExpectationConfiguration, ExpectationSuite\nfrom great_expectations.data_context.util import instantiate_class_from_config\nfrom great_expectations.rule_based_profiler.domain_builder.domain_builder import (\n DomainBuilder,\n)\nfrom great_expectations.rule_based_profiler.expectation_configuration_builder.expectation_configuration_builder import (\n ExpectationConfigurationBuilder,\n)\nfrom great_expectations.rule_based_profiler.parameter_builder.parameter_builder import (\n ParameterBuilder,\n)\nfrom great_expectations.rule_based_profiler.parameter_builder.parameter_container import (\n ParameterContainer,\n build_parameter_container_for_variables,\n)\nfrom great_expectations.rule_based_profiler.rule.rule import Rule\n\n\nclass Profiler:\n \"\"\"\n Profiler object serves to profile, or automatically evaluate a set of rules, upon a given\n batch / multiple batches of data.\n \"\"\"\n\n def __init__(\n self,\n *,\n profiler_config: Optional[Dict[str, Dict[str, Dict]]] = None,\n data_context: Optional[DataContext] = None,\n ):\n \"\"\"\n Create a new Profiler using configured rules.\n For a rule or an item in a rule configuration, instantiates the following if\n available: a domain builder, a parameter builder, and a configuration builder.\n These will be used to define profiler computation patterns.\n\n Args:\n profiler_config: Variables and Rules configuration as a dictionary\n data_context: DataContext object that defines a full runtime environment (data access, etc.)\n \"\"\"\n self._data_context = data_context\n self._rules = []\n\n rules_configs: Dict[str, Dict] = profiler_config.get(\"rules\", {})\n rule_name: str\n rule_config: dict\n\n for rule_name, rule_config in rules_configs.items():\n domain_builder_config: dict = rule_config.get(\"domain_builder\")\n\n if domain_builder_config is None:\n raise ge_exceptions.ProfilerConfigurationError(\n message=f'Invalid rule \"{rule_name}\": no domain_builder found.'\n )\n\n domain_builder: DomainBuilder = instantiate_class_from_config(\n config=domain_builder_config,\n runtime_environment={\"data_context\": data_context},\n config_defaults={\n \"module_name\": \"great_expectations.rule_based_profiler.domain_builder\"\n },\n )\n\n parameter_builders: List[ParameterBuilder] = []\n\n parameter_builder_configs: dict = rule_config.get(\"parameter_builders\")\n\n if parameter_builder_configs:\n parameter_builder_config: dict\n for parameter_builder_config in parameter_builder_configs:\n parameter_builders.append(\n instantiate_class_from_config(\n config=parameter_builder_config,\n runtime_environment={\"data_context\": data_context},\n config_defaults={\n \"module_name\": \"great_expectations.rule_based_profiler.parameter_builder\"\n },\n )\n )\n\n expectation_configuration_builders: List[\n ExpectationConfigurationBuilder\n ] = []\n\n expectation_configuration_builder_configs: dict = rule_config.get(\n \"expectation_configuration_builders\"\n )\n\n if expectation_configuration_builder_configs:\n expectation_configuration_builder_config: dict\n for (\n expectation_configuration_builder_config\n ) in expectation_configuration_builder_configs:\n expectation_configuration_builders.append(\n instantiate_class_from_config(\n config=expectation_configuration_builder_config,\n runtime_environment={},\n config_defaults={\n \"class_name\": \"DefaultExpectationConfigurationBuilder\",\n \"module_name\": \"great_expectations.rule_based_profiler.expectation_configuration_builder\",\n },\n )\n )\n\n variables_configs: Dict[str, Dict] = profiler_config.get(\"variables\", {})\n variables: Optional[ParameterContainer] = None\n\n if variables_configs:\n variables = build_parameter_container_for_variables(\n variables_configs=variables_configs\n )\n\n self._rules.append(\n Rule(\n name=rule_name,\n domain_builder=domain_builder,\n parameter_builders=parameter_builders,\n expectation_configuration_builders=expectation_configuration_builders,\n variables=variables,\n )\n )\n\n def profile(\n self,\n *,\n expectation_suite_name: Optional[str] = None,\n ) -> ExpectationSuite:\n \"\"\"\n Args:\n :param expectation_suite_name: A name for returned Expectation suite.\n :return: Set of rule evaluation results in the form of an ExpectationSuite\n \"\"\"\n if expectation_suite_name is None:\n expectation_suite_name = (\n f\"tmp_suite_{self.__class__.__name__}_{str(uuid.uuid4())[:8]}\"\n )\n\n expectation_suite: ExpectationSuite = ExpectationSuite(\n expectation_suite_name=expectation_suite_name\n )\n\n rule: Rule\n for rule in self._rules:\n expectation_configurations: List[ExpectationConfiguration] = rule.generate()\n expectation_configuration: ExpectationConfiguration\n for expectation_configuration in expectation_configurations:\n expectation_suite.add_expectation(\n expectation_configuration=expectation_configuration\n )\n\n return expectation_suite\n", "path": "great_expectations/rule_based_profiler/profiler.py"}]}
1,720
151
gh_patches_debug_567
rasdani/github-patches
git_diff
pex-tool__pex-891
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Release 2.1.3 On the docket: + [x] Error eagerly if an interpreter binary doesn't exist #886 + [x] The pip-powered resolve in pex 2 will re-tokenize --find-links pages on each transitive requirement #887 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pex/version.py` Content: ``` 1 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). 2 # Licensed under the Apache License, Version 2.0 (see LICENSE). 3 4 __version__ = '2.1.2' 5 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pex/version.py b/pex/version.py --- a/pex/version.py +++ b/pex/version.py @@ -1,4 +1,4 @@ # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). -__version__ = '2.1.2' +__version__ = '2.1.3'
{"golden_diff": "diff --git a/pex/version.py b/pex/version.py\n--- a/pex/version.py\n+++ b/pex/version.py\n@@ -1,4 +1,4 @@\n # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n # Licensed under the Apache License, Version 2.0 (see LICENSE).\n \n-__version__ = '2.1.2'\n+__version__ = '2.1.3'\n", "issue": "Release 2.1.3\nOn the docket:\r\n+ [x] Error eagerly if an interpreter binary doesn't exist #886 \r\n+ [x] The pip-powered resolve in pex 2 will re-tokenize --find-links pages on each transitive requirement #887 \n", "before_files": [{"content": "# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n__version__ = '2.1.2'\n", "path": "pex/version.py"}], "after_files": [{"content": "# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n__version__ = '2.1.3'\n", "path": "pex/version.py"}]}
368
94
gh_patches_debug_24149
rasdani/github-patches
git_diff
lightly-ai__lightly-482
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- when pip version older than newest version, it calls API on every command rather than caching the information When I use an older pip version, I see multiple lines of output like this when I run `lightly-magic` ``` ...Python/3.8/lib/python/site-packages/lightly/api/version_checking.py:57: Warning: You are using lightly version 1.1.17. There is a newer version of the package available. For compatability reasons, please upgrade your current version: pip install lightly==1.1.18 warnings.warn(Warning(warning)) ``` Also tracking the connections it makes, it calls the API for **every** images I want to upload. So the pip does not cache the information that it is an outdated version. This is no bueno --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `lightly/__init__.py` Content: ``` 1 """Lightly is a computer vision framework for self-supervised learning. 2 3 With Lightly you can train deep learning models using 4 self-supervision. This means, that you don't require 5 any labels to train a model. Lightly has been built 6 to help you understand and work with large unlabeled datasets. 7 It is built on top of PyTorch and therefore fully compatible 8 with other frameworks such as Fast.ai. 9 10 The framework is structured into the following modules: 11 12 - **api**: 13 14 The lightly.api module handles communication with the Lightly web-app. 15 16 - **cli**: 17 18 The lightly.cli module provides a command-line interface for training 19 self-supervised models and embedding images. Furthermore, the command-line 20 tool can be used to upload and download images from/to the Lightly web-app. 21 22 - **core**: 23 24 The lightly.core module offers one-liners for simple self-supervised learning. 25 26 - **data**: 27 28 The lightly.data module provides a dataset wrapper and collate functions. The 29 collate functions are in charge of the data augmentations which are crucial for 30 self-supervised learning. 31 32 - **embedding**: 33 34 The lightly.embedding module combines the self-supervised models with a dataloader, 35 optimizer, and loss function to provide a simple pytorch-lightning trainable. 36 37 - **loss**: 38 39 The lightly.loss module contains implementations of popular self-supervised training 40 loss functions. 41 42 - **models**: 43 44 The lightly.models module holds the implementation of the ResNet as well as self- 45 supervised methods. Currently implements: 46 47 - SimCLR 48 49 - MoCo 50 51 - SimSiam 52 53 - Barlow Twins 54 55 - BYOL 56 57 - NNCLR 58 59 - **transforms**: 60 61 The lightly.transforms module implements custom data transforms. Currently implements: 62 63 - Gaussian Blur 64 65 - Random Rotation 66 67 - Random Solarization 68 69 - **utils**: 70 71 The lightly.utils package provides global utility methods. 72 The io module contains utility to save and load embeddings in a format which is 73 understood by the Lightly library. 74 75 """ 76 77 # Copyright (c) 2020. Lightly AG and its affiliates. 78 # All Rights Reserved 79 80 __name__ = 'lightly' 81 __version__ = '1.1.18' 82 83 84 try: 85 # See (https://github.com/PyTorchLightning/pytorch-lightning) 86 # This variable is injected in the __builtins__ by the build 87 # process. It used to enable importing subpackages of skimage when 88 # the binaries are not built 89 __LIGHTLY_SETUP__ 90 except NameError: 91 __LIGHTLY_SETUP__ = False 92 93 94 if __LIGHTLY_SETUP__: 95 # setting up lightly 96 msg = f'Partial import of {__name__}=={__version__} during build process.' 97 print(msg) 98 else: 99 # see if prefetch_generator is available 100 try: 101 import prefetch_generator 102 except ImportError: 103 _prefetch_generator_available = False 104 else: 105 _prefetch_generator_available = True 106 107 def _is_prefetch_generator_available(): 108 return _prefetch_generator_available 109 110 from lightly.core import * 111 from lightly import active_learning 112 from lightly import api 113 from lightly import data 114 from lightly import embedding 115 from lightly import loss 116 from lightly import models 117 from lightly import openapi_generated 118 from lightly import transforms 119 from lightly import utils 120 121 122 # check for latest version 123 from lightly.api.version_checking import get_latest_version 124 from lightly.api.version_checking import version_compare 125 from lightly.api.version_checking import pretty_print_latest_version 126 127 latest_version = get_latest_version(__version__) 128 if latest_version is not None: 129 if version_compare(__version__, latest_version) < 0: 130 # local version is behind latest version 131 pretty_print_latest_version(latest_version) 132 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/lightly/__init__.py b/lightly/__init__.py --- a/lightly/__init__.py +++ b/lightly/__init__.py @@ -80,6 +80,7 @@ __name__ = 'lightly' __version__ = '1.1.18' +from multiprocessing import current_process try: # See (https://github.com/PyTorchLightning/pytorch-lightning) @@ -118,14 +119,15 @@ from lightly import transforms from lightly import utils + if current_process().name == 'MainProcess': + # check for latest version + from lightly.api.version_checking import get_latest_version + from lightly.api.version_checking import version_compare + from lightly.api.version_checking import pretty_print_latest_version - # check for latest version - from lightly.api.version_checking import get_latest_version - from lightly.api.version_checking import version_compare - from lightly.api.version_checking import pretty_print_latest_version + latest_version = get_latest_version(__version__) + if latest_version is not None: + if version_compare(__version__, latest_version) < 0: + # local version is behind latest version + pretty_print_latest_version(latest_version) - latest_version = get_latest_version(__version__) - if latest_version is not None: - if version_compare(__version__, latest_version) < 0: - # local version is behind latest version - pretty_print_latest_version(latest_version)
{"golden_diff": "diff --git a/lightly/__init__.py b/lightly/__init__.py\n--- a/lightly/__init__.py\n+++ b/lightly/__init__.py\n@@ -80,6 +80,7 @@\n __name__ = 'lightly'\n __version__ = '1.1.18'\n \n+from multiprocessing import current_process\n \n try:\n # See (https://github.com/PyTorchLightning/pytorch-lightning)\n@@ -118,14 +119,15 @@\n from lightly import transforms\n from lightly import utils\n \n+ if current_process().name == 'MainProcess':\n+ # check for latest version\n+ from lightly.api.version_checking import get_latest_version\n+ from lightly.api.version_checking import version_compare\n+ from lightly.api.version_checking import pretty_print_latest_version\n \n- # check for latest version\n- from lightly.api.version_checking import get_latest_version\n- from lightly.api.version_checking import version_compare\n- from lightly.api.version_checking import pretty_print_latest_version\n+ latest_version = get_latest_version(__version__)\n+ if latest_version is not None:\n+ if version_compare(__version__, latest_version) < 0:\n+ # local version is behind latest version\n+ pretty_print_latest_version(latest_version)\n \n- latest_version = get_latest_version(__version__)\n- if latest_version is not None:\n- if version_compare(__version__, latest_version) < 0:\n- # local version is behind latest version\n- pretty_print_latest_version(latest_version)\n", "issue": "when pip version older than newest version, it calls API on every command rather than caching the information\nWhen I use an older pip version, I see multiple lines of output like this when I run `lightly-magic`\r\n```\r\n...Python/3.8/lib/python/site-packages/lightly/api/version_checking.py:57: Warning: You are using lightly version 1.1.17. There is a newer version of the package available. For compatability reasons, please upgrade your current version: pip install lightly==1.1.18\r\n warnings.warn(Warning(warning))\r\n```\r\n\r\nAlso tracking the connections it makes, it calls the API for **every** images I want to upload. So the pip does not cache the information that it is an outdated version. This is no bueno\r\n \r\n \n", "before_files": [{"content": "\"\"\"Lightly is a computer vision framework for self-supervised learning.\n\nWith Lightly you can train deep learning models using\nself-supervision. This means, that you don't require\nany labels to train a model. Lightly has been built\nto help you understand and work with large unlabeled datasets.\nIt is built on top of PyTorch and therefore fully compatible \nwith other frameworks such as Fast.ai.\n\nThe framework is structured into the following modules:\n\n- **api**: \n\n The lightly.api module handles communication with the Lightly web-app.\n\n- **cli**:\n\n The lightly.cli module provides a command-line interface for training \n self-supervised models and embedding images. Furthermore, the command-line\n tool can be used to upload and download images from/to the Lightly web-app.\n\n- **core**:\n\n The lightly.core module offers one-liners for simple self-supervised learning.\n\n- **data**:\n\n The lightly.data module provides a dataset wrapper and collate functions. The\n collate functions are in charge of the data augmentations which are crucial for\n self-supervised learning.\n\n- **embedding**:\n\n The lightly.embedding module combines the self-supervised models with a dataloader,\n optimizer, and loss function to provide a simple pytorch-lightning trainable.\n\n- **loss**:\n\n The lightly.loss module contains implementations of popular self-supervised training\n loss functions.\n\n- **models**:\n\n The lightly.models module holds the implementation of the ResNet as well as self-\n supervised methods. Currently implements:\n\n - SimCLR\n\n - MoCo\n\n - SimSiam\n\n - Barlow Twins\n\n - BYOL\n\n - NNCLR\n\n- **transforms**:\n\n The lightly.transforms module implements custom data transforms. Currently implements:\n\n - Gaussian Blur\n\n - Random Rotation\n\n - Random Solarization\n\n- **utils**:\n\n The lightly.utils package provides global utility methods.\n The io module contains utility to save and load embeddings in a format which is\n understood by the Lightly library.\n\n\"\"\"\n\n# Copyright (c) 2020. Lightly AG and its affiliates.\n# All Rights Reserved\n\n__name__ = 'lightly'\n__version__ = '1.1.18'\n\n\ntry:\n # See (https://github.com/PyTorchLightning/pytorch-lightning)\n # This variable is injected in the __builtins__ by the build\n # process. It used to enable importing subpackages of skimage when\n # the binaries are not built\n __LIGHTLY_SETUP__\nexcept NameError:\n __LIGHTLY_SETUP__ = False\n\n\nif __LIGHTLY_SETUP__:\n # setting up lightly\n msg = f'Partial import of {__name__}=={__version__} during build process.' \n print(msg)\nelse:\n # see if prefetch_generator is available\n try:\n import prefetch_generator\n except ImportError:\n _prefetch_generator_available = False\n else:\n _prefetch_generator_available = True\n\n def _is_prefetch_generator_available():\n return _prefetch_generator_available\n\n from lightly.core import *\n from lightly import active_learning\n from lightly import api\n from lightly import data\n from lightly import embedding\n from lightly import loss\n from lightly import models\n from lightly import openapi_generated\n from lightly import transforms\n from lightly import utils\n\n\n # check for latest version\n from lightly.api.version_checking import get_latest_version\n from lightly.api.version_checking import version_compare\n from lightly.api.version_checking import pretty_print_latest_version\n\n latest_version = get_latest_version(__version__)\n if latest_version is not None:\n if version_compare(__version__, latest_version) < 0:\n # local version is behind latest version\n pretty_print_latest_version(latest_version)\n", "path": "lightly/__init__.py"}], "after_files": [{"content": "\"\"\"Lightly is a computer vision framework for self-supervised learning.\n\nWith Lightly you can train deep learning models using\nself-supervision. This means, that you don't require\nany labels to train a model. Lightly has been built\nto help you understand and work with large unlabeled datasets.\nIt is built on top of PyTorch and therefore fully compatible \nwith other frameworks such as Fast.ai.\n\nThe framework is structured into the following modules:\n\n- **api**: \n\n The lightly.api module handles communication with the Lightly web-app.\n\n- **cli**:\n\n The lightly.cli module provides a command-line interface for training \n self-supervised models and embedding images. Furthermore, the command-line\n tool can be used to upload and download images from/to the Lightly web-app.\n\n- **core**:\n\n The lightly.core module offers one-liners for simple self-supervised learning.\n\n- **data**:\n\n The lightly.data module provides a dataset wrapper and collate functions. The\n collate functions are in charge of the data augmentations which are crucial for\n self-supervised learning.\n\n- **embedding**:\n\n The lightly.embedding module combines the self-supervised models with a dataloader,\n optimizer, and loss function to provide a simple pytorch-lightning trainable.\n\n- **loss**:\n\n The lightly.loss module contains implementations of popular self-supervised training\n loss functions.\n\n- **models**:\n\n The lightly.models module holds the implementation of the ResNet as well as self-\n supervised methods. Currently implements:\n\n - SimCLR\n\n - MoCo\n\n - SimSiam\n\n - Barlow Twins\n\n - BYOL\n\n - NNCLR\n\n- **transforms**:\n\n The lightly.transforms module implements custom data transforms. Currently implements:\n\n - Gaussian Blur\n\n - Random Rotation\n\n - Random Solarization\n\n- **utils**:\n\n The lightly.utils package provides global utility methods.\n The io module contains utility to save and load embeddings in a format which is\n understood by the Lightly library.\n\n\"\"\"\n\n# Copyright (c) 2020. Lightly AG and its affiliates.\n# All Rights Reserved\n\n__name__ = 'lightly'\n__version__ = '1.1.18'\n\nfrom multiprocessing import current_process\n\ntry:\n # See (https://github.com/PyTorchLightning/pytorch-lightning)\n # This variable is injected in the __builtins__ by the build\n # process. It used to enable importing subpackages of skimage when\n # the binaries are not built\n __LIGHTLY_SETUP__\nexcept NameError:\n __LIGHTLY_SETUP__ = False\n\n\nif __LIGHTLY_SETUP__:\n # setting up lightly\n msg = f'Partial import of {__name__}=={__version__} during build process.' \n print(msg)\nelse:\n # see if prefetch_generator is available\n try:\n import prefetch_generator\n except ImportError:\n _prefetch_generator_available = False\n else:\n _prefetch_generator_available = True\n\n def _is_prefetch_generator_available():\n return _prefetch_generator_available\n\n from lightly.core import *\n from lightly import active_learning\n from lightly import api\n from lightly import data\n from lightly import embedding\n from lightly import loss\n from lightly import models\n from lightly import openapi_generated\n from lightly import transforms\n from lightly import utils\n\n if current_process().name == 'MainProcess':\n # check for latest version\n from lightly.api.version_checking import get_latest_version\n from lightly.api.version_checking import version_compare\n from lightly.api.version_checking import pretty_print_latest_version\n\n latest_version = get_latest_version(__version__)\n if latest_version is not None:\n if version_compare(__version__, latest_version) < 0:\n # local version is behind latest version\n pretty_print_latest_version(latest_version)\n\n", "path": "lightly/__init__.py"}]}
1,562
341
gh_patches_debug_25623
rasdani/github-patches
git_diff
StackStorm__st2-5468
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- An exception is raised when calling MockDatastoreService.set_value() with a ttl ## SUMMARY When using `MockDatastoreService.set_value()` for unit testing (e.g. via `BaseActionTestCase`), a `ValueError` exception will be raised if `ttl` argument is specified. ### STACKSTORM VERSION `st2 3.1.0, on Python 3.6.8` ### OS, environment, install method Custom install, but not relevant to this case, see below. ## Steps to reproduce the problem See [code](https://github.com/StackStorm/st2/blob/6d1809a4bb577e117baa00f249757284db9c6e76/st2tests/st2tests/mocks/datastore.py#L108) for `MockDatastoreService.set_value()`. If `ttl` argument is specified, `ValueError` will explicitly be raised. ```python class MockDatastoreService(BaseDatastoreService): # ... def set_value(self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False): """ Store a value in a dictionary which is local to this class. """ if ttl: raise ValueError('MockDatastoreService.set_value doesn\'t support "ttl" argument') # ... ``` ## Expected Results Both `action_service.set_value()` and `sensor_service.set_value()` support `ttl` argument. Although I understand that this argument cannot be honored in a mock situation, `MockDatastoreService` should be consistent with the behavior of the class it is mocking - perhaps fire a warning instead of an Exception? ## Actual Results An exception is returned while running tests: ```python ValueError: MockDatastoreService.set_value doesn't support "ttl" argument ``` It is not possible to test actions or sensors that use `xxx.set_value()` with a `ttl` argument. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `st2tests/st2tests/mocks/datastore.py` Content: ``` 1 # Copyright 2020 The StackStorm Authors. 2 # Copyright 2019 Extreme Networks, Inc. 3 # 4 # Licensed under the Apache License, Version 2.0 (the "License"); 5 # you may not use this file except in compliance with the License. 6 # You may obtain a copy of the License at 7 # 8 # http://www.apache.org/licenses/LICENSE-2.0 9 # 10 # Unless required by applicable law or agreed to in writing, software 11 # distributed under the License is distributed on an "AS IS" BASIS, 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 16 """ 17 Mock classes for use in pack testing. 18 """ 19 20 from __future__ import absolute_import 21 from st2common.constants.keyvalue import SYSTEM_SCOPE 22 from st2common.services.datastore import BaseDatastoreService 23 from st2client.models.keyvalue import KeyValuePair 24 25 __all__ = ["MockDatastoreService"] 26 27 28 class MockDatastoreService(BaseDatastoreService): 29 """ 30 Mock DatastoreService for use in testing. 31 """ 32 33 def __init__(self, logger, pack_name, class_name, api_username=None): 34 self._pack_name = pack_name 35 self._class_name = class_name 36 self._username = api_username or "admin" 37 38 # Holds mock KeyValuePair objects 39 # Key is a KeyValuePair name and value is the KeyValuePair object 40 self._datastore_items = {} 41 42 ################################## 43 # General methods 44 ################################## 45 46 def get_user_info(self): 47 """ 48 Retrieve information about the current user which is authenticated against StackStorm and 49 used to perform other datastore operations via the API. 50 51 :rtype: ``dict`` 52 """ 53 result = { 54 "username": self._username, 55 "rbac": {"is_admin": True, "enabled": True, "roles": ["admin"]}, 56 "authentication": {"method": "authentication token", "location": "header"}, 57 } 58 59 return result 60 61 ################################## 62 # Methods for datastore management 63 ################################## 64 65 def list_values(self, local=True, prefix=None): 66 """ 67 Return a list of all values stored in a dictionary which is local to this class. 68 """ 69 key_prefix = self._get_full_key_prefix(local=local, prefix=prefix) 70 71 if not key_prefix: 72 return list(self._datastore_items.values()) 73 74 result = [] 75 for name, kvp in self._datastore_items.items(): 76 if name.startswith(key_prefix): 77 result.append(kvp) 78 79 return result 80 81 def get_value(self, name, local=True, scope=SYSTEM_SCOPE, decrypt=False): 82 """ 83 Return a particular value stored in a dictionary which is local to this class. 84 """ 85 name = self._get_full_key_name(name=name, local=local) 86 87 if name not in self._datastore_items: 88 return None 89 90 kvp = self._datastore_items[name] 91 return kvp.value 92 93 def set_value( 94 self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False 95 ): 96 """ 97 Store a value in a dictionary which is local to this class. 98 """ 99 if ttl: 100 raise ValueError( 101 'MockDatastoreService.set_value doesn\'t support "ttl" argument' 102 ) 103 104 name = self._get_full_key_name(name=name, local=local) 105 106 instance = KeyValuePair() 107 instance.id = name 108 instance.name = name 109 instance.value = value 110 111 self._datastore_items[name] = instance 112 return True 113 114 def delete_value(self, name, local=True, scope=SYSTEM_SCOPE): 115 """ 116 Delete a value from a dictionary which is local to this class. 117 """ 118 name = self._get_full_key_name(name=name, local=local) 119 120 if name not in self._datastore_items: 121 return False 122 123 del self._datastore_items[name] 124 return True 125 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/st2tests/st2tests/mocks/datastore.py b/st2tests/st2tests/mocks/datastore.py --- a/st2tests/st2tests/mocks/datastore.py +++ b/st2tests/st2tests/mocks/datastore.py @@ -34,6 +34,7 @@ self._pack_name = pack_name self._class_name = class_name self._username = api_username or "admin" + self._logger = logger # Holds mock KeyValuePair objects # Key is a KeyValuePair name and value is the KeyValuePair object @@ -96,10 +97,6 @@ """ Store a value in a dictionary which is local to this class. """ - if ttl: - raise ValueError( - 'MockDatastoreService.set_value doesn\'t support "ttl" argument' - ) name = self._get_full_key_name(name=name, local=local) @@ -107,6 +104,11 @@ instance.id = name instance.name = name instance.value = value + if ttl: + self._logger.warning( + "MockDatastoreService is not able to expire keys based on ttl." + ) + instance.ttl = ttl self._datastore_items[name] = instance return True
{"golden_diff": "diff --git a/st2tests/st2tests/mocks/datastore.py b/st2tests/st2tests/mocks/datastore.py\n--- a/st2tests/st2tests/mocks/datastore.py\n+++ b/st2tests/st2tests/mocks/datastore.py\n@@ -34,6 +34,7 @@\n self._pack_name = pack_name\n self._class_name = class_name\n self._username = api_username or \"admin\"\n+ self._logger = logger\n \n # Holds mock KeyValuePair objects\n # Key is a KeyValuePair name and value is the KeyValuePair object\n@@ -96,10 +97,6 @@\n \"\"\"\n Store a value in a dictionary which is local to this class.\n \"\"\"\n- if ttl:\n- raise ValueError(\n- 'MockDatastoreService.set_value doesn\\'t support \"ttl\" argument'\n- )\n \n name = self._get_full_key_name(name=name, local=local)\n \n@@ -107,6 +104,11 @@\n instance.id = name\n instance.name = name\n instance.value = value\n+ if ttl:\n+ self._logger.warning(\n+ \"MockDatastoreService is not able to expire keys based on ttl.\"\n+ )\n+ instance.ttl = ttl\n \n self._datastore_items[name] = instance\n return True\n", "issue": "An exception is raised when calling MockDatastoreService.set_value() with a ttl\n## SUMMARY\r\n\r\nWhen using `MockDatastoreService.set_value()` for unit testing (e.g. via `BaseActionTestCase`), a `ValueError` exception will be raised if `ttl` argument is specified.\r\n\r\n\r\n### STACKSTORM VERSION\r\n\r\n`st2 3.1.0, on Python 3.6.8`\r\n\r\n### OS, environment, install method\r\n\r\nCustom install, but not relevant to this case, see below.\r\n\r\n## Steps to reproduce the problem\r\n\r\nSee [code](https://github.com/StackStorm/st2/blob/6d1809a4bb577e117baa00f249757284db9c6e76/st2tests/st2tests/mocks/datastore.py#L108) for `MockDatastoreService.set_value()`. If `ttl` argument is specified, `ValueError` will explicitly be raised.\r\n\r\n```python\r\nclass MockDatastoreService(BaseDatastoreService):\r\n # ...\r\n def set_value(self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False):\r\n \"\"\"\r\n Store a value in a dictionary which is local to this class.\r\n \"\"\"\r\n if ttl:\r\n raise ValueError('MockDatastoreService.set_value doesn\\'t support \"ttl\" argument')\r\n # ...\r\n```\r\n\r\n\r\n## Expected Results\r\n\r\nBoth `action_service.set_value()` and `sensor_service.set_value()` support `ttl` argument. Although I understand that this argument cannot be honored in a mock situation, `MockDatastoreService` should be consistent with the behavior of the class it is mocking - perhaps fire a warning instead of an Exception?\r\n\r\n## Actual Results\r\n\r\nAn exception is returned while running tests:\r\n```python\r\nValueError: MockDatastoreService.set_value doesn't support \"ttl\" argument\r\n```\r\nIt is not possible to test actions or sensors that use `xxx.set_value()` with a `ttl` argument.\r\n\r\n\n", "before_files": [{"content": "# Copyright 2020 The StackStorm Authors.\n# Copyright 2019 Extreme Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nMock classes for use in pack testing.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom st2common.constants.keyvalue import SYSTEM_SCOPE\nfrom st2common.services.datastore import BaseDatastoreService\nfrom st2client.models.keyvalue import KeyValuePair\n\n__all__ = [\"MockDatastoreService\"]\n\n\nclass MockDatastoreService(BaseDatastoreService):\n \"\"\"\n Mock DatastoreService for use in testing.\n \"\"\"\n\n def __init__(self, logger, pack_name, class_name, api_username=None):\n self._pack_name = pack_name\n self._class_name = class_name\n self._username = api_username or \"admin\"\n\n # Holds mock KeyValuePair objects\n # Key is a KeyValuePair name and value is the KeyValuePair object\n self._datastore_items = {}\n\n ##################################\n # General methods\n ##################################\n\n def get_user_info(self):\n \"\"\"\n Retrieve information about the current user which is authenticated against StackStorm and\n used to perform other datastore operations via the API.\n\n :rtype: ``dict``\n \"\"\"\n result = {\n \"username\": self._username,\n \"rbac\": {\"is_admin\": True, \"enabled\": True, \"roles\": [\"admin\"]},\n \"authentication\": {\"method\": \"authentication token\", \"location\": \"header\"},\n }\n\n return result\n\n ##################################\n # Methods for datastore management\n ##################################\n\n def list_values(self, local=True, prefix=None):\n \"\"\"\n Return a list of all values stored in a dictionary which is local to this class.\n \"\"\"\n key_prefix = self._get_full_key_prefix(local=local, prefix=prefix)\n\n if not key_prefix:\n return list(self._datastore_items.values())\n\n result = []\n for name, kvp in self._datastore_items.items():\n if name.startswith(key_prefix):\n result.append(kvp)\n\n return result\n\n def get_value(self, name, local=True, scope=SYSTEM_SCOPE, decrypt=False):\n \"\"\"\n Return a particular value stored in a dictionary which is local to this class.\n \"\"\"\n name = self._get_full_key_name(name=name, local=local)\n\n if name not in self._datastore_items:\n return None\n\n kvp = self._datastore_items[name]\n return kvp.value\n\n def set_value(\n self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False\n ):\n \"\"\"\n Store a value in a dictionary which is local to this class.\n \"\"\"\n if ttl:\n raise ValueError(\n 'MockDatastoreService.set_value doesn\\'t support \"ttl\" argument'\n )\n\n name = self._get_full_key_name(name=name, local=local)\n\n instance = KeyValuePair()\n instance.id = name\n instance.name = name\n instance.value = value\n\n self._datastore_items[name] = instance\n return True\n\n def delete_value(self, name, local=True, scope=SYSTEM_SCOPE):\n \"\"\"\n Delete a value from a dictionary which is local to this class.\n \"\"\"\n name = self._get_full_key_name(name=name, local=local)\n\n if name not in self._datastore_items:\n return False\n\n del self._datastore_items[name]\n return True\n", "path": "st2tests/st2tests/mocks/datastore.py"}], "after_files": [{"content": "# Copyright 2020 The StackStorm Authors.\n# Copyright 2019 Extreme Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nMock classes for use in pack testing.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom st2common.constants.keyvalue import SYSTEM_SCOPE\nfrom st2common.services.datastore import BaseDatastoreService\nfrom st2client.models.keyvalue import KeyValuePair\n\n__all__ = [\"MockDatastoreService\"]\n\n\nclass MockDatastoreService(BaseDatastoreService):\n \"\"\"\n Mock DatastoreService for use in testing.\n \"\"\"\n\n def __init__(self, logger, pack_name, class_name, api_username=None):\n self._pack_name = pack_name\n self._class_name = class_name\n self._username = api_username or \"admin\"\n self._logger = logger\n\n # Holds mock KeyValuePair objects\n # Key is a KeyValuePair name and value is the KeyValuePair object\n self._datastore_items = {}\n\n ##################################\n # General methods\n ##################################\n\n def get_user_info(self):\n \"\"\"\n Retrieve information about the current user which is authenticated against StackStorm and\n used to perform other datastore operations via the API.\n\n :rtype: ``dict``\n \"\"\"\n result = {\n \"username\": self._username,\n \"rbac\": {\"is_admin\": True, \"enabled\": True, \"roles\": [\"admin\"]},\n \"authentication\": {\"method\": \"authentication token\", \"location\": \"header\"},\n }\n\n return result\n\n ##################################\n # Methods for datastore management\n ##################################\n\n def list_values(self, local=True, prefix=None):\n \"\"\"\n Return a list of all values stored in a dictionary which is local to this class.\n \"\"\"\n key_prefix = self._get_full_key_prefix(local=local, prefix=prefix)\n\n if not key_prefix:\n return list(self._datastore_items.values())\n\n result = []\n for name, kvp in self._datastore_items.items():\n if name.startswith(key_prefix):\n result.append(kvp)\n\n return result\n\n def get_value(self, name, local=True, scope=SYSTEM_SCOPE, decrypt=False):\n \"\"\"\n Return a particular value stored in a dictionary which is local to this class.\n \"\"\"\n name = self._get_full_key_name(name=name, local=local)\n\n if name not in self._datastore_items:\n return None\n\n kvp = self._datastore_items[name]\n return kvp.value\n\n def set_value(\n self, name, value, ttl=None, local=True, scope=SYSTEM_SCOPE, encrypt=False\n ):\n \"\"\"\n Store a value in a dictionary which is local to this class.\n \"\"\"\n\n name = self._get_full_key_name(name=name, local=local)\n\n instance = KeyValuePair()\n instance.id = name\n instance.name = name\n instance.value = value\n if ttl:\n self._logger.warning(\n \"MockDatastoreService is not able to expire keys based on ttl.\"\n )\n instance.ttl = ttl\n\n self._datastore_items[name] = instance\n return True\n\n def delete_value(self, name, local=True, scope=SYSTEM_SCOPE):\n \"\"\"\n Delete a value from a dictionary which is local to this class.\n \"\"\"\n name = self._get_full_key_name(name=name, local=local)\n\n if name not in self._datastore_items:\n return False\n\n del self._datastore_items[name]\n return True\n", "path": "st2tests/st2tests/mocks/datastore.py"}]}
1,809
294
gh_patches_debug_30371
rasdani/github-patches
git_diff
Flexget__Flexget-2222
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Cannot use variables with integer-only values ### Expected behaviour: Variables should be able to handle integer-only values. ### Actual behaviour: Configuration parsing error (when using ``'{? deluge.port ?}'``): ``Got `50586`, expected: integer`` Configuration parsing error (when using ``{? deluge.port ?}``): ``` while parsing a flow mapping in "<unicode string>", line 16, column 13: port: {? deluge.port ?} ^ expected ',' or '}', but got '?' in "<unicode string>", line 16, column 28: port: {? deluge.port ?} ^ ``` ### Steps to reproduce: - Step 1: Try to use below config. #### Config: ``` from_deluge: host: '{? deluge.host ?}' port: '{? deluge.port ?}' ``` #### Log: See above. ### Additional information: - Flexget Version: 2.10.24 - Python Version: 2.7.9 - Installation method: pip - OS and version: macOS El Capitan 10.11.6 - Link to crash log: n/a --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `flexget/plugins/modify/variables.py` Content: ``` 1 from __future__ import unicode_literals, division, absolute_import 2 from builtins import * # noqa pylint: disable=unused-import, redefined-builtin 3 4 import codecs 5 import logging 6 import os 7 from datetime import datetime 8 9 import yaml 10 11 from jinja2 import Environment, TemplateError 12 13 from sqlalchemy import Column 14 from sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer 15 16 from flexget import db_schema 17 from flexget.config_schema import register_config_key 18 from flexget.event import event 19 from flexget.manager import Session 20 from flexget.plugin import PluginError 21 from flexget.utils.database import json_synonym 22 23 log = logging.getLogger('variables') 24 25 DB_VERSION = 0 26 Base = db_schema.versioned_base('variables', DB_VERSION) 27 28 29 class Variables(Base): 30 __tablename__ = 'variables' 31 32 id = Column(Integer, primary_key=True) 33 _variables = Column('variables', Unicode) 34 variables = json_synonym('_variables') 35 added = Column(DateTime, default=datetime.now) 36 37 38 def variables_from_file(config_base, filename): 39 variables_file = os.path.join(config_base, filename) 40 if not os.path.exists(variables_file): 41 raise PluginError('File %s does not exist!' % variables_file) 42 try: 43 with codecs.open(variables_file, 'rb', 'utf-8') as f: 44 variables_dict = yaml.safe_load(f.read()) 45 except yaml.YAMLError as e: 46 raise PluginError('Invalid variables file: %s' % e) 47 return variables_dict or {} 48 49 50 def variables_from_db(): 51 with Session() as session: 52 variables = session.query(Variables).first() 53 if variables: 54 return variables.variables 55 else: 56 return {} 57 58 59 def variables_to_db(variables_dict): 60 with Session() as session: 61 variables = session.query(Variables).first() 62 if not variables: 63 variables = Variables() 64 variables.variables = variables_dict 65 session.merge(variables) 66 67 68 @event('manager.before_config_validate') 69 def process_variables(config, manager): 70 """Render all string elements of the config against defined variables.""" 71 env_params = { 72 'block_start_string': '^^disabled^^', 73 'block_end_string': '^^disabled^^', 74 'variable_start_string': '{?', 75 'variable_end_string': '?}' 76 } 77 if 'variables' not in config or config.get('variables') is False: 78 return 79 env = Environment(**env_params) 80 if isinstance(config['variables'], bool): 81 log.debug('trying to load variables from DB') 82 variables = variables_from_db() 83 else: 84 log.debug('trying to load variables from file') 85 variables = variables_from_file(manager.config_base, config['variables']) 86 log.debug('updating DB with variable file contents') 87 variables_to_db(variables) 88 env.globals = variables 89 _process(config, env) 90 return config 91 92 93 def _process(element, environment): 94 if isinstance(element, dict): 95 for k, v in element.items(): 96 new_key = _process(k, environment) 97 if new_key: 98 element[new_key] = element.pop(k) 99 k = new_key 100 val = _process(element[k], environment) 101 if val: 102 element[k] = val 103 elif isinstance(element, list): 104 for i, v in enumerate(element): 105 val = _process(v, environment) 106 if val: 107 element[i] = val 108 elif isinstance(element, str) and '{?' in element: 109 try: 110 template = environment.from_string(element) 111 return template.render() 112 except (TemplateError, TypeError): 113 return None 114 115 116 variables_config_schema = {'type': ['string', 'boolean']} 117 118 119 @event('config.register') 120 def register_config(): 121 register_config_key('variables', variables_config_schema) 122 ``` Path: `flexget/_version.py` Content: ``` 1 """ 2 Current FlexGet version. 3 This is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by 4 release scripts in continuous integration. Should (almost) never be set manually. 5 6 The version should always be set to the <next release version>.dev 7 The jenkins release job will automatically strip the .dev for release, 8 and update the version again for continued development. 9 """ 10 __version__ = '2.15.2.dev' 11 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/flexget/_version.py b/flexget/_version.py --- a/flexget/_version.py +++ b/flexget/_version.py @@ -7,4 +7,4 @@ The jenkins release job will automatically strip the .dev for release, and update the version again for continued development. """ -__version__ = '2.15.2.dev' +__version__ = '2.16.0.dev' diff --git a/flexget/plugins/modify/variables.py b/flexget/plugins/modify/variables.py --- a/flexget/plugins/modify/variables.py +++ b/flexget/plugins/modify/variables.py @@ -8,7 +8,8 @@ import yaml -from jinja2 import Environment, TemplateError +from jinja2 import TemplateError +from jinja2.nativetypes import NativeEnvironment from sqlalchemy import Column from sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer @@ -76,10 +77,13 @@ } if 'variables' not in config or config.get('variables') is False: return - env = Environment(**env_params) + env = NativeEnvironment(**env_params) if isinstance(config['variables'], bool): log.debug('trying to load variables from DB') variables = variables_from_db() + elif isinstance(config['variables'], dict): + log.debug('loading variables from config') + variables = config['variables'] else: log.debug('trying to load variables from file') variables = variables_from_file(manager.config_base, config['variables']) @@ -113,7 +117,7 @@ return None -variables_config_schema = {'type': ['string', 'boolean']} +variables_config_schema = {'type': ['string', 'boolean', 'object']} @event('config.register')
{"golden_diff": "diff --git a/flexget/_version.py b/flexget/_version.py\n--- a/flexget/_version.py\n+++ b/flexget/_version.py\n@@ -7,4 +7,4 @@\n The jenkins release job will automatically strip the .dev for release,\n and update the version again for continued development.\n \"\"\"\n-__version__ = '2.15.2.dev'\n+__version__ = '2.16.0.dev'\ndiff --git a/flexget/plugins/modify/variables.py b/flexget/plugins/modify/variables.py\n--- a/flexget/plugins/modify/variables.py\n+++ b/flexget/plugins/modify/variables.py\n@@ -8,7 +8,8 @@\n \n import yaml\n \n-from jinja2 import Environment, TemplateError\n+from jinja2 import TemplateError\n+from jinja2.nativetypes import NativeEnvironment\n \n from sqlalchemy import Column\n from sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer\n@@ -76,10 +77,13 @@\n }\n if 'variables' not in config or config.get('variables') is False:\n return\n- env = Environment(**env_params)\n+ env = NativeEnvironment(**env_params)\n if isinstance(config['variables'], bool):\n log.debug('trying to load variables from DB')\n variables = variables_from_db()\n+ elif isinstance(config['variables'], dict):\n+ log.debug('loading variables from config')\n+ variables = config['variables']\n else:\n log.debug('trying to load variables from file')\n variables = variables_from_file(manager.config_base, config['variables'])\n@@ -113,7 +117,7 @@\n return None\n \n \n-variables_config_schema = {'type': ['string', 'boolean']}\n+variables_config_schema = {'type': ['string', 'boolean', 'object']}\n \n \n @event('config.register')\n", "issue": "Cannot use variables with integer-only values\n### Expected behaviour:\r\nVariables should be able to handle integer-only values.\r\n\r\n### Actual behaviour:\r\nConfiguration parsing error (when using ``'{? deluge.port ?}'``): ``Got `50586`, expected: integer``\r\nConfiguration parsing error (when using ``{? deluge.port ?}``):\r\n```\r\nwhile parsing a flow mapping in \"<unicode string>\", line 16, column 13: port: {? deluge.port ?} ^ expected ',' or '}', but got '?' in \"<unicode string>\", line 16, column 28: port: {? deluge.port ?} ^\r\n```\r\n\r\n### Steps to reproduce:\r\n- Step 1: Try to use below config.\r\n\r\n#### Config:\r\n```\r\n from_deluge:\r\n host: '{? deluge.host ?}'\r\n port: '{? deluge.port ?}'\r\n\r\n```\r\n \r\n#### Log:\r\nSee above.\r\n\r\n### Additional information:\r\n\r\n- Flexget Version: 2.10.24\r\n- Python Version: 2.7.9\r\n- Installation method: pip\r\n- OS and version: macOS El Capitan 10.11.6\r\n- Link to crash log: n/a\n", "before_files": [{"content": "from __future__ import unicode_literals, division, absolute_import\nfrom builtins import * # noqa pylint: disable=unused-import, redefined-builtin\n\nimport codecs\nimport logging\nimport os\nfrom datetime import datetime\n\nimport yaml\n\nfrom jinja2 import Environment, TemplateError\n\nfrom sqlalchemy import Column\nfrom sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer\n\nfrom flexget import db_schema\nfrom flexget.config_schema import register_config_key\nfrom flexget.event import event\nfrom flexget.manager import Session\nfrom flexget.plugin import PluginError\nfrom flexget.utils.database import json_synonym\n\nlog = logging.getLogger('variables')\n\nDB_VERSION = 0\nBase = db_schema.versioned_base('variables', DB_VERSION)\n\n\nclass Variables(Base):\n __tablename__ = 'variables'\n\n id = Column(Integer, primary_key=True)\n _variables = Column('variables', Unicode)\n variables = json_synonym('_variables')\n added = Column(DateTime, default=datetime.now)\n\n\ndef variables_from_file(config_base, filename):\n variables_file = os.path.join(config_base, filename)\n if not os.path.exists(variables_file):\n raise PluginError('File %s does not exist!' % variables_file)\n try:\n with codecs.open(variables_file, 'rb', 'utf-8') as f:\n variables_dict = yaml.safe_load(f.read())\n except yaml.YAMLError as e:\n raise PluginError('Invalid variables file: %s' % e)\n return variables_dict or {}\n\n\ndef variables_from_db():\n with Session() as session:\n variables = session.query(Variables).first()\n if variables:\n return variables.variables\n else:\n return {}\n\n\ndef variables_to_db(variables_dict):\n with Session() as session:\n variables = session.query(Variables).first()\n if not variables:\n variables = Variables()\n variables.variables = variables_dict\n session.merge(variables)\n\n\n@event('manager.before_config_validate')\ndef process_variables(config, manager):\n \"\"\"Render all string elements of the config against defined variables.\"\"\"\n env_params = {\n 'block_start_string': '^^disabled^^',\n 'block_end_string': '^^disabled^^',\n 'variable_start_string': '{?',\n 'variable_end_string': '?}'\n }\n if 'variables' not in config or config.get('variables') is False:\n return\n env = Environment(**env_params)\n if isinstance(config['variables'], bool):\n log.debug('trying to load variables from DB')\n variables = variables_from_db()\n else:\n log.debug('trying to load variables from file')\n variables = variables_from_file(manager.config_base, config['variables'])\n log.debug('updating DB with variable file contents')\n variables_to_db(variables)\n env.globals = variables\n _process(config, env)\n return config\n\n\ndef _process(element, environment):\n if isinstance(element, dict):\n for k, v in element.items():\n new_key = _process(k, environment)\n if new_key:\n element[new_key] = element.pop(k)\n k = new_key\n val = _process(element[k], environment)\n if val:\n element[k] = val\n elif isinstance(element, list):\n for i, v in enumerate(element):\n val = _process(v, environment)\n if val:\n element[i] = val\n elif isinstance(element, str) and '{?' in element:\n try:\n template = environment.from_string(element)\n return template.render()\n except (TemplateError, TypeError):\n return None\n\n\nvariables_config_schema = {'type': ['string', 'boolean']}\n\n\n@event('config.register')\ndef register_config():\n register_config_key('variables', variables_config_schema)\n", "path": "flexget/plugins/modify/variables.py"}, {"content": "\"\"\"\nCurrent FlexGet version.\nThis is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by\nrelease scripts in continuous integration. Should (almost) never be set manually.\n\nThe version should always be set to the <next release version>.dev\nThe jenkins release job will automatically strip the .dev for release,\nand update the version again for continued development.\n\"\"\"\n__version__ = '2.15.2.dev'\n", "path": "flexget/_version.py"}], "after_files": [{"content": "from __future__ import unicode_literals, division, absolute_import\nfrom builtins import * # noqa pylint: disable=unused-import, redefined-builtin\n\nimport codecs\nimport logging\nimport os\nfrom datetime import datetime\n\nimport yaml\n\nfrom jinja2 import TemplateError\nfrom jinja2.nativetypes import NativeEnvironment\n\nfrom sqlalchemy import Column\nfrom sqlalchemy.sql.sqltypes import Unicode, DateTime, Integer\n\nfrom flexget import db_schema\nfrom flexget.config_schema import register_config_key\nfrom flexget.event import event\nfrom flexget.manager import Session\nfrom flexget.plugin import PluginError\nfrom flexget.utils.database import json_synonym\n\nlog = logging.getLogger('variables')\n\nDB_VERSION = 0\nBase = db_schema.versioned_base('variables', DB_VERSION)\n\n\nclass Variables(Base):\n __tablename__ = 'variables'\n\n id = Column(Integer, primary_key=True)\n _variables = Column('variables', Unicode)\n variables = json_synonym('_variables')\n added = Column(DateTime, default=datetime.now)\n\n\ndef variables_from_file(config_base, filename):\n variables_file = os.path.join(config_base, filename)\n if not os.path.exists(variables_file):\n raise PluginError('File %s does not exist!' % variables_file)\n try:\n with codecs.open(variables_file, 'rb', 'utf-8') as f:\n variables_dict = yaml.safe_load(f.read())\n except yaml.YAMLError as e:\n raise PluginError('Invalid variables file: %s' % e)\n return variables_dict or {}\n\n\ndef variables_from_db():\n with Session() as session:\n variables = session.query(Variables).first()\n if variables:\n return variables.variables\n else:\n return {}\n\n\ndef variables_to_db(variables_dict):\n with Session() as session:\n variables = session.query(Variables).first()\n if not variables:\n variables = Variables()\n variables.variables = variables_dict\n session.merge(variables)\n\n\n@event('manager.before_config_validate')\ndef process_variables(config, manager):\n \"\"\"Render all string elements of the config against defined variables.\"\"\"\n env_params = {\n 'block_start_string': '^^disabled^^',\n 'block_end_string': '^^disabled^^',\n 'variable_start_string': '{?',\n 'variable_end_string': '?}'\n }\n if 'variables' not in config or config.get('variables') is False:\n return\n env = NativeEnvironment(**env_params)\n if isinstance(config['variables'], bool):\n log.debug('trying to load variables from DB')\n variables = variables_from_db()\n elif isinstance(config['variables'], dict):\n log.debug('loading variables from config')\n variables = config['variables']\n else:\n log.debug('trying to load variables from file')\n variables = variables_from_file(manager.config_base, config['variables'])\n log.debug('updating DB with variable file contents')\n variables_to_db(variables)\n env.globals = variables\n _process(config, env)\n return config\n\n\ndef _process(element, environment):\n if isinstance(element, dict):\n for k, v in element.items():\n new_key = _process(k, environment)\n if new_key:\n element[new_key] = element.pop(k)\n k = new_key\n val = _process(element[k], environment)\n if val:\n element[k] = val\n elif isinstance(element, list):\n for i, v in enumerate(element):\n val = _process(v, environment)\n if val:\n element[i] = val\n elif isinstance(element, str) and '{?' in element:\n try:\n template = environment.from_string(element)\n return template.render()\n except (TemplateError, TypeError):\n return None\n\n\nvariables_config_schema = {'type': ['string', 'boolean', 'object']}\n\n\n@event('config.register')\ndef register_config():\n register_config_key('variables', variables_config_schema)\n", "path": "flexget/plugins/modify/variables.py"}, {"content": "\"\"\"\nCurrent FlexGet version.\nThis is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by\nrelease scripts in continuous integration. Should (almost) never be set manually.\n\nThe version should always be set to the <next release version>.dev\nThe jenkins release job will automatically strip the .dev for release,\nand update the version again for continued development.\n\"\"\"\n__version__ = '2.16.0.dev'\n", "path": "flexget/_version.py"}]}
1,704
403
gh_patches_debug_21179
rasdani/github-patches
git_diff
googleapis__google-api-python-client-903
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add a new mechanism to avoid calling the legacy memcache API This API is only supported on the python27 runtime. Lets only try to import it in environments that actually support it. The problem I'm running into is a bit esoteric, but here goes. We've built some GAE API shims to help move our apps to newer App Engine runtimes (like python3) that don't include these legacy APIs. Because of that, when this library tries to import google.appengine.api.memcache, it imports and uses our shim, and that isn't always desirable. Having some way to configure googleapiclient to not use this legacy API even if it is importable would be useful. Despite this sorta niche use case, I figured I'd propose this change upstream since reducing reliance on a py2-only API shouldn't be too controversial these days. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `googleapiclient/discovery_cache/__init__.py` Content: ``` 1 # Copyright 2014 Google Inc. All Rights Reserved. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """Caching utility for the discovery document.""" 16 17 from __future__ import absolute_import 18 19 import logging 20 import datetime 21 22 23 LOGGER = logging.getLogger(__name__) 24 25 DISCOVERY_DOC_MAX_AGE = 60 * 60 * 24 # 1 day 26 27 28 def autodetect(): 29 """Detects an appropriate cache module and returns it. 30 31 Returns: 32 googleapiclient.discovery_cache.base.Cache, a cache object which 33 is auto detected, or None if no cache object is available. 34 """ 35 try: 36 from google.appengine.api import memcache 37 from . import appengine_memcache 38 39 return appengine_memcache.cache 40 except Exception: 41 try: 42 from . import file_cache 43 44 return file_cache.cache 45 except Exception as e: 46 LOGGER.warning(e, exc_info=True) 47 return None 48 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/googleapiclient/discovery_cache/__init__.py b/googleapiclient/discovery_cache/__init__.py --- a/googleapiclient/discovery_cache/__init__.py +++ b/googleapiclient/discovery_cache/__init__.py @@ -18,7 +18,7 @@ import logging import datetime - +import os LOGGER = logging.getLogger(__name__) @@ -32,16 +32,18 @@ googleapiclient.discovery_cache.base.Cache, a cache object which is auto detected, or None if no cache object is available. """ - try: - from google.appengine.api import memcache - from . import appengine_memcache - - return appengine_memcache.cache - except Exception: + if 'APPENGINE_RUNTIME' in os.environ: try: - from . import file_cache + from google.appengine.api import memcache + from . import appengine_memcache + + return appengine_memcache.cache + except Exception: + pass + try: + from . import file_cache - return file_cache.cache - except Exception as e: - LOGGER.warning(e, exc_info=True) - return None + return file_cache.cache + except Exception as e: + LOGGER.warning(e, exc_info=True) + return None
{"golden_diff": "diff --git a/googleapiclient/discovery_cache/__init__.py b/googleapiclient/discovery_cache/__init__.py\n--- a/googleapiclient/discovery_cache/__init__.py\n+++ b/googleapiclient/discovery_cache/__init__.py\n@@ -18,7 +18,7 @@\n \n import logging\n import datetime\n-\n+import os\n \n LOGGER = logging.getLogger(__name__)\n \n@@ -32,16 +32,18 @@\n googleapiclient.discovery_cache.base.Cache, a cache object which\n is auto detected, or None if no cache object is available.\n \"\"\"\n- try:\n- from google.appengine.api import memcache\n- from . import appengine_memcache\n-\n- return appengine_memcache.cache\n- except Exception:\n+ if 'APPENGINE_RUNTIME' in os.environ:\n try:\n- from . import file_cache\n+ from google.appengine.api import memcache\n+ from . import appengine_memcache\n+\n+ return appengine_memcache.cache\n+ except Exception:\n+ pass\n+ try:\n+ from . import file_cache\n \n- return file_cache.cache\n- except Exception as e:\n- LOGGER.warning(e, exc_info=True)\n- return None\n+ return file_cache.cache\n+ except Exception as e:\n+ LOGGER.warning(e, exc_info=True)\n+ return None\n", "issue": "Add a new mechanism to avoid calling the legacy memcache API\nThis API is only supported on the python27 runtime. Lets only try to import it in environments that actually support it.\r\n\r\nThe problem I'm running into is a bit esoteric, but here goes. We've built some GAE API shims to help move our apps to newer App Engine runtimes (like python3) that don't include these legacy APIs. Because of that, when this library tries to import google.appengine.api.memcache, it imports and uses our shim, and that isn't always desirable. Having some way to configure googleapiclient to not use this legacy API even if it is importable would be useful.\r\n\r\nDespite this sorta niche use case, I figured I'd propose this change upstream since reducing reliance on a py2-only API shouldn't be too controversial these days.\n", "before_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Caching utility for the discovery document.\"\"\"\n\nfrom __future__ import absolute_import\n\nimport logging\nimport datetime\n\n\nLOGGER = logging.getLogger(__name__)\n\nDISCOVERY_DOC_MAX_AGE = 60 * 60 * 24 # 1 day\n\n\ndef autodetect():\n \"\"\"Detects an appropriate cache module and returns it.\n\n Returns:\n googleapiclient.discovery_cache.base.Cache, a cache object which\n is auto detected, or None if no cache object is available.\n \"\"\"\n try:\n from google.appengine.api import memcache\n from . import appengine_memcache\n\n return appengine_memcache.cache\n except Exception:\n try:\n from . import file_cache\n\n return file_cache.cache\n except Exception as e:\n LOGGER.warning(e, exc_info=True)\n return None\n", "path": "googleapiclient/discovery_cache/__init__.py"}], "after_files": [{"content": "# Copyright 2014 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Caching utility for the discovery document.\"\"\"\n\nfrom __future__ import absolute_import\n\nimport logging\nimport datetime\nimport os\n\nLOGGER = logging.getLogger(__name__)\n\nDISCOVERY_DOC_MAX_AGE = 60 * 60 * 24 # 1 day\n\n\ndef autodetect():\n \"\"\"Detects an appropriate cache module and returns it.\n\n Returns:\n googleapiclient.discovery_cache.base.Cache, a cache object which\n is auto detected, or None if no cache object is available.\n \"\"\"\n if 'APPENGINE_RUNTIME' in os.environ:\n try:\n from google.appengine.api import memcache\n from . import appengine_memcache\n\n return appengine_memcache.cache\n except Exception:\n pass\n try:\n from . import file_cache\n\n return file_cache.cache\n except Exception as e:\n LOGGER.warning(e, exc_info=True)\n return None\n", "path": "googleapiclient/discovery_cache/__init__.py"}]}
852
307
gh_patches_debug_19492
rasdani/github-patches
git_diff
zigpy__zha-device-handlers-664
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [Device Support Request] Phillips Button (ROM001) Missing support for manufactuer specific button events **Is your feature request related to a problem? Please describe.** I have just started migrating my devices from deconz to ZHA and had success with the hue dimmer remote event codes. However, the hue button which also supports the 64512 is not configured for it. **Describe the solution you'd like** Add the 64512 (0xfc00) cluster to the hue button. **Device signature - this can be acquired by removing the device from ZHA and pairing it again from the add devices screen. Be sure to add the entire content of the log panel after pairing the device to a code block below this line.** Button: ``` { "node_descriptor": "NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4107, maximum_buffer_size=82, maximum_incoming_transfer_size=128, server_mask=11264, maximum_outgoing_transfer_size=128, descriptor_capability_field=0)", "endpoints": { "1": { "profile_id": 260, "device_type": "0x0830", "in_clusters": [ "0x0000", "0x0001", "0x0003", "0x1000", "0xfc00" ], "out_clusters": [ "0x0000", "0x0003", "0x0004", "0x0005", "0x0006", "0x0008", "0x0019", "0x1000" ] } }, "manufacturer": "Philips", "model": "ROM001", "class": "zhaquirks.philips.rom001.PhilipsROM001" } ``` Dimmer: ``` { "node_descriptor": "NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4107, maximum_buffer_size=89, maximum_incoming_transfer_size=63, server_mask=0, maximum_outgoing_transfer_size=63, descriptor_capability_field=0)", "endpoints": { "1": { "profile_id": 49246, "device_type": "0x0830", "in_clusters": [ "0x0000" ], "out_clusters": [ "0x0000", "0x0003", "0x0004", "0x0005", "0x0006", "0x0008" ] }, "2": { "profile_id": 260, "device_type": "0x000c", "in_clusters": [ "0x0000", "0x0001", "0x0003", "0x000f", "0xfc00" ], "out_clusters": [ "0x0019" ] } }, "manufacturer": "Philips", "model": "RWL021", "class": "zhaquirks.philips.rwl021.PhilipsRWL021" } ``` **Additional context** Add any other context or screenshots about the feature request here. This should be a simple case of importing PhilipsRemoteCluster and applying it https://github.com/zigpy/zha-device-handlers/blob/71d4dcb9c8f502dee7f73ac4bbf1593b916e794e/zhaquirks/philips/rwl020.py#L80 https://github.com/zigpy/zha-device-handlers/blob/71d4dcb9c8f502dee7f73ac4bbf1593b916e794e/zhaquirks/philips/rom001.py#L75 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `zhaquirks/philips/rom001.py` Content: ``` 1 """Philips ROM001 device.""" 2 from zigpy.profiles import zha 3 from zigpy.quirks import CustomDevice 4 from zigpy.zcl.clusters.general import ( 5 Basic, 6 Groups, 7 Identify, 8 LevelControl, 9 OnOff, 10 Ota, 11 PowerConfiguration, 12 Scenes, 13 ) 14 from zigpy.zcl.clusters.lightlink import LightLink 15 16 from ..const import ( 17 COMMAND, 18 COMMAND_OFF_WITH_EFFECT, 19 COMMAND_ON, 20 DEVICE_TYPE, 21 ENDPOINTS, 22 INPUT_CLUSTERS, 23 OUTPUT_CLUSTERS, 24 PROFILE_ID, 25 SHORT_PRESS, 26 TURN_OFF, 27 TURN_ON, 28 ) 29 30 DEVICE_SPECIFIC_UNKNOWN = 64512 31 32 33 class PhilipsROM001(CustomDevice): 34 """Philips ROM001 device.""" 35 36 signature = { 37 # <SimpleDescriptor endpoint=1 profile=260 device_type=2096 38 # device_version=1 39 # input_clusters=[0, 1, 3, 64512, 4096] 40 # output_clusters=[25, 0, 3, 4, 6, 8, 5, 4096]> 41 ENDPOINTS: { 42 1: { 43 PROFILE_ID: zha.PROFILE_ID, 44 DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER, 45 INPUT_CLUSTERS: [ 46 Basic.cluster_id, 47 PowerConfiguration.cluster_id, 48 Identify.cluster_id, 49 DEVICE_SPECIFIC_UNKNOWN, 50 LightLink.cluster_id, 51 ], 52 OUTPUT_CLUSTERS: [ 53 Ota.cluster_id, 54 Basic.cluster_id, 55 Identify.cluster_id, 56 Groups.cluster_id, 57 OnOff.cluster_id, 58 LevelControl.cluster_id, 59 Scenes.cluster_id, 60 LightLink.cluster_id, 61 ], 62 } 63 } 64 } 65 66 replacement = { 67 ENDPOINTS: { 68 1: { 69 PROFILE_ID: zha.PROFILE_ID, 70 DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER, 71 INPUT_CLUSTERS: [ 72 Basic.cluster_id, 73 PowerConfiguration.cluster_id, 74 Identify.cluster_id, 75 DEVICE_SPECIFIC_UNKNOWN, 76 LightLink.cluster_id, 77 ], 78 OUTPUT_CLUSTERS: [ 79 Ota.cluster_id, 80 Basic.cluster_id, 81 Identify.cluster_id, 82 Groups.cluster_id, 83 OnOff.cluster_id, 84 LevelControl.cluster_id, 85 Scenes.cluster_id, 86 LightLink.cluster_id, 87 ], 88 } 89 } 90 } 91 92 device_automation_triggers = { 93 (SHORT_PRESS, TURN_ON): {COMMAND: COMMAND_ON}, 94 (SHORT_PRESS, TURN_OFF): {COMMAND: COMMAND_OFF_WITH_EFFECT}, 95 } 96 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/zhaquirks/philips/rom001.py b/zhaquirks/philips/rom001.py --- a/zhaquirks/philips/rom001.py +++ b/zhaquirks/philips/rom001.py @@ -13,6 +13,7 @@ ) from zigpy.zcl.clusters.lightlink import LightLink +from . import PhilipsBasicCluster, PhilipsRemoteCluster from ..const import ( COMMAND, COMMAND_OFF_WITH_EFFECT, @@ -69,10 +70,10 @@ PROFILE_ID: zha.PROFILE_ID, DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER, INPUT_CLUSTERS: [ - Basic.cluster_id, + PhilipsBasicCluster, PowerConfiguration.cluster_id, Identify.cluster_id, - DEVICE_SPECIFIC_UNKNOWN, + PhilipsRemoteCluster, LightLink.cluster_id, ], OUTPUT_CLUSTERS: [
{"golden_diff": "diff --git a/zhaquirks/philips/rom001.py b/zhaquirks/philips/rom001.py\n--- a/zhaquirks/philips/rom001.py\n+++ b/zhaquirks/philips/rom001.py\n@@ -13,6 +13,7 @@\n )\n from zigpy.zcl.clusters.lightlink import LightLink\n \n+from . import PhilipsBasicCluster, PhilipsRemoteCluster\n from ..const import (\n COMMAND,\n COMMAND_OFF_WITH_EFFECT,\n@@ -69,10 +70,10 @@\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n- Basic.cluster_id,\n+ PhilipsBasicCluster,\n PowerConfiguration.cluster_id,\n Identify.cluster_id,\n- DEVICE_SPECIFIC_UNKNOWN,\n+ PhilipsRemoteCluster,\n LightLink.cluster_id,\n ],\n OUTPUT_CLUSTERS: [\n", "issue": "[Device Support Request] Phillips Button (ROM001) Missing support for manufactuer specific button events\n**Is your feature request related to a problem? Please describe.**\r\nI have just started migrating my devices from deconz to ZHA and had success with the hue dimmer remote event codes.\r\nHowever, the hue button which also supports the 64512 is not configured for it.\r\n\r\n**Describe the solution you'd like**\r\nAdd the 64512 (0xfc00) cluster to the hue button.\r\n\r\n**Device signature - this can be acquired by removing the device from ZHA and pairing it again from the add devices screen. Be sure to add the entire content of the log panel after pairing the device to a code block below this line.**\r\n\r\nButton:\r\n```\r\n{\r\n \"node_descriptor\": \"NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4107, maximum_buffer_size=82, maximum_incoming_transfer_size=128, server_mask=11264, maximum_outgoing_transfer_size=128, descriptor_capability_field=0)\",\r\n \"endpoints\": {\r\n \"1\": {\r\n \"profile_id\": 260,\r\n \"device_type\": \"0x0830\",\r\n \"in_clusters\": [\r\n \"0x0000\",\r\n \"0x0001\",\r\n \"0x0003\",\r\n \"0x1000\",\r\n \"0xfc00\"\r\n ],\r\n \"out_clusters\": [\r\n \"0x0000\",\r\n \"0x0003\",\r\n \"0x0004\",\r\n \"0x0005\",\r\n \"0x0006\",\r\n \"0x0008\",\r\n \"0x0019\",\r\n \"0x1000\"\r\n ]\r\n }\r\n },\r\n \"manufacturer\": \"Philips\",\r\n \"model\": \"ROM001\",\r\n \"class\": \"zhaquirks.philips.rom001.PhilipsROM001\"\r\n}\r\n```\r\n\r\nDimmer:\r\n```\r\n{\r\n \"node_descriptor\": \"NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4107, maximum_buffer_size=89, maximum_incoming_transfer_size=63, server_mask=0, maximum_outgoing_transfer_size=63, descriptor_capability_field=0)\",\r\n \"endpoints\": {\r\n \"1\": {\r\n \"profile_id\": 49246,\r\n \"device_type\": \"0x0830\",\r\n \"in_clusters\": [\r\n \"0x0000\"\r\n ],\r\n \"out_clusters\": [\r\n \"0x0000\",\r\n \"0x0003\",\r\n \"0x0004\",\r\n \"0x0005\",\r\n \"0x0006\",\r\n \"0x0008\"\r\n ]\r\n },\r\n \"2\": {\r\n \"profile_id\": 260,\r\n \"device_type\": \"0x000c\",\r\n \"in_clusters\": [\r\n \"0x0000\",\r\n \"0x0001\",\r\n \"0x0003\",\r\n \"0x000f\",\r\n \"0xfc00\"\r\n ],\r\n \"out_clusters\": [\r\n \"0x0019\"\r\n ]\r\n }\r\n },\r\n \"manufacturer\": \"Philips\",\r\n \"model\": \"RWL021\",\r\n \"class\": \"zhaquirks.philips.rwl021.PhilipsRWL021\"\r\n}\r\n```\r\n**Additional context**\r\nAdd any other context or screenshots about the feature request here.\r\n\r\nThis should be a simple case of importing PhilipsRemoteCluster and applying it\r\nhttps://github.com/zigpy/zha-device-handlers/blob/71d4dcb9c8f502dee7f73ac4bbf1593b916e794e/zhaquirks/philips/rwl020.py#L80\r\n\r\nhttps://github.com/zigpy/zha-device-handlers/blob/71d4dcb9c8f502dee7f73ac4bbf1593b916e794e/zhaquirks/philips/rom001.py#L75\r\n\n", "before_files": [{"content": "\"\"\"Philips ROM001 device.\"\"\"\nfrom zigpy.profiles import zha\nfrom zigpy.quirks import CustomDevice\nfrom zigpy.zcl.clusters.general import (\n Basic,\n Groups,\n Identify,\n LevelControl,\n OnOff,\n Ota,\n PowerConfiguration,\n Scenes,\n)\nfrom zigpy.zcl.clusters.lightlink import LightLink\n\nfrom ..const import (\n COMMAND,\n COMMAND_OFF_WITH_EFFECT,\n COMMAND_ON,\n DEVICE_TYPE,\n ENDPOINTS,\n INPUT_CLUSTERS,\n OUTPUT_CLUSTERS,\n PROFILE_ID,\n SHORT_PRESS,\n TURN_OFF,\n TURN_ON,\n)\n\nDEVICE_SPECIFIC_UNKNOWN = 64512\n\n\nclass PhilipsROM001(CustomDevice):\n \"\"\"Philips ROM001 device.\"\"\"\n\n signature = {\n # <SimpleDescriptor endpoint=1 profile=260 device_type=2096\n # device_version=1\n # input_clusters=[0, 1, 3, 64512, 4096]\n # output_clusters=[25, 0, 3, 4, 6, 8, 5, 4096]>\n ENDPOINTS: {\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n Basic.cluster_id,\n PowerConfiguration.cluster_id,\n Identify.cluster_id,\n DEVICE_SPECIFIC_UNKNOWN,\n LightLink.cluster_id,\n ],\n OUTPUT_CLUSTERS: [\n Ota.cluster_id,\n Basic.cluster_id,\n Identify.cluster_id,\n Groups.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Scenes.cluster_id,\n LightLink.cluster_id,\n ],\n }\n }\n }\n\n replacement = {\n ENDPOINTS: {\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n Basic.cluster_id,\n PowerConfiguration.cluster_id,\n Identify.cluster_id,\n DEVICE_SPECIFIC_UNKNOWN,\n LightLink.cluster_id,\n ],\n OUTPUT_CLUSTERS: [\n Ota.cluster_id,\n Basic.cluster_id,\n Identify.cluster_id,\n Groups.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Scenes.cluster_id,\n LightLink.cluster_id,\n ],\n }\n }\n }\n\n device_automation_triggers = {\n (SHORT_PRESS, TURN_ON): {COMMAND: COMMAND_ON},\n (SHORT_PRESS, TURN_OFF): {COMMAND: COMMAND_OFF_WITH_EFFECT},\n }\n", "path": "zhaquirks/philips/rom001.py"}], "after_files": [{"content": "\"\"\"Philips ROM001 device.\"\"\"\nfrom zigpy.profiles import zha\nfrom zigpy.quirks import CustomDevice\nfrom zigpy.zcl.clusters.general import (\n Basic,\n Groups,\n Identify,\n LevelControl,\n OnOff,\n Ota,\n PowerConfiguration,\n Scenes,\n)\nfrom zigpy.zcl.clusters.lightlink import LightLink\n\nfrom . import PhilipsBasicCluster, PhilipsRemoteCluster\nfrom ..const import (\n COMMAND,\n COMMAND_OFF_WITH_EFFECT,\n COMMAND_ON,\n DEVICE_TYPE,\n ENDPOINTS,\n INPUT_CLUSTERS,\n OUTPUT_CLUSTERS,\n PROFILE_ID,\n SHORT_PRESS,\n TURN_OFF,\n TURN_ON,\n)\n\nDEVICE_SPECIFIC_UNKNOWN = 64512\n\n\nclass PhilipsROM001(CustomDevice):\n \"\"\"Philips ROM001 device.\"\"\"\n\n signature = {\n # <SimpleDescriptor endpoint=1 profile=260 device_type=2096\n # device_version=1\n # input_clusters=[0, 1, 3, 64512, 4096]\n # output_clusters=[25, 0, 3, 4, 6, 8, 5, 4096]>\n ENDPOINTS: {\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n Basic.cluster_id,\n PowerConfiguration.cluster_id,\n Identify.cluster_id,\n DEVICE_SPECIFIC_UNKNOWN,\n LightLink.cluster_id,\n ],\n OUTPUT_CLUSTERS: [\n Ota.cluster_id,\n Basic.cluster_id,\n Identify.cluster_id,\n Groups.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Scenes.cluster_id,\n LightLink.cluster_id,\n ],\n }\n }\n }\n\n replacement = {\n ENDPOINTS: {\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.NON_COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n PhilipsBasicCluster,\n PowerConfiguration.cluster_id,\n Identify.cluster_id,\n PhilipsRemoteCluster,\n LightLink.cluster_id,\n ],\n OUTPUT_CLUSTERS: [\n Ota.cluster_id,\n Basic.cluster_id,\n Identify.cluster_id,\n Groups.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Scenes.cluster_id,\n LightLink.cluster_id,\n ],\n }\n }\n }\n\n device_automation_triggers = {\n (SHORT_PRESS, TURN_ON): {COMMAND: COMMAND_ON},\n (SHORT_PRESS, TURN_OFF): {COMMAND: COMMAND_OFF_WITH_EFFECT},\n }\n", "path": "zhaquirks/philips/rom001.py"}]}
1,988
212
gh_patches_debug_29276
rasdani/github-patches
git_diff
wagtail__wagtail-365
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Searching images without match is not displayed correctly (minor) When searching for images, if you enter a query string which will not return resuls you will get the message Sorry, no images match "" (without the query string inside the ""). Beyon this, search works fine. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `wagtail/wagtailsearch/views/editorspicks.py` Content: ``` 1 from django.shortcuts import render, redirect, get_object_or_404 2 from django.contrib.auth.decorators import permission_required 3 from django.contrib import messages 4 5 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger 6 from django.utils.translation import ugettext as _ 7 from django.views.decorators.vary import vary_on_headers 8 9 from wagtail.wagtailsearch import models, forms 10 from wagtail.wagtailadmin.forms import SearchForm 11 12 13 @permission_required('wagtailadmin.access_admin') 14 @vary_on_headers('X-Requested-With') 15 def index(request): 16 page = request.GET.get('p', 1) 17 query_string = request.GET.get('q', "") 18 19 queries = models.Query.objects.filter(editors_picks__isnull=False).distinct() 20 21 # Search 22 if query_string: 23 queries = queries.filter(query_string__icontains=query_string) 24 25 # Pagination 26 paginator = Paginator(queries, 20) 27 try: 28 queries = paginator.page(page) 29 except PageNotAnInteger: 30 queries = paginator.page(1) 31 except EmptyPage: 32 queries = paginator.page(paginator.num_pages) 33 34 if request.is_ajax(): 35 return render(request, "wagtailsearch/editorspicks/results.html", { 36 'queries': queries, 37 'query_string': query_string, 38 }) 39 else: 40 return render(request, 'wagtailsearch/editorspicks/index.html', { 41 'queries': queries, 42 'query_string': query_string, 43 'search_form': SearchForm(data=dict(q=query_string) if query_string else None, placeholder=_("Search editor's picks")), 44 }) 45 46 47 def save_editorspicks(query, new_query, editors_pick_formset): 48 # Save 49 if editors_pick_formset.is_valid(): 50 # Set sort_order 51 for i, form in enumerate(editors_pick_formset.ordered_forms): 52 form.instance.sort_order = i 53 54 editors_pick_formset.save() 55 56 # If query was changed, move all editors picks to the new query 57 if query != new_query: 58 editors_pick_formset.get_queryset().update(query=new_query) 59 60 return True 61 else: 62 return False 63 64 65 @permission_required('wagtailadmin.access_admin') 66 def add(request): 67 if request.POST: 68 # Get query 69 query_form = forms.QueryForm(request.POST) 70 if query_form.is_valid(): 71 query = models.Query.get(query_form['query_string'].value()) 72 73 # Save editors picks 74 editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query) 75 if save_editorspicks(query, query, editors_pick_formset): 76 messages.success(request, _("Editor's picks for '{0}' created.").format(query)) 77 return redirect('wagtailsearch_editorspicks_index') 78 else: 79 if len(editors_pick_formset.non_form_errors()): 80 messages.error(request, " ".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted) 81 else: 82 messages.error(request, _("Recommendations have not been created due to errors")) # specific errors will be displayed within form fields 83 else: 84 editors_pick_formset = forms.EditorsPickFormSet() 85 else: 86 query_form = forms.QueryForm() 87 editors_pick_formset = forms.EditorsPickFormSet() 88 89 return render(request, 'wagtailsearch/editorspicks/add.html', { 90 'query_form': query_form, 91 'editors_pick_formset': editors_pick_formset, 92 }) 93 94 95 @permission_required('wagtailadmin.access_admin') 96 def edit(request, query_id): 97 query = get_object_or_404(models.Query, id=query_id) 98 99 if request.POST: 100 # Get query 101 query_form = forms.QueryForm(request.POST) 102 # and the recommendations 103 editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query) 104 105 if query_form.is_valid(): 106 new_query = models.Query.get(query_form['query_string'].value()) 107 108 # Save editors picks 109 if save_editorspicks(query, new_query, editors_pick_formset): 110 messages.success(request, _("Editor's picks for '{0}' updated.").format(new_query)) 111 return redirect('wagtailsearch_editorspicks_index') 112 else: 113 if len(editors_pick_formset.non_form_errors()): 114 messages.error(request, " ".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted) 115 else: 116 messages.error(request, _("Recommendations have not been saved due to errors")) # specific errors will be displayed within form fields 117 118 else: 119 query_form = forms.QueryForm(initial=dict(query_string=query.query_string)) 120 editors_pick_formset = forms.EditorsPickFormSet(instance=query) 121 122 return render(request, 'wagtailsearch/editorspicks/edit.html', { 123 'query_form': query_form, 124 'editors_pick_formset': editors_pick_formset, 125 'query': query, 126 }) 127 128 129 @permission_required('wagtailadmin.access_admin') 130 def delete(request, query_id): 131 query = get_object_or_404(models.Query, id=query_id) 132 133 if request.POST: 134 query.editors_picks.all().delete() 135 messages.success(request, _("Editor's picks deleted.")) 136 return redirect('wagtailsearch_editorspicks_index') 137 138 return render(request, 'wagtailsearch/editorspicks/confirm_delete.html', { 139 'query': query, 140 }) 141 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/wagtail/wagtailsearch/views/editorspicks.py b/wagtail/wagtailsearch/views/editorspicks.py --- a/wagtail/wagtailsearch/views/editorspicks.py +++ b/wagtail/wagtailsearch/views/editorspicks.py @@ -13,6 +13,7 @@ @permission_required('wagtailadmin.access_admin') @vary_on_headers('X-Requested-With') def index(request): + is_searching = False page = request.GET.get('p', 1) query_string = request.GET.get('q', "") @@ -21,6 +22,7 @@ # Search if query_string: queries = queries.filter(query_string__icontains=query_string) + is_searching = True # Pagination paginator = Paginator(queries, 20) @@ -33,11 +35,13 @@ if request.is_ajax(): return render(request, "wagtailsearch/editorspicks/results.html", { + 'is_searching': is_searching, 'queries': queries, 'query_string': query_string, }) else: return render(request, 'wagtailsearch/editorspicks/index.html', { + 'is_searching': is_searching, 'queries': queries, 'query_string': query_string, 'search_form': SearchForm(data=dict(q=query_string) if query_string else None, placeholder=_("Search editor's picks")),
{"golden_diff": "diff --git a/wagtail/wagtailsearch/views/editorspicks.py b/wagtail/wagtailsearch/views/editorspicks.py\n--- a/wagtail/wagtailsearch/views/editorspicks.py\n+++ b/wagtail/wagtailsearch/views/editorspicks.py\n@@ -13,6 +13,7 @@\n @permission_required('wagtailadmin.access_admin')\n @vary_on_headers('X-Requested-With')\n def index(request):\n+ is_searching = False\n page = request.GET.get('p', 1)\n query_string = request.GET.get('q', \"\")\n \n@@ -21,6 +22,7 @@\n # Search\n if query_string:\n queries = queries.filter(query_string__icontains=query_string)\n+ is_searching = True\n \n # Pagination\n paginator = Paginator(queries, 20)\n@@ -33,11 +35,13 @@\n \n if request.is_ajax():\n return render(request, \"wagtailsearch/editorspicks/results.html\", {\n+ 'is_searching': is_searching,\n 'queries': queries,\n 'query_string': query_string,\n })\n else:\n return render(request, 'wagtailsearch/editorspicks/index.html', {\n+ 'is_searching': is_searching,\n 'queries': queries,\n 'query_string': query_string,\n 'search_form': SearchForm(data=dict(q=query_string) if query_string else None, placeholder=_(\"Search editor's picks\")),\n", "issue": "Searching images without match is not displayed correctly (minor)\nWhen searching for images, if you enter a query string which will not return resuls you will get the message Sorry, no images match \"\" (without the query string inside the \"\"). Beyon this, search works fine.\n\n", "before_files": [{"content": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib import messages\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.vary import vary_on_headers\n\nfrom wagtail.wagtailsearch import models, forms\nfrom wagtail.wagtailadmin.forms import SearchForm\n\n\n@permission_required('wagtailadmin.access_admin')\n@vary_on_headers('X-Requested-With')\ndef index(request):\n page = request.GET.get('p', 1)\n query_string = request.GET.get('q', \"\")\n\n queries = models.Query.objects.filter(editors_picks__isnull=False).distinct()\n\n # Search\n if query_string:\n queries = queries.filter(query_string__icontains=query_string)\n\n # Pagination\n paginator = Paginator(queries, 20)\n try:\n queries = paginator.page(page)\n except PageNotAnInteger:\n queries = paginator.page(1)\n except EmptyPage:\n queries = paginator.page(paginator.num_pages)\n\n if request.is_ajax():\n return render(request, \"wagtailsearch/editorspicks/results.html\", {\n 'queries': queries,\n 'query_string': query_string,\n })\n else:\n return render(request, 'wagtailsearch/editorspicks/index.html', {\n 'queries': queries,\n 'query_string': query_string,\n 'search_form': SearchForm(data=dict(q=query_string) if query_string else None, placeholder=_(\"Search editor's picks\")),\n })\n\n\ndef save_editorspicks(query, new_query, editors_pick_formset):\n # Save\n if editors_pick_formset.is_valid():\n # Set sort_order\n for i, form in enumerate(editors_pick_formset.ordered_forms):\n form.instance.sort_order = i\n\n editors_pick_formset.save()\n\n # If query was changed, move all editors picks to the new query\n if query != new_query:\n editors_pick_formset.get_queryset().update(query=new_query)\n\n return True\n else:\n return False\n\n\n@permission_required('wagtailadmin.access_admin')\ndef add(request):\n if request.POST:\n # Get query\n query_form = forms.QueryForm(request.POST)\n if query_form.is_valid():\n query = models.Query.get(query_form['query_string'].value())\n\n # Save editors picks\n editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)\n if save_editorspicks(query, query, editors_pick_formset):\n messages.success(request, _(\"Editor's picks for '{0}' created.\").format(query))\n return redirect('wagtailsearch_editorspicks_index')\n else:\n if len(editors_pick_formset.non_form_errors()):\n messages.error(request, \" \".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted)\n else:\n messages.error(request, _(\"Recommendations have not been created due to errors\")) # specific errors will be displayed within form fields\n else:\n editors_pick_formset = forms.EditorsPickFormSet()\n else:\n query_form = forms.QueryForm()\n editors_pick_formset = forms.EditorsPickFormSet()\n\n return render(request, 'wagtailsearch/editorspicks/add.html', {\n 'query_form': query_form,\n 'editors_pick_formset': editors_pick_formset,\n })\n\n\n@permission_required('wagtailadmin.access_admin')\ndef edit(request, query_id):\n query = get_object_or_404(models.Query, id=query_id)\n\n if request.POST:\n # Get query\n query_form = forms.QueryForm(request.POST)\n # and the recommendations\n editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)\n\n if query_form.is_valid():\n new_query = models.Query.get(query_form['query_string'].value())\n\n # Save editors picks\n if save_editorspicks(query, new_query, editors_pick_formset):\n messages.success(request, _(\"Editor's picks for '{0}' updated.\").format(new_query))\n return redirect('wagtailsearch_editorspicks_index')\n else:\n if len(editors_pick_formset.non_form_errors()):\n messages.error(request, \" \".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted)\n else:\n messages.error(request, _(\"Recommendations have not been saved due to errors\")) # specific errors will be displayed within form fields\n\n else:\n query_form = forms.QueryForm(initial=dict(query_string=query.query_string))\n editors_pick_formset = forms.EditorsPickFormSet(instance=query)\n\n return render(request, 'wagtailsearch/editorspicks/edit.html', {\n 'query_form': query_form,\n 'editors_pick_formset': editors_pick_formset,\n 'query': query,\n })\n\n\n@permission_required('wagtailadmin.access_admin')\ndef delete(request, query_id):\n query = get_object_or_404(models.Query, id=query_id)\n\n if request.POST:\n query.editors_picks.all().delete()\n messages.success(request, _(\"Editor's picks deleted.\"))\n return redirect('wagtailsearch_editorspicks_index')\n\n return render(request, 'wagtailsearch/editorspicks/confirm_delete.html', {\n 'query': query,\n })\n", "path": "wagtail/wagtailsearch/views/editorspicks.py"}], "after_files": [{"content": "from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import permission_required\nfrom django.contrib import messages\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.vary import vary_on_headers\n\nfrom wagtail.wagtailsearch import models, forms\nfrom wagtail.wagtailadmin.forms import SearchForm\n\n\n@permission_required('wagtailadmin.access_admin')\n@vary_on_headers('X-Requested-With')\ndef index(request):\n is_searching = False\n page = request.GET.get('p', 1)\n query_string = request.GET.get('q', \"\")\n\n queries = models.Query.objects.filter(editors_picks__isnull=False).distinct()\n\n # Search\n if query_string:\n queries = queries.filter(query_string__icontains=query_string)\n is_searching = True\n\n # Pagination\n paginator = Paginator(queries, 20)\n try:\n queries = paginator.page(page)\n except PageNotAnInteger:\n queries = paginator.page(1)\n except EmptyPage:\n queries = paginator.page(paginator.num_pages)\n\n if request.is_ajax():\n return render(request, \"wagtailsearch/editorspicks/results.html\", {\n 'is_searching': is_searching,\n 'queries': queries,\n 'query_string': query_string,\n })\n else:\n return render(request, 'wagtailsearch/editorspicks/index.html', {\n 'is_searching': is_searching,\n 'queries': queries,\n 'query_string': query_string,\n 'search_form': SearchForm(data=dict(q=query_string) if query_string else None, placeholder=_(\"Search editor's picks\")),\n })\n\n\ndef save_editorspicks(query, new_query, editors_pick_formset):\n # Save\n if editors_pick_formset.is_valid():\n # Set sort_order\n for i, form in enumerate(editors_pick_formset.ordered_forms):\n form.instance.sort_order = i\n\n editors_pick_formset.save()\n\n # If query was changed, move all editors picks to the new query\n if query != new_query:\n editors_pick_formset.get_queryset().update(query=new_query)\n\n return True\n else:\n return False\n\n\n@permission_required('wagtailadmin.access_admin')\ndef add(request):\n if request.POST:\n # Get query\n query_form = forms.QueryForm(request.POST)\n if query_form.is_valid():\n query = models.Query.get(query_form['query_string'].value())\n\n # Save editors picks\n editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)\n if save_editorspicks(query, query, editors_pick_formset):\n messages.success(request, _(\"Editor's picks for '{0}' created.\").format(query))\n return redirect('wagtailsearch_editorspicks_index')\n else:\n if len(editors_pick_formset.non_form_errors()):\n messages.error(request, \" \".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted)\n else:\n messages.error(request, _(\"Recommendations have not been created due to errors\")) # specific errors will be displayed within form fields\n else:\n editors_pick_formset = forms.EditorsPickFormSet()\n else:\n query_form = forms.QueryForm()\n editors_pick_formset = forms.EditorsPickFormSet()\n\n return render(request, 'wagtailsearch/editorspicks/add.html', {\n 'query_form': query_form,\n 'editors_pick_formset': editors_pick_formset,\n })\n\n\n@permission_required('wagtailadmin.access_admin')\ndef edit(request, query_id):\n query = get_object_or_404(models.Query, id=query_id)\n\n if request.POST:\n # Get query\n query_form = forms.QueryForm(request.POST)\n # and the recommendations\n editors_pick_formset = forms.EditorsPickFormSet(request.POST, instance=query)\n\n if query_form.is_valid():\n new_query = models.Query.get(query_form['query_string'].value())\n\n # Save editors picks\n if save_editorspicks(query, new_query, editors_pick_formset):\n messages.success(request, _(\"Editor's picks for '{0}' updated.\").format(new_query))\n return redirect('wagtailsearch_editorspicks_index')\n else:\n if len(editors_pick_formset.non_form_errors()):\n messages.error(request, \" \".join(error for error in editors_pick_formset.non_form_errors())) # formset level error (e.g. no forms submitted)\n else:\n messages.error(request, _(\"Recommendations have not been saved due to errors\")) # specific errors will be displayed within form fields\n\n else:\n query_form = forms.QueryForm(initial=dict(query_string=query.query_string))\n editors_pick_formset = forms.EditorsPickFormSet(instance=query)\n\n return render(request, 'wagtailsearch/editorspicks/edit.html', {\n 'query_form': query_form,\n 'editors_pick_formset': editors_pick_formset,\n 'query': query,\n })\n\n\n@permission_required('wagtailadmin.access_admin')\ndef delete(request, query_id):\n query = get_object_or_404(models.Query, id=query_id)\n\n if request.POST:\n query.editors_picks.all().delete()\n messages.success(request, _(\"Editor's picks deleted.\"))\n return redirect('wagtailsearch_editorspicks_index')\n\n return render(request, 'wagtailsearch/editorspicks/confirm_delete.html', {\n 'query': query,\n })\n", "path": "wagtail/wagtailsearch/views/editorspicks.py"}]}
1,820
326
gh_patches_debug_686
rasdani/github-patches
git_diff
projectmesa__mesa-398
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- error launching Flocker I've Anaconda with python 3.6 & Mesa 0.8.1 I launch Flocker's run.py and I get this error: ``` Flockers e$ python run.py Traceback (most recent call last): File "run.py", line 1, in <module> from flockers.server import server File "/Users/e/Dropbox/devlib/notebooks/mesa-master/examples/Flockers/flockers/server.py", line 20, in <module> server = ModularServer(BoidModel, [boid_canvas], "Boids", model_params) File "/Users/e/anaconda3/lib/python3.6/site-packages/mesa/visualization/ModularVisualization.py", line 287, in __init__ self.reset_model() File "/Users/e/anaconda3/lib/python3.6/site-packages/mesa/visualization/ModularVisualization.py", line 313, in reset_model self.model = self.model_cls(**model_params) TypeError: __init__() got an unexpected keyword argument 'N' ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `examples/Flockers/flockers/server.py` Content: ``` 1 from mesa.visualization.ModularVisualization import ModularServer 2 3 from .model import BoidModel 4 from .SimpleContinuousModule import SimpleCanvas 5 6 7 def boid_draw(agent): 8 return {"Shape": "circle", "r": 2, "Filled": "true", "Color": "Red"} 9 10 boid_canvas = SimpleCanvas(boid_draw, 500, 500) 11 model_params = { 12 "N": 100, 13 "width": 100, 14 "height": 100, 15 "speed": 5, 16 "vision": 10, 17 "separation": 2 18 } 19 20 server = ModularServer(BoidModel, [boid_canvas], "Boids", model_params) 21 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/examples/Flockers/flockers/server.py b/examples/Flockers/flockers/server.py --- a/examples/Flockers/flockers/server.py +++ b/examples/Flockers/flockers/server.py @@ -9,7 +9,7 @@ boid_canvas = SimpleCanvas(boid_draw, 500, 500) model_params = { - "N": 100, + "population": 100, "width": 100, "height": 100, "speed": 5,
{"golden_diff": "diff --git a/examples/Flockers/flockers/server.py b/examples/Flockers/flockers/server.py\n--- a/examples/Flockers/flockers/server.py\n+++ b/examples/Flockers/flockers/server.py\n@@ -9,7 +9,7 @@\n \n boid_canvas = SimpleCanvas(boid_draw, 500, 500)\n model_params = {\n- \"N\": 100,\n+ \"population\": 100,\n \"width\": 100,\n \"height\": 100,\n \"speed\": 5,\n", "issue": "error launching Flocker\nI've Anaconda with python 3.6 & Mesa 0.8.1\r\n\r\nI launch Flocker's run.py and I get this error:\r\n```\r\nFlockers e$ python run.py\r\nTraceback (most recent call last):\r\n File \"run.py\", line 1, in <module>\r\n from flockers.server import server\r\n File \"/Users/e/Dropbox/devlib/notebooks/mesa-master/examples/Flockers/flockers/server.py\", line 20, in <module>\r\n server = ModularServer(BoidModel, [boid_canvas], \"Boids\", model_params)\r\n File \"/Users/e/anaconda3/lib/python3.6/site-packages/mesa/visualization/ModularVisualization.py\", line 287, in __init__\r\n self.reset_model()\r\n File \"/Users/e/anaconda3/lib/python3.6/site-packages/mesa/visualization/ModularVisualization.py\", line 313, in reset_model\r\n self.model = self.model_cls(**model_params)\r\nTypeError: __init__() got an unexpected keyword argument 'N'\r\n```\n", "before_files": [{"content": "from mesa.visualization.ModularVisualization import ModularServer\n\nfrom .model import BoidModel\nfrom .SimpleContinuousModule import SimpleCanvas\n\n\ndef boid_draw(agent):\n return {\"Shape\": \"circle\", \"r\": 2, \"Filled\": \"true\", \"Color\": \"Red\"}\n\nboid_canvas = SimpleCanvas(boid_draw, 500, 500)\nmodel_params = {\n \"N\": 100,\n \"width\": 100,\n \"height\": 100,\n \"speed\": 5,\n \"vision\": 10,\n \"separation\": 2\n}\n\nserver = ModularServer(BoidModel, [boid_canvas], \"Boids\", model_params)\n", "path": "examples/Flockers/flockers/server.py"}], "after_files": [{"content": "from mesa.visualization.ModularVisualization import ModularServer\n\nfrom .model import BoidModel\nfrom .SimpleContinuousModule import SimpleCanvas\n\n\ndef boid_draw(agent):\n return {\"Shape\": \"circle\", \"r\": 2, \"Filled\": \"true\", \"Color\": \"Red\"}\n\nboid_canvas = SimpleCanvas(boid_draw, 500, 500)\nmodel_params = {\n \"population\": 100,\n \"width\": 100,\n \"height\": 100,\n \"speed\": 5,\n \"vision\": 10,\n \"separation\": 2\n}\n\nserver = ModularServer(BoidModel, [boid_canvas], \"Boids\", model_params)\n", "path": "examples/Flockers/flockers/server.py"}]}
692
128
gh_patches_debug_39717
rasdani/github-patches
git_diff
kserve__kserve-156
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- KFServing should have a consistent way of supporting model download across inference server implementations /kind feature **Describe the solution you'd like** KFServing should expose a consistent way to download models across inference servers and clouds. The current implementation depends on the features of individual inference servers expose. E.g. see #137 **Anything else you would like to add:** Proposed solution design is documented here: https://docs.google.com/document/d/1xqBOkoQ6Vzc5gv4O5MgVVNE3qILbKuMkC-DN5zp5w28/edit?usp=sharing --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `python/kfserving/kfserving/storage.py` Content: ``` 1 # Copyright 2019 kubeflow.org. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 import logging 16 import tempfile 17 import os 18 import re 19 from minio import Minio 20 from google.cloud import storage 21 from google.auth import exceptions 22 23 _GCS_PREFIX = "gs://" 24 _S3_PREFIX = "s3://" 25 _LOCAL_PREFIX = "file://" 26 27 28 class Storage(object): # pylint: disable=too-few-public-methods 29 @staticmethod 30 def download(uri: str) -> str: 31 logging.info("Copying contents of %s to local", uri) 32 if uri.startswith(_LOCAL_PREFIX) or os.path.exists(uri): 33 return Storage._download_local(uri) 34 35 temp_dir = tempfile.mkdtemp() 36 if uri.startswith(_GCS_PREFIX): 37 Storage._download_gcs(uri, temp_dir) 38 elif uri.startswith(_S3_PREFIX): 39 Storage._download_s3(uri, temp_dir) 40 else: 41 raise Exception("Cannot recognize storage type for " + uri + 42 "\n'%s', '%s', and '%s' are the current available storage type." % 43 (_GCS_PREFIX, _S3_PREFIX, _LOCAL_PREFIX)) 44 45 logging.info("Successfully copied %s to %s", uri, temp_dir) 46 return temp_dir 47 48 @staticmethod 49 def _download_s3(uri, temp_dir: str): 50 client = Storage._create_minio_client() 51 bucket_args = uri.replace(_S3_PREFIX, "", 1).split("/", 1) 52 bucket_name = bucket_args[0] 53 bucket_path = bucket_args[1] if len(bucket_args) > 1 else "" 54 objects = client.list_objects(bucket_name, prefix=bucket_path, recursive=True) 55 for obj in objects: 56 # Replace any prefix from the object key with temp_dir 57 subdir_object_key = obj.object_name.replace(bucket_path, "", 1).strip("/") 58 client.fget_object(bucket_name, obj.object_name, 59 os.path.join(temp_dir, subdir_object_key)) 60 61 @staticmethod 62 def _download_gcs(uri, temp_dir: str): 63 try: 64 storage_client = storage.Client() 65 except exceptions.DefaultCredentialsError: 66 storage_client = storage.Client.create_anonymous_client() 67 bucket_args = uri.replace(_GCS_PREFIX, "", 1).split("/", 1) 68 bucket_name = bucket_args[0] 69 bucket_path = bucket_args[1] if len(bucket_args) > 1 else "" 70 bucket = storage_client.bucket(bucket_name) 71 blobs = bucket.list_blobs(prefix=bucket_path) 72 for blob in blobs: 73 # Replace any prefix from the object key with temp_dir 74 subdir_object_key = blob.name.replace(bucket_path, "", 1).strip("/") 75 # Create necessary subdirectory to store the object locally 76 if "/" in subdir_object_key: 77 local_object_dir = os.path.join(temp_dir, subdir_object_key.rsplit("/", 1)[0]) 78 if not os.path.isdir(local_object_dir): 79 os.makedirs(local_object_dir, exist_ok=True) 80 blob.download_to_filename(os.path.join(temp_dir, subdir_object_key)) 81 82 @staticmethod 83 def _download_local(uri): 84 local_path = uri.replace(_LOCAL_PREFIX, "", 1) 85 if not os.path.exists(local_path): 86 raise Exception("Local path %s does not exist." % (uri)) 87 return local_path 88 89 @staticmethod 90 def _create_minio_client(): 91 # Remove possible http scheme for Minio 92 url = re.compile(r"https?://") 93 minioClient = Minio(url.sub("", os.getenv("S3_ENDPOINT", "")), 94 access_key=os.getenv("AWS_ACCESS_KEY_ID", ""), 95 secret_key=os.getenv("AWS_SECRET_ACCESS_KEY", ""), 96 secure=True) 97 return minioClient 98 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/python/kfserving/kfserving/storage.py b/python/kfserving/kfserving/storage.py --- a/python/kfserving/kfserving/storage.py +++ b/python/kfserving/kfserving/storage.py @@ -27,23 +27,25 @@ class Storage(object): # pylint: disable=too-few-public-methods @staticmethod - def download(uri: str) -> str: + def download(uri: str, out_dir: str = None) -> str: logging.info("Copying contents of %s to local", uri) if uri.startswith(_LOCAL_PREFIX) or os.path.exists(uri): return Storage._download_local(uri) - temp_dir = tempfile.mkdtemp() + if out_dir is None: + out_dir = tempfile.mkdtemp() + if uri.startswith(_GCS_PREFIX): - Storage._download_gcs(uri, temp_dir) + Storage._download_gcs(uri, out_dir) elif uri.startswith(_S3_PREFIX): - Storage._download_s3(uri, temp_dir) + Storage._download_s3(uri, out_dir) else: raise Exception("Cannot recognize storage type for " + uri + "\n'%s', '%s', and '%s' are the current available storage type." % (_GCS_PREFIX, _S3_PREFIX, _LOCAL_PREFIX)) - logging.info("Successfully copied %s to %s", uri, temp_dir) - return temp_dir + logging.info("Successfully copied %s to %s", uri, out_dir) + return out_dir @staticmethod def _download_s3(uri, temp_dir: str): @@ -68,16 +70,23 @@ bucket_name = bucket_args[0] bucket_path = bucket_args[1] if len(bucket_args) > 1 else "" bucket = storage_client.bucket(bucket_name) - blobs = bucket.list_blobs(prefix=bucket_path) + prefix = bucket_path + if not prefix.endswith("/"): + prefix = prefix + "/" + blobs = bucket.list_blobs(prefix=prefix) for blob in blobs: # Replace any prefix from the object key with temp_dir subdir_object_key = blob.name.replace(bucket_path, "", 1).strip("/") + # Create necessary subdirectory to store the object locally if "/" in subdir_object_key: local_object_dir = os.path.join(temp_dir, subdir_object_key.rsplit("/", 1)[0]) if not os.path.isdir(local_object_dir): os.makedirs(local_object_dir, exist_ok=True) - blob.download_to_filename(os.path.join(temp_dir, subdir_object_key)) + if subdir_object_key.strip() != "": + dest_path = os.path.join(temp_dir, subdir_object_key) + logging.info("Downloading: %s", dest_path) + blob.download_to_filename(dest_path) @staticmethod def _download_local(uri):
{"golden_diff": "diff --git a/python/kfserving/kfserving/storage.py b/python/kfserving/kfserving/storage.py\n--- a/python/kfserving/kfserving/storage.py\n+++ b/python/kfserving/kfserving/storage.py\n@@ -27,23 +27,25 @@\n \n class Storage(object): # pylint: disable=too-few-public-methods\n @staticmethod\n- def download(uri: str) -> str:\n+ def download(uri: str, out_dir: str = None) -> str:\n logging.info(\"Copying contents of %s to local\", uri)\n if uri.startswith(_LOCAL_PREFIX) or os.path.exists(uri):\n return Storage._download_local(uri)\n \n- temp_dir = tempfile.mkdtemp()\n+ if out_dir is None:\n+ out_dir = tempfile.mkdtemp()\n+\n if uri.startswith(_GCS_PREFIX):\n- Storage._download_gcs(uri, temp_dir)\n+ Storage._download_gcs(uri, out_dir)\n elif uri.startswith(_S3_PREFIX):\n- Storage._download_s3(uri, temp_dir)\n+ Storage._download_s3(uri, out_dir)\n else:\n raise Exception(\"Cannot recognize storage type for \" + uri +\n \"\\n'%s', '%s', and '%s' are the current available storage type.\" %\n (_GCS_PREFIX, _S3_PREFIX, _LOCAL_PREFIX))\n \n- logging.info(\"Successfully copied %s to %s\", uri, temp_dir)\n- return temp_dir\n+ logging.info(\"Successfully copied %s to %s\", uri, out_dir)\n+ return out_dir\n \n @staticmethod\n def _download_s3(uri, temp_dir: str):\n@@ -68,16 +70,23 @@\n bucket_name = bucket_args[0]\n bucket_path = bucket_args[1] if len(bucket_args) > 1 else \"\"\n bucket = storage_client.bucket(bucket_name)\n- blobs = bucket.list_blobs(prefix=bucket_path)\n+ prefix = bucket_path\n+ if not prefix.endswith(\"/\"):\n+ prefix = prefix + \"/\"\n+ blobs = bucket.list_blobs(prefix=prefix)\n for blob in blobs:\n # Replace any prefix from the object key with temp_dir\n subdir_object_key = blob.name.replace(bucket_path, \"\", 1).strip(\"/\")\n+\n # Create necessary subdirectory to store the object locally\n if \"/\" in subdir_object_key:\n local_object_dir = os.path.join(temp_dir, subdir_object_key.rsplit(\"/\", 1)[0])\n if not os.path.isdir(local_object_dir):\n os.makedirs(local_object_dir, exist_ok=True)\n- blob.download_to_filename(os.path.join(temp_dir, subdir_object_key))\n+ if subdir_object_key.strip() != \"\":\n+ dest_path = os.path.join(temp_dir, subdir_object_key)\n+ logging.info(\"Downloading: %s\", dest_path)\n+ blob.download_to_filename(dest_path)\n \n @staticmethod\n def _download_local(uri):\n", "issue": "KFServing should have a consistent way of supporting model download across inference server implementations\n/kind feature\r\n\r\n**Describe the solution you'd like**\r\nKFServing should expose a consistent way to download models across inference servers and clouds. The current implementation depends on the features of individual inference servers expose. E.g. see #137 \r\n\r\n**Anything else you would like to add:**\r\nProposed solution design is documented here: https://docs.google.com/document/d/1xqBOkoQ6Vzc5gv4O5MgVVNE3qILbKuMkC-DN5zp5w28/edit?usp=sharing\r\n\n", "before_files": [{"content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport tempfile\nimport os\nimport re\nfrom minio import Minio\nfrom google.cloud import storage\nfrom google.auth import exceptions\n\n_GCS_PREFIX = \"gs://\"\n_S3_PREFIX = \"s3://\"\n_LOCAL_PREFIX = \"file://\"\n\n\nclass Storage(object): # pylint: disable=too-few-public-methods\n @staticmethod\n def download(uri: str) -> str:\n logging.info(\"Copying contents of %s to local\", uri)\n if uri.startswith(_LOCAL_PREFIX) or os.path.exists(uri):\n return Storage._download_local(uri)\n\n temp_dir = tempfile.mkdtemp()\n if uri.startswith(_GCS_PREFIX):\n Storage._download_gcs(uri, temp_dir)\n elif uri.startswith(_S3_PREFIX):\n Storage._download_s3(uri, temp_dir)\n else:\n raise Exception(\"Cannot recognize storage type for \" + uri +\n \"\\n'%s', '%s', and '%s' are the current available storage type.\" %\n (_GCS_PREFIX, _S3_PREFIX, _LOCAL_PREFIX))\n\n logging.info(\"Successfully copied %s to %s\", uri, temp_dir)\n return temp_dir\n\n @staticmethod\n def _download_s3(uri, temp_dir: str):\n client = Storage._create_minio_client()\n bucket_args = uri.replace(_S3_PREFIX, \"\", 1).split(\"/\", 1)\n bucket_name = bucket_args[0]\n bucket_path = bucket_args[1] if len(bucket_args) > 1 else \"\"\n objects = client.list_objects(bucket_name, prefix=bucket_path, recursive=True)\n for obj in objects:\n # Replace any prefix from the object key with temp_dir\n subdir_object_key = obj.object_name.replace(bucket_path, \"\", 1).strip(\"/\")\n client.fget_object(bucket_name, obj.object_name,\n os.path.join(temp_dir, subdir_object_key))\n\n @staticmethod\n def _download_gcs(uri, temp_dir: str):\n try:\n storage_client = storage.Client()\n except exceptions.DefaultCredentialsError:\n storage_client = storage.Client.create_anonymous_client()\n bucket_args = uri.replace(_GCS_PREFIX, \"\", 1).split(\"/\", 1)\n bucket_name = bucket_args[0]\n bucket_path = bucket_args[1] if len(bucket_args) > 1 else \"\"\n bucket = storage_client.bucket(bucket_name)\n blobs = bucket.list_blobs(prefix=bucket_path)\n for blob in blobs:\n # Replace any prefix from the object key with temp_dir\n subdir_object_key = blob.name.replace(bucket_path, \"\", 1).strip(\"/\")\n # Create necessary subdirectory to store the object locally\n if \"/\" in subdir_object_key:\n local_object_dir = os.path.join(temp_dir, subdir_object_key.rsplit(\"/\", 1)[0])\n if not os.path.isdir(local_object_dir):\n os.makedirs(local_object_dir, exist_ok=True)\n blob.download_to_filename(os.path.join(temp_dir, subdir_object_key))\n\n @staticmethod\n def _download_local(uri):\n local_path = uri.replace(_LOCAL_PREFIX, \"\", 1)\n if not os.path.exists(local_path):\n raise Exception(\"Local path %s does not exist.\" % (uri))\n return local_path\n\n @staticmethod\n def _create_minio_client():\n # Remove possible http scheme for Minio\n url = re.compile(r\"https?://\")\n minioClient = Minio(url.sub(\"\", os.getenv(\"S3_ENDPOINT\", \"\")),\n access_key=os.getenv(\"AWS_ACCESS_KEY_ID\", \"\"),\n secret_key=os.getenv(\"AWS_SECRET_ACCESS_KEY\", \"\"),\n secure=True)\n return minioClient\n", "path": "python/kfserving/kfserving/storage.py"}], "after_files": [{"content": "# Copyright 2019 kubeflow.org.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport tempfile\nimport os\nimport re\nfrom minio import Minio\nfrom google.cloud import storage\nfrom google.auth import exceptions\n\n_GCS_PREFIX = \"gs://\"\n_S3_PREFIX = \"s3://\"\n_LOCAL_PREFIX = \"file://\"\n\n\nclass Storage(object): # pylint: disable=too-few-public-methods\n @staticmethod\n def download(uri: str, out_dir: str = None) -> str:\n logging.info(\"Copying contents of %s to local\", uri)\n if uri.startswith(_LOCAL_PREFIX) or os.path.exists(uri):\n return Storage._download_local(uri)\n\n if out_dir is None:\n out_dir = tempfile.mkdtemp()\n\n if uri.startswith(_GCS_PREFIX):\n Storage._download_gcs(uri, out_dir)\n elif uri.startswith(_S3_PREFIX):\n Storage._download_s3(uri, out_dir)\n else:\n raise Exception(\"Cannot recognize storage type for \" + uri +\n \"\\n'%s', '%s', and '%s' are the current available storage type.\" %\n (_GCS_PREFIX, _S3_PREFIX, _LOCAL_PREFIX))\n\n logging.info(\"Successfully copied %s to %s\", uri, out_dir)\n return out_dir\n\n @staticmethod\n def _download_s3(uri, temp_dir: str):\n client = Storage._create_minio_client()\n bucket_args = uri.replace(_S3_PREFIX, \"\", 1).split(\"/\", 1)\n bucket_name = bucket_args[0]\n bucket_path = bucket_args[1] if len(bucket_args) > 1 else \"\"\n objects = client.list_objects(bucket_name, prefix=bucket_path, recursive=True)\n for obj in objects:\n # Replace any prefix from the object key with temp_dir\n subdir_object_key = obj.object_name.replace(bucket_path, \"\", 1).strip(\"/\")\n client.fget_object(bucket_name, obj.object_name,\n os.path.join(temp_dir, subdir_object_key))\n\n @staticmethod\n def _download_gcs(uri, temp_dir: str):\n try:\n storage_client = storage.Client()\n except exceptions.DefaultCredentialsError:\n storage_client = storage.Client.create_anonymous_client()\n bucket_args = uri.replace(_GCS_PREFIX, \"\", 1).split(\"/\", 1)\n bucket_name = bucket_args[0]\n bucket_path = bucket_args[1] if len(bucket_args) > 1 else \"\"\n bucket = storage_client.bucket(bucket_name)\n prefix = bucket_path\n if not prefix.endswith(\"/\"):\n prefix = prefix + \"/\"\n blobs = bucket.list_blobs(prefix=prefix)\n for blob in blobs:\n # Replace any prefix from the object key with temp_dir\n subdir_object_key = blob.name.replace(bucket_path, \"\", 1).strip(\"/\")\n\n # Create necessary subdirectory to store the object locally\n if \"/\" in subdir_object_key:\n local_object_dir = os.path.join(temp_dir, subdir_object_key.rsplit(\"/\", 1)[0])\n if not os.path.isdir(local_object_dir):\n os.makedirs(local_object_dir, exist_ok=True)\n if subdir_object_key.strip() != \"\":\n dest_path = os.path.join(temp_dir, subdir_object_key)\n logging.info(\"Downloading: %s\", dest_path)\n blob.download_to_filename(dest_path)\n\n @staticmethod\n def _download_local(uri):\n local_path = uri.replace(_LOCAL_PREFIX, \"\", 1)\n if not os.path.exists(local_path):\n raise Exception(\"Local path %s does not exist.\" % (uri))\n return local_path\n\n @staticmethod\n def _create_minio_client():\n # Remove possible http scheme for Minio\n url = re.compile(r\"https?://\")\n minioClient = Minio(url.sub(\"\", os.getenv(\"S3_ENDPOINT\", \"\")),\n access_key=os.getenv(\"AWS_ACCESS_KEY_ID\", \"\"),\n secret_key=os.getenv(\"AWS_SECRET_ACCESS_KEY\", \"\"),\n secure=True)\n return minioClient\n", "path": "python/kfserving/kfserving/storage.py"}]}
1,496
635
gh_patches_debug_11230
rasdani/github-patches
git_diff
spack__spack-12009
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Installation issue: py-jsonchema (No checksum provided for @2.6.0 requested by nrm) The nrm package specifically requests [email protected]. Attempting to install this package results in the following error: ==> Warning: There is no checksum on file to fetch [email protected] safely. ==> Error: Will not fetch [email protected] Add a checksum or use --no-checksum to skip this check. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `var/spack/repos/builtin/packages/py-jsonschema/package.py` Content: ``` 1 # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other 2 # Spack Project Developers. See the top-level COPYRIGHT file for details. 3 # 4 # SPDX-License-Identifier: (Apache-2.0 OR MIT) 5 6 from spack import * 7 8 9 class PyJsonschema(PythonPackage): 10 """Jsonschema: An(other) implementation of JSON Schema for Python.""" 11 12 homepage = "http://github.com/Julian/jsonschema" 13 url = "https://pypi.io/packages/source/j/jsonschema/jsonschema-2.5.1.tar.gz" 14 15 version('2.5.1', '374e848fdb69a3ce8b7e778b47c30640') 16 17 depends_on('py-setuptools', type='build') 18 depends_on('py-vcversioner', type=('build', 'run')) 19 depends_on('py-functools32', when="^[email protected]:2.7.999", type=('build', 'run')) 20 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/var/spack/repos/builtin/packages/py-jsonschema/package.py b/var/spack/repos/builtin/packages/py-jsonschema/package.py --- a/var/spack/repos/builtin/packages/py-jsonschema/package.py +++ b/var/spack/repos/builtin/packages/py-jsonschema/package.py @@ -10,8 +10,9 @@ """Jsonschema: An(other) implementation of JSON Schema for Python.""" homepage = "http://github.com/Julian/jsonschema" - url = "https://pypi.io/packages/source/j/jsonschema/jsonschema-2.5.1.tar.gz" + url = "https://pypi.io/packages/source/j/jsonschema/jsonschema-2.6.0.tar.gz" + version('2.6.0', sha256='6ff5f3180870836cae40f06fa10419f557208175f13ad7bc26caa77beb1f6e02') version('2.5.1', '374e848fdb69a3ce8b7e778b47c30640') depends_on('py-setuptools', type='build')
{"golden_diff": "diff --git a/var/spack/repos/builtin/packages/py-jsonschema/package.py b/var/spack/repos/builtin/packages/py-jsonschema/package.py\n--- a/var/spack/repos/builtin/packages/py-jsonschema/package.py\n+++ b/var/spack/repos/builtin/packages/py-jsonschema/package.py\n@@ -10,8 +10,9 @@\n \"\"\"Jsonschema: An(other) implementation of JSON Schema for Python.\"\"\"\n \n homepage = \"http://github.com/Julian/jsonschema\"\n- url = \"https://pypi.io/packages/source/j/jsonschema/jsonschema-2.5.1.tar.gz\"\n+ url = \"https://pypi.io/packages/source/j/jsonschema/jsonschema-2.6.0.tar.gz\"\n \n+ version('2.6.0', sha256='6ff5f3180870836cae40f06fa10419f557208175f13ad7bc26caa77beb1f6e02')\n version('2.5.1', '374e848fdb69a3ce8b7e778b47c30640')\n \n depends_on('py-setuptools', type='build')\n", "issue": "Installation issue: py-jsonchema (No checksum provided for @2.6.0 requested by nrm)\nThe nrm package specifically requests [email protected]. Attempting to install this package results in the following error:\r\n\r\n==> Warning: There is no checksum on file to fetch [email protected] safely.\r\n==> Error: Will not fetch [email protected]\r\nAdd a checksum or use --no-checksum to skip this check.\r\n\n", "before_files": [{"content": "# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass PyJsonschema(PythonPackage):\n \"\"\"Jsonschema: An(other) implementation of JSON Schema for Python.\"\"\"\n\n homepage = \"http://github.com/Julian/jsonschema\"\n url = \"https://pypi.io/packages/source/j/jsonschema/jsonschema-2.5.1.tar.gz\"\n\n version('2.5.1', '374e848fdb69a3ce8b7e778b47c30640')\n\n depends_on('py-setuptools', type='build')\n depends_on('py-vcversioner', type=('build', 'run'))\n depends_on('py-functools32', when=\"^[email protected]:2.7.999\", type=('build', 'run'))\n", "path": "var/spack/repos/builtin/packages/py-jsonschema/package.py"}], "after_files": [{"content": "# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass PyJsonschema(PythonPackage):\n \"\"\"Jsonschema: An(other) implementation of JSON Schema for Python.\"\"\"\n\n homepage = \"http://github.com/Julian/jsonschema\"\n url = \"https://pypi.io/packages/source/j/jsonschema/jsonschema-2.6.0.tar.gz\"\n\n version('2.6.0', sha256='6ff5f3180870836cae40f06fa10419f557208175f13ad7bc26caa77beb1f6e02')\n version('2.5.1', '374e848fdb69a3ce8b7e778b47c30640')\n\n depends_on('py-setuptools', type='build')\n depends_on('py-vcversioner', type=('build', 'run'))\n depends_on('py-functools32', when=\"^[email protected]:2.7.999\", type=('build', 'run'))\n", "path": "var/spack/repos/builtin/packages/py-jsonschema/package.py"}]}
633
280
gh_patches_debug_25167
rasdani/github-patches
git_diff
aws-cloudformation__cfn-lint-2057
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Incorrect E1029 errors when literal YAML block style is used *cfn-lint version: 0.51.0 Embedded parameters are being flagged for not being wrapped in a `!Sub`, but they are in fact wrapped in a `!Sub`. Please provide as much information as possible: Sample template (extraneous lines have been removed): ```yaml Resources: SomeStackset: Type: AWS::CloudFormation::StackSet Properties: TemplateBody: | Resources: SomeRole: Type: AWS::IAM::Role Properties: Policies: - PolicyName: SomeName PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - iam:GetSomething Resource: - !Sub arn:aws:iam::${AWS::AccountId}:role/SomeRole* ``` The error is an [E1029](https://github.com/aws-cloudformation/cfn-lint/blob/main/src/cfnlint/rules/functions/SubNeeded.py), and the line number referenced is the line number where the YAML literal appears (here, the line that contains `TemplateBody: |`) This appears to be a new issue with [release 0.51.0](https://github.com/aws-cloudformation/cfn-lint/releases/tag/v0.51.0). The code in question above hasn't changed in my repo for a long time, and I don't get the error on previous releases. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/cfnlint/rules/functions/SubNeeded.py` Content: ``` 1 """ 2 Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 SPDX-License-Identifier: MIT-0 4 """ 5 from functools import reduce # pylint: disable=redefined-builtin 6 import re 7 import copy 8 import six 9 from cfnlint.rules import CloudFormationLintRule 10 from cfnlint.rules import RuleMatch 11 12 13 class SubNeeded(CloudFormationLintRule): 14 """Check if a substitution string exists without a substitution function""" 15 id = 'E1029' 16 shortdesc = 'Sub is required if a variable is used in a string' 17 description = 'If a substitution variable exists in a string but isn\'t wrapped with the Fn::Sub function the deployment will fail.' 18 source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' 19 tags = ['functions', 'sub'] 20 21 def __init__(self): 22 """Init""" 23 super(SubNeeded, self).__init__() 24 self.config_definition = { 25 'custom_excludes': { 26 'default': '', 27 'type': 'string' 28 } 29 } 30 self.configure() 31 self.subParameterRegex = re.compile(r'(\$\{[A-Za-z0-9_:\.]+\})') 32 33 def _match_values(self, cfnelem, path): 34 """Recursively search for values matching the searchRegex""" 35 values = [] 36 if isinstance(cfnelem, dict): 37 for key in cfnelem: 38 pathprop = path[:] 39 pathprop.append(key) 40 values.extend(self._match_values(cfnelem[key], pathprop)) 41 elif isinstance(cfnelem, list): 42 for index, item in enumerate(cfnelem): 43 pathprop = path[:] 44 pathprop.append(index) 45 values.extend(self._match_values(item, pathprop)) 46 else: 47 # Leaf node 48 if isinstance(cfnelem, six.string_types): # and re.match(searchRegex, cfnelem): 49 for variable in re.findall(self.subParameterRegex, cfnelem): 50 values.append(path + [variable]) 51 52 return values 53 54 def match_values(self, cfn): 55 """ 56 Search for values in all parts of the templates that match the searchRegex 57 """ 58 results = [] 59 results.extend(self._match_values(cfn.template, [])) 60 # Globals are removed during a transform. They need to be checked manually 61 results.extend(self._match_values(cfn.template.get('Globals', {}), [])) 62 return results 63 64 def _api_exceptions(self, value): 65 """ Key value exceptions """ 66 parameter_search = re.compile(r'^\$\{stageVariables\..*\}$') 67 return re.match(parameter_search, value) 68 69 def _variable_custom_excluded(self, value): 70 """ User-defined exceptions for variables, anywhere in the file """ 71 custom_excludes = self.config['custom_excludes'] 72 if custom_excludes: 73 custom_search = re.compile(custom_excludes) 74 return re.match(custom_search, value) 75 return False 76 77 def match(self, cfn): 78 matches = [] 79 80 refs = cfn.get_valid_refs() 81 getatts = cfn.get_valid_getatts() 82 83 # Get a list of paths to every leaf node string containing at least one ${parameter} 84 parameter_string_paths = self.match_values(cfn) 85 # We want to search all of the paths to check if each one contains an 'Fn::Sub' 86 for parameter_string_path in parameter_string_paths: 87 # Get variable 88 var = parameter_string_path[-1] 89 90 # Step Function State Machine has a Definition Substitution that allows usage of special variables outside of a !Sub 91 # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-definitionsubstitutions.html 92 93 if 'DefinitionString' in parameter_string_path: 94 modified_parameter_string_path = copy.copy(parameter_string_path) 95 index = parameter_string_path.index('DefinitionString') 96 modified_parameter_string_path[index] = 'DefinitionSubstitutions' 97 modified_parameter_string_path = modified_parameter_string_path[:index+1] 98 modified_parameter_string_path.append(var[2:-1]) 99 if reduce(lambda c, k: c.get(k, {}), modified_parameter_string_path, cfn.template): 100 continue 101 102 # Exclude variables that match custom exclude filters, if configured 103 # (for third-party tools that pre-process templates before uploading them to AWS) 104 if self._variable_custom_excluded(var): 105 continue 106 107 # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html) 108 if var.startswith('${!'): 109 continue 110 111 var_stripped = var[2:-1].strip() 112 113 # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly 114 if not 'Fn::Sub' in parameter_string_path: 115 if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path: 116 # Remove the last item (the variable) to prevent multiple errors on 1 line errors 117 path = parameter_string_path[:-1] 118 message = 'Found an embedded parameter "{}" outside of an "Fn::Sub" at {}'.format( 119 var, '/'.join(map(str, path))) 120 matches.append(RuleMatch(path, message)) 121 122 return matches 123 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py --- a/src/cfnlint/rules/functions/SubNeeded.py +++ b/src/cfnlint/rules/functions/SubNeeded.py @@ -18,6 +18,8 @@ source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html' tags = ['functions', 'sub'] + exceptions = ['TemplateBody'] + def __init__(self): """Init""" super(SubNeeded, self).__init__() @@ -111,7 +113,7 @@ var_stripped = var[2:-1].strip() # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly - if not 'Fn::Sub' in parameter_string_path: + if not 'Fn::Sub' in parameter_string_path and parameter_string_path[-2] not in self.exceptions: if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path: # Remove the last item (the variable) to prevent multiple errors on 1 line errors path = parameter_string_path[:-1]
{"golden_diff": "diff --git a/src/cfnlint/rules/functions/SubNeeded.py b/src/cfnlint/rules/functions/SubNeeded.py\n--- a/src/cfnlint/rules/functions/SubNeeded.py\n+++ b/src/cfnlint/rules/functions/SubNeeded.py\n@@ -18,6 +18,8 @@\n source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html'\n tags = ['functions', 'sub']\n \n+ exceptions = ['TemplateBody']\n+\n def __init__(self):\n \"\"\"Init\"\"\"\n super(SubNeeded, self).__init__()\n@@ -111,7 +113,7 @@\n var_stripped = var[2:-1].strip()\n \n # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly\n- if not 'Fn::Sub' in parameter_string_path:\n+ if not 'Fn::Sub' in parameter_string_path and parameter_string_path[-2] not in self.exceptions:\n if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path:\n # Remove the last item (the variable) to prevent multiple errors on 1 line errors\n path = parameter_string_path[:-1]\n", "issue": "Incorrect E1029 errors when literal YAML block style is used\n*cfn-lint version: 0.51.0\r\n\r\nEmbedded parameters are being flagged for not being wrapped in a `!Sub`, but they are in fact wrapped in a `!Sub`.\r\n\r\nPlease provide as much information as possible:\r\n\r\nSample template (extraneous lines have been removed):\r\n```yaml\r\nResources:\r\n SomeStackset:\r\n Type: AWS::CloudFormation::StackSet\r\n Properties:\r\n TemplateBody: |\r\n Resources:\r\n SomeRole:\r\n Type: AWS::IAM::Role\r\n Properties:\r\n Policies:\r\n -\r\n PolicyName: SomeName\r\n PolicyDocument:\r\n Version: 2012-10-17\r\n Statement:\r\n -\r\n Effect: Allow\r\n Action:\r\n - iam:GetSomething\r\n Resource:\r\n - !Sub arn:aws:iam::${AWS::AccountId}:role/SomeRole*\r\n```\r\n\r\nThe error is an [E1029](https://github.com/aws-cloudformation/cfn-lint/blob/main/src/cfnlint/rules/functions/SubNeeded.py), and the line number referenced is the line number where the YAML literal appears (here, the line that contains `TemplateBody: |`)\r\n\r\nThis appears to be a new issue with [release 0.51.0](https://github.com/aws-cloudformation/cfn-lint/releases/tag/v0.51.0). The code in question above hasn't changed in my repo for a long time, and I don't get the error on previous releases.\r\n\n", "before_files": [{"content": "\"\"\"\nCopyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: MIT-0\n\"\"\"\nfrom functools import reduce # pylint: disable=redefined-builtin\nimport re\nimport copy\nimport six\nfrom cfnlint.rules import CloudFormationLintRule\nfrom cfnlint.rules import RuleMatch\n\n\nclass SubNeeded(CloudFormationLintRule):\n \"\"\"Check if a substitution string exists without a substitution function\"\"\"\n id = 'E1029'\n shortdesc = 'Sub is required if a variable is used in a string'\n description = 'If a substitution variable exists in a string but isn\\'t wrapped with the Fn::Sub function the deployment will fail.'\n source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html'\n tags = ['functions', 'sub']\n\n def __init__(self):\n \"\"\"Init\"\"\"\n super(SubNeeded, self).__init__()\n self.config_definition = {\n 'custom_excludes': {\n 'default': '',\n 'type': 'string'\n }\n }\n self.configure()\n self.subParameterRegex = re.compile(r'(\\$\\{[A-Za-z0-9_:\\.]+\\})')\n\n def _match_values(self, cfnelem, path):\n \"\"\"Recursively search for values matching the searchRegex\"\"\"\n values = []\n if isinstance(cfnelem, dict):\n for key in cfnelem:\n pathprop = path[:]\n pathprop.append(key)\n values.extend(self._match_values(cfnelem[key], pathprop))\n elif isinstance(cfnelem, list):\n for index, item in enumerate(cfnelem):\n pathprop = path[:]\n pathprop.append(index)\n values.extend(self._match_values(item, pathprop))\n else:\n # Leaf node\n if isinstance(cfnelem, six.string_types): # and re.match(searchRegex, cfnelem):\n for variable in re.findall(self.subParameterRegex, cfnelem):\n values.append(path + [variable])\n\n return values\n\n def match_values(self, cfn):\n \"\"\"\n Search for values in all parts of the templates that match the searchRegex\n \"\"\"\n results = []\n results.extend(self._match_values(cfn.template, []))\n # Globals are removed during a transform. They need to be checked manually\n results.extend(self._match_values(cfn.template.get('Globals', {}), []))\n return results\n\n def _api_exceptions(self, value):\n \"\"\" Key value exceptions \"\"\"\n parameter_search = re.compile(r'^\\$\\{stageVariables\\..*\\}$')\n return re.match(parameter_search, value)\n\n def _variable_custom_excluded(self, value):\n \"\"\" User-defined exceptions for variables, anywhere in the file \"\"\"\n custom_excludes = self.config['custom_excludes']\n if custom_excludes:\n custom_search = re.compile(custom_excludes)\n return re.match(custom_search, value)\n return False\n\n def match(self, cfn):\n matches = []\n\n refs = cfn.get_valid_refs()\n getatts = cfn.get_valid_getatts()\n\n # Get a list of paths to every leaf node string containing at least one ${parameter}\n parameter_string_paths = self.match_values(cfn)\n # We want to search all of the paths to check if each one contains an 'Fn::Sub'\n for parameter_string_path in parameter_string_paths:\n # Get variable\n var = parameter_string_path[-1]\n\n # Step Function State Machine has a Definition Substitution that allows usage of special variables outside of a !Sub\n # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-definitionsubstitutions.html\n\n if 'DefinitionString' in parameter_string_path:\n modified_parameter_string_path = copy.copy(parameter_string_path)\n index = parameter_string_path.index('DefinitionString')\n modified_parameter_string_path[index] = 'DefinitionSubstitutions'\n modified_parameter_string_path = modified_parameter_string_path[:index+1]\n modified_parameter_string_path.append(var[2:-1])\n if reduce(lambda c, k: c.get(k, {}), modified_parameter_string_path, cfn.template):\n continue\n\n # Exclude variables that match custom exclude filters, if configured\n # (for third-party tools that pre-process templates before uploading them to AWS)\n if self._variable_custom_excluded(var):\n continue\n\n # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html)\n if var.startswith('${!'):\n continue\n\n var_stripped = var[2:-1].strip()\n\n # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly\n if not 'Fn::Sub' in parameter_string_path:\n if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path:\n # Remove the last item (the variable) to prevent multiple errors on 1 line errors\n path = parameter_string_path[:-1]\n message = 'Found an embedded parameter \"{}\" outside of an \"Fn::Sub\" at {}'.format(\n var, '/'.join(map(str, path)))\n matches.append(RuleMatch(path, message))\n\n return matches\n", "path": "src/cfnlint/rules/functions/SubNeeded.py"}], "after_files": [{"content": "\"\"\"\nCopyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: MIT-0\n\"\"\"\nfrom functools import reduce # pylint: disable=redefined-builtin\nimport re\nimport copy\nimport six\nfrom cfnlint.rules import CloudFormationLintRule\nfrom cfnlint.rules import RuleMatch\n\n\nclass SubNeeded(CloudFormationLintRule):\n \"\"\"Check if a substitution string exists without a substitution function\"\"\"\n id = 'E1029'\n shortdesc = 'Sub is required if a variable is used in a string'\n description = 'If a substitution variable exists in a string but isn\\'t wrapped with the Fn::Sub function the deployment will fail.'\n source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html'\n tags = ['functions', 'sub']\n\n exceptions = ['TemplateBody']\n\n def __init__(self):\n \"\"\"Init\"\"\"\n super(SubNeeded, self).__init__()\n self.config_definition = {\n 'custom_excludes': {\n 'default': '',\n 'type': 'string'\n }\n }\n self.configure()\n self.subParameterRegex = re.compile(r'(\\$\\{[A-Za-z0-9_:\\.]+\\})')\n\n def _match_values(self, cfnelem, path):\n \"\"\"Recursively search for values matching the searchRegex\"\"\"\n values = []\n if isinstance(cfnelem, dict):\n for key in cfnelem:\n pathprop = path[:]\n pathprop.append(key)\n values.extend(self._match_values(cfnelem[key], pathprop))\n elif isinstance(cfnelem, list):\n for index, item in enumerate(cfnelem):\n pathprop = path[:]\n pathprop.append(index)\n values.extend(self._match_values(item, pathprop))\n else:\n # Leaf node\n if isinstance(cfnelem, six.string_types): # and re.match(searchRegex, cfnelem):\n for variable in re.findall(self.subParameterRegex, cfnelem):\n values.append(path + [variable])\n\n return values\n\n def match_values(self, cfn):\n \"\"\"\n Search for values in all parts of the templates that match the searchRegex\n \"\"\"\n results = []\n results.extend(self._match_values(cfn.template, []))\n # Globals are removed during a transform. They need to be checked manually\n results.extend(self._match_values(cfn.template.get('Globals', {}), []))\n return results\n\n def _api_exceptions(self, value):\n \"\"\" Key value exceptions \"\"\"\n parameter_search = re.compile(r'^\\$\\{stageVariables\\..*\\}$')\n return re.match(parameter_search, value)\n\n def _variable_custom_excluded(self, value):\n \"\"\" User-defined exceptions for variables, anywhere in the file \"\"\"\n custom_excludes = self.config['custom_excludes']\n if custom_excludes:\n custom_search = re.compile(custom_excludes)\n return re.match(custom_search, value)\n return False\n\n def match(self, cfn):\n matches = []\n\n refs = cfn.get_valid_refs()\n getatts = cfn.get_valid_getatts()\n\n # Get a list of paths to every leaf node string containing at least one ${parameter}\n parameter_string_paths = self.match_values(cfn)\n # We want to search all of the paths to check if each one contains an 'Fn::Sub'\n for parameter_string_path in parameter_string_paths:\n # Get variable\n var = parameter_string_path[-1]\n\n # Step Function State Machine has a Definition Substitution that allows usage of special variables outside of a !Sub\n # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stepfunctions-statemachine-definitionsubstitutions.html\n\n if 'DefinitionString' in parameter_string_path:\n modified_parameter_string_path = copy.copy(parameter_string_path)\n index = parameter_string_path.index('DefinitionString')\n modified_parameter_string_path[index] = 'DefinitionSubstitutions'\n modified_parameter_string_path = modified_parameter_string_path[:index+1]\n modified_parameter_string_path.append(var[2:-1])\n if reduce(lambda c, k: c.get(k, {}), modified_parameter_string_path, cfn.template):\n continue\n\n # Exclude variables that match custom exclude filters, if configured\n # (for third-party tools that pre-process templates before uploading them to AWS)\n if self._variable_custom_excluded(var):\n continue\n\n # Exclude literals (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html)\n if var.startswith('${!'):\n continue\n\n var_stripped = var[2:-1].strip()\n\n # If we didn't find an 'Fn::Sub' it means a string containing a ${parameter} may not be evaluated correctly\n if not 'Fn::Sub' in parameter_string_path and parameter_string_path[-2] not in self.exceptions:\n if (var_stripped in refs or var_stripped in getatts) or 'DefinitionString' in parameter_string_path:\n # Remove the last item (the variable) to prevent multiple errors on 1 line errors\n path = parameter_string_path[:-1]\n message = 'Found an embedded parameter \"{}\" outside of an \"Fn::Sub\" at {}'.format(\n var, '/'.join(map(str, path)))\n matches.append(RuleMatch(path, message))\n\n return matches\n", "path": "src/cfnlint/rules/functions/SubNeeded.py"}]}
1,992
277
gh_patches_debug_18554
rasdani/github-patches
git_diff
praw-dev__praw-846
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- UnicodeEncodeError is raised if reddit returns localized error message ## Issue Description Context: [[PRAW] UnicodeEncodeError when submitting non-unicode text : redditdev](https://www.reddit.com/r/redditdev/comments/6xf600/praw_unicodeencodeerror_when_submitting/) Reddit may return localized error messages depends on the user's preference settings. Since localized error messages may contain non-ascii characters (and underlying requests library converts the errror message to unicode type), running this code in Python2 may raise UnicodeEncodeError: https://github.com/praw-dev/praw/blob/efbe90f8c01a8afcda1fa09a59d1d89ed0da0f6b/praw/exceptions.py#L25 Here is an example of the localized message: ``` File "/usr/local/lib/python2.7/site-packages/praw/exceptions.py", line 25, in __init__ error_str = '{}: \'{}\''.format(error_type, message) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10: ordinal not in range(128) Uncaught exception. Entering post mortem debugging Running 'cont' or 'step' will restart the program > /usr/local/lib/python2.7/site-packages/praw/exceptions.py(25)__init__() -> error_str = '{}: \'{}\''.format(error_type, message) (Pdb) p error_type u'RATELIMIT' (Pdb) print message 実行回数が多すぎます。9分経ってから再試行してください。 ``` I think this issue is only affect to Python2 users because Python3's str type is unicode string. ## System Information PRAW Version: 5.0.0 Python Version: Python 2.7.13 Operating System: OS X El Capitan 10.11.6 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `praw/exceptions.py` Content: ``` 1 """PRAW exception classes. 2 3 Includes two main exceptions: :class:`.APIException` for when something goes 4 wrong on the server side, and :class:`.ClientException` when something goes 5 wrong on the client side. Both of these classes extend :class:`.PRAWException`. 6 7 """ 8 9 10 class PRAWException(Exception): 11 """The base PRAW Exception that all other exception classes extend.""" 12 13 14 class APIException(PRAWException): 15 """Indicate exception that involve responses from Reddit's API.""" 16 17 def __init__(self, error_type, message, field): 18 """Initialize an instance of APIException. 19 20 :param error_type: The error type set on Reddit's end. 21 :param message: The associated message for the error. 22 :param field: The input field associated with the error if available. 23 24 """ 25 error_str = '{}: \'{}\''.format(error_type, message) 26 if field: 27 error_str += ' on field \'{}\''.format(field) 28 super(APIException, self).__init__(error_str) 29 self.error_type = error_type 30 self.message = message 31 self.field = field 32 33 34 class ClientException(PRAWException): 35 """Indicate exceptions that don't involve interaction with Reddit's API.""" 36 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/praw/exceptions.py b/praw/exceptions.py --- a/praw/exceptions.py +++ b/praw/exceptions.py @@ -21,10 +21,17 @@ :param message: The associated message for the error. :param field: The input field associated with the error if available. + .. note: Calling `str()` on the instance returns `unicode_escape`d + ASCII string because the message may be localized and may contain + UNICODE characters. If you want a non-escaped message, access + the `message` atribute on the instance. + """ - error_str = '{}: \'{}\''.format(error_type, message) + error_str = u'{}: \'{}\''.format(error_type, message) if field: - error_str += ' on field \'{}\''.format(field) + error_str += u' on field \'{}\''.format(field) + error_str = error_str.encode('unicode_escape').decode('ascii') + super(APIException, self).__init__(error_str) self.error_type = error_type self.message = message
{"golden_diff": "diff --git a/praw/exceptions.py b/praw/exceptions.py\n--- a/praw/exceptions.py\n+++ b/praw/exceptions.py\n@@ -21,10 +21,17 @@\n :param message: The associated message for the error.\n :param field: The input field associated with the error if available.\n \n+ .. note: Calling `str()` on the instance returns `unicode_escape`d\n+ ASCII string because the message may be localized and may contain\n+ UNICODE characters. If you want a non-escaped message, access\n+ the `message` atribute on the instance.\n+\n \"\"\"\n- error_str = '{}: \\'{}\\''.format(error_type, message)\n+ error_str = u'{}: \\'{}\\''.format(error_type, message)\n if field:\n- error_str += ' on field \\'{}\\''.format(field)\n+ error_str += u' on field \\'{}\\''.format(field)\n+ error_str = error_str.encode('unicode_escape').decode('ascii')\n+\n super(APIException, self).__init__(error_str)\n self.error_type = error_type\n self.message = message\n", "issue": "UnicodeEncodeError is raised if reddit returns localized error message\n## Issue Description\r\n\r\nContext: [[PRAW] UnicodeEncodeError when submitting non-unicode text : redditdev](https://www.reddit.com/r/redditdev/comments/6xf600/praw_unicodeencodeerror_when_submitting/)\r\n\r\nReddit may return localized error messages depends on the user's preference settings. Since\r\nlocalized error messages may contain non-ascii characters (and underlying requests library\r\nconverts the errror message to unicode type), running this code in Python2 may raise UnicodeEncodeError:\r\n\r\nhttps://github.com/praw-dev/praw/blob/efbe90f8c01a8afcda1fa09a59d1d89ed0da0f6b/praw/exceptions.py#L25\r\n\r\nHere is an example of the localized message:\r\n\r\n```\r\n File \"/usr/local/lib/python2.7/site-packages/praw/exceptions.py\", line 25, in __init__\r\n error_str = '{}: \\'{}\\''.format(error_type, message)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10: ordinal not in range(128)\r\nUncaught exception. Entering post mortem debugging\r\nRunning 'cont' or 'step' will restart the program\r\n> /usr/local/lib/python2.7/site-packages/praw/exceptions.py(25)__init__()\r\n-> error_str = '{}: \\'{}\\''.format(error_type, message)\r\n(Pdb) p error_type\r\nu'RATELIMIT'\r\n(Pdb) print message\r\n\u5b9f\u884c\u56de\u6570\u304c\u591a\u3059\u304e\u307e\u3059\u30029\u5206\u7d4c\u3063\u3066\u304b\u3089\u518d\u8a66\u884c\u3057\u3066\u304f\u3060\u3055\u3044\u3002\r\n```\r\n\r\nI think this issue is only affect to Python2 users because Python3's str type is unicode string. \r\n\r\n## System Information\r\n\r\n PRAW Version: 5.0.0\r\n Python Version: Python 2.7.13\r\n Operating System: OS X El Capitan 10.11.6\n", "before_files": [{"content": "\"\"\"PRAW exception classes.\n\nIncludes two main exceptions: :class:`.APIException` for when something goes\nwrong on the server side, and :class:`.ClientException` when something goes\nwrong on the client side. Both of these classes extend :class:`.PRAWException`.\n\n\"\"\"\n\n\nclass PRAWException(Exception):\n \"\"\"The base PRAW Exception that all other exception classes extend.\"\"\"\n\n\nclass APIException(PRAWException):\n \"\"\"Indicate exception that involve responses from Reddit's API.\"\"\"\n\n def __init__(self, error_type, message, field):\n \"\"\"Initialize an instance of APIException.\n\n :param error_type: The error type set on Reddit's end.\n :param message: The associated message for the error.\n :param field: The input field associated with the error if available.\n\n \"\"\"\n error_str = '{}: \\'{}\\''.format(error_type, message)\n if field:\n error_str += ' on field \\'{}\\''.format(field)\n super(APIException, self).__init__(error_str)\n self.error_type = error_type\n self.message = message\n self.field = field\n\n\nclass ClientException(PRAWException):\n \"\"\"Indicate exceptions that don't involve interaction with Reddit's API.\"\"\"\n", "path": "praw/exceptions.py"}], "after_files": [{"content": "\"\"\"PRAW exception classes.\n\nIncludes two main exceptions: :class:`.APIException` for when something goes\nwrong on the server side, and :class:`.ClientException` when something goes\nwrong on the client side. Both of these classes extend :class:`.PRAWException`.\n\n\"\"\"\n\n\nclass PRAWException(Exception):\n \"\"\"The base PRAW Exception that all other exception classes extend.\"\"\"\n\n\nclass APIException(PRAWException):\n \"\"\"Indicate exception that involve responses from Reddit's API.\"\"\"\n\n def __init__(self, error_type, message, field):\n \"\"\"Initialize an instance of APIException.\n\n :param error_type: The error type set on Reddit's end.\n :param message: The associated message for the error.\n :param field: The input field associated with the error if available.\n\n .. note: Calling `str()` on the instance returns `unicode_escape`d\n ASCII string because the message may be localized and may contain\n UNICODE characters. If you want a non-escaped message, access\n the `message` atribute on the instance.\n\n \"\"\"\n error_str = u'{}: \\'{}\\''.format(error_type, message)\n if field:\n error_str += u' on field \\'{}\\''.format(field)\n error_str = error_str.encode('unicode_escape').decode('ascii')\n\n super(APIException, self).__init__(error_str)\n self.error_type = error_type\n self.message = message\n self.field = field\n\n\nclass ClientException(PRAWException):\n \"\"\"Indicate exceptions that don't involve interaction with Reddit's API.\"\"\"\n", "path": "praw/exceptions.py"}]}
1,011
252
gh_patches_debug_1683
rasdani/github-patches
git_diff
RedHatInsights__insights-core-2085
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Dmesg combiner always succeeds The [Dmesg combiner has only optional dependencies](https://github.com/RedHatInsights/insights-core/blob/master/insights/combiners/dmesg.py#L51), which means it always succeeds. This is an anti-pattern. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `insights/combiners/dmesg.py` Content: ``` 1 """ 2 Dmesg 3 ===== 4 5 Combiner for Dmesg information. It uses the results of the following parsers (if they are present): 6 :class:`insights.parsers.dmesg.DmesgLineList`, 7 :class:`insights.parsers.dmesg_log.DmesgLog` 8 9 Typical output of the ``/var/log/dmesg`` file is:: 10 11 [ 0.000000] Initializing cgroup subsys cpu 12 [ 0.000000] Linux version 3.10.0-862.el7.x86_64 ([email protected]) \ 13 (gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) ) #1 SMP Wed Mar 21 18:14:51 EDT 2018 14 [ 2.090905] SELinux: Completing initialization. 15 [ 2.090907] SELinux: Setting up existing superblocks. 16 [ 2.099684] systemd[1]: Successfully loaded SELinux policy in 82.788ms. 17 [ 2.117410] ip_tables: (C) 2000-2006 Netfilter Core Team 18 [ 2.117429] systemd[1]: Inserted module 'ip_tables' 19 [ 2.376551] systemd-journald[441]: Received request to flush runtime journal from PID 1 20 [ 2.716874] cryptd: max_cpu_qlen set to 100 21 [ 2.804152] AES CTR mode by8 optimization enabled 22 23 Typical output of the ``dmesg`` command is:: 24 25 [ 2.939498] [TTM] Initializing pool allocator 26 [ 2.939502] [TTM] Initializing DMA pool allocator 27 [ 2.940800] [drm] fb mappable at 0xFC000000 28 [ 2.940947] fbcon: cirrusdrmfb (fb0) is primary device 29 [ 2.957375] Console: switching to colour frame buffer device 128x48 30 [ 2.959322] cirrus 0000:00:02.0: fb0: cirrusdrmfb frame buffer device 31 [ 2.959334] [drm] Initialized cirrus 1.0.0 20110418 for 0000:00:02.0 on minor 0 32 [ 3.062459] XFS (vda1): Ending clean mount 33 [ 5.048484] ip6_tables: (C) 2000-2006 Netfilter Core Team 34 [ 5.102434] Ebtables v2.0 registered 35 36 37 Examples: 38 >>> dmesg.dmesg_cmd_available 39 True 40 >>> dmesg.dmesg_log_available 41 True 42 >>> dmesg.dmesg_log_wrapped 43 False 44 """ 45 46 from insights.core.plugins import combiner 47 from insights.parsers.dmesg import DmesgLineList 48 from insights.parsers.dmesg_log import DmesgLog 49 50 51 @combiner(optional=[DmesgLineList, DmesgLog]) 52 class Dmesg(object): 53 """ 54 Combiner for ``dmesg`` command and ``/var/log/dmesg`` file. 55 """ 56 57 def __init__(self, dmesg_cmd, dmesg_log): 58 if dmesg_cmd is not None: 59 self.dmesg_cmd_available = True 60 self.dmesg_cmd = dmesg_cmd 61 self.dmesg_cmd_wrapped = True if 'Linux version' not in dmesg_cmd else False 62 else: 63 self.dmesg_cmd_available = False 64 65 if dmesg_log is not None: 66 self.dmesg_log_available = True 67 self.dmesg_log = dmesg_log 68 self.dmesg_log_wrapped = True if 'Linux version' not in dmesg_log else False 69 else: 70 self.dmesg_log_available = False 71 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/insights/combiners/dmesg.py b/insights/combiners/dmesg.py --- a/insights/combiners/dmesg.py +++ b/insights/combiners/dmesg.py @@ -48,7 +48,7 @@ from insights.parsers.dmesg_log import DmesgLog -@combiner(optional=[DmesgLineList, DmesgLog]) +@combiner([DmesgLineList, DmesgLog]) class Dmesg(object): """ Combiner for ``dmesg`` command and ``/var/log/dmesg`` file.
{"golden_diff": "diff --git a/insights/combiners/dmesg.py b/insights/combiners/dmesg.py\n--- a/insights/combiners/dmesg.py\n+++ b/insights/combiners/dmesg.py\n@@ -48,7 +48,7 @@\n from insights.parsers.dmesg_log import DmesgLog\n \n \n-@combiner(optional=[DmesgLineList, DmesgLog])\n+@combiner([DmesgLineList, DmesgLog])\n class Dmesg(object):\n \"\"\"\n Combiner for ``dmesg`` command and ``/var/log/dmesg`` file.\n", "issue": "Dmesg combiner always succeeds\nThe [Dmesg combiner has only optional dependencies](https://github.com/RedHatInsights/insights-core/blob/master/insights/combiners/dmesg.py#L51), which means it always succeeds. This is an anti-pattern.\n", "before_files": [{"content": "\"\"\"\nDmesg\n=====\n\nCombiner for Dmesg information. It uses the results of the following parsers (if they are present):\n:class:`insights.parsers.dmesg.DmesgLineList`,\n:class:`insights.parsers.dmesg_log.DmesgLog`\n\nTypical output of the ``/var/log/dmesg`` file is::\n\n[ 0.000000] Initializing cgroup subsys cpu\n[ 0.000000] Linux version 3.10.0-862.el7.x86_64 ([email protected]) \\\n(gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) ) #1 SMP Wed Mar 21 18:14:51 EDT 2018\n[ 2.090905] SELinux: Completing initialization.\n[ 2.090907] SELinux: Setting up existing superblocks.\n[ 2.099684] systemd[1]: Successfully loaded SELinux policy in 82.788ms.\n[ 2.117410] ip_tables: (C) 2000-2006 Netfilter Core Team\n[ 2.117429] systemd[1]: Inserted module 'ip_tables'\n[ 2.376551] systemd-journald[441]: Received request to flush runtime journal from PID 1\n[ 2.716874] cryptd: max_cpu_qlen set to 100\n[ 2.804152] AES CTR mode by8 optimization enabled\n\nTypical output of the ``dmesg`` command is::\n\n[ 2.939498] [TTM] Initializing pool allocator\n[ 2.939502] [TTM] Initializing DMA pool allocator\n[ 2.940800] [drm] fb mappable at 0xFC000000\n[ 2.940947] fbcon: cirrusdrmfb (fb0) is primary device\n[ 2.957375] Console: switching to colour frame buffer device 128x48\n[ 2.959322] cirrus 0000:00:02.0: fb0: cirrusdrmfb frame buffer device\n[ 2.959334] [drm] Initialized cirrus 1.0.0 20110418 for 0000:00:02.0 on minor 0\n[ 3.062459] XFS (vda1): Ending clean mount\n[ 5.048484] ip6_tables: (C) 2000-2006 Netfilter Core Team\n[ 5.102434] Ebtables v2.0 registered\n\n\nExamples:\n >>> dmesg.dmesg_cmd_available\n True\n >>> dmesg.dmesg_log_available\n True\n >>> dmesg.dmesg_log_wrapped\n False\n\"\"\"\n\nfrom insights.core.plugins import combiner\nfrom insights.parsers.dmesg import DmesgLineList\nfrom insights.parsers.dmesg_log import DmesgLog\n\n\n@combiner(optional=[DmesgLineList, DmesgLog])\nclass Dmesg(object):\n \"\"\"\n Combiner for ``dmesg`` command and ``/var/log/dmesg`` file.\n \"\"\"\n\n def __init__(self, dmesg_cmd, dmesg_log):\n if dmesg_cmd is not None:\n self.dmesg_cmd_available = True\n self.dmesg_cmd = dmesg_cmd\n self.dmesg_cmd_wrapped = True if 'Linux version' not in dmesg_cmd else False\n else:\n self.dmesg_cmd_available = False\n\n if dmesg_log is not None:\n self.dmesg_log_available = True\n self.dmesg_log = dmesg_log\n self.dmesg_log_wrapped = True if 'Linux version' not in dmesg_log else False\n else:\n self.dmesg_log_available = False\n", "path": "insights/combiners/dmesg.py"}], "after_files": [{"content": "\"\"\"\nDmesg\n=====\n\nCombiner for Dmesg information. It uses the results of the following parsers (if they are present):\n:class:`insights.parsers.dmesg.DmesgLineList`,\n:class:`insights.parsers.dmesg_log.DmesgLog`\n\nTypical output of the ``/var/log/dmesg`` file is::\n\n[ 0.000000] Initializing cgroup subsys cpu\n[ 0.000000] Linux version 3.10.0-862.el7.x86_64 ([email protected]) \\\n(gcc version 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) ) #1 SMP Wed Mar 21 18:14:51 EDT 2018\n[ 2.090905] SELinux: Completing initialization.\n[ 2.090907] SELinux: Setting up existing superblocks.\n[ 2.099684] systemd[1]: Successfully loaded SELinux policy in 82.788ms.\n[ 2.117410] ip_tables: (C) 2000-2006 Netfilter Core Team\n[ 2.117429] systemd[1]: Inserted module 'ip_tables'\n[ 2.376551] systemd-journald[441]: Received request to flush runtime journal from PID 1\n[ 2.716874] cryptd: max_cpu_qlen set to 100\n[ 2.804152] AES CTR mode by8 optimization enabled\n\nTypical output of the ``dmesg`` command is::\n\n[ 2.939498] [TTM] Initializing pool allocator\n[ 2.939502] [TTM] Initializing DMA pool allocator\n[ 2.940800] [drm] fb mappable at 0xFC000000\n[ 2.940947] fbcon: cirrusdrmfb (fb0) is primary device\n[ 2.957375] Console: switching to colour frame buffer device 128x48\n[ 2.959322] cirrus 0000:00:02.0: fb0: cirrusdrmfb frame buffer device\n[ 2.959334] [drm] Initialized cirrus 1.0.0 20110418 for 0000:00:02.0 on minor 0\n[ 3.062459] XFS (vda1): Ending clean mount\n[ 5.048484] ip6_tables: (C) 2000-2006 Netfilter Core Team\n[ 5.102434] Ebtables v2.0 registered\n\n\nExamples:\n >>> dmesg.dmesg_cmd_available\n True\n >>> dmesg.dmesg_log_available\n True\n >>> dmesg.dmesg_log_wrapped\n False\n\"\"\"\n\nfrom insights.core.plugins import combiner\nfrom insights.parsers.dmesg import DmesgLineList\nfrom insights.parsers.dmesg_log import DmesgLog\n\n\n@combiner([DmesgLineList, DmesgLog])\nclass Dmesg(object):\n \"\"\"\n Combiner for ``dmesg`` command and ``/var/log/dmesg`` file.\n \"\"\"\n\n def __init__(self, dmesg_cmd, dmesg_log):\n if dmesg_cmd is not None:\n self.dmesg_cmd_available = True\n self.dmesg_cmd = dmesg_cmd\n self.dmesg_cmd_wrapped = True if 'Linux version' not in dmesg_cmd else False\n else:\n self.dmesg_cmd_available = False\n\n if dmesg_log is not None:\n self.dmesg_log_available = True\n self.dmesg_log = dmesg_log\n self.dmesg_log_wrapped = True if 'Linux version' not in dmesg_log else False\n else:\n self.dmesg_log_available = False\n", "path": "insights/combiners/dmesg.py"}]}
1,474
143
gh_patches_debug_31108
rasdani/github-patches
git_diff
python-poetry__poetry-5053
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Update prompt environment variable when opening shell <!-- Hi there! Thank you for wanting to make Poetry better. Before you submit this; let's make sure of a few things. Please make sure the following boxes are ticked if they are correct. If not, please try and fulfill these first. --> <!-- Checked checkbox should look like this: [x] --> - [x] I have searched the [issues](https://github.com/sdispater/poetry/issues) of this repo and believe that this is not a duplicate. - [x] I have searched the [documentation](https://poetry.eustace.io/docs/) and believe that my question is not covered. ## Feature Request <!-- Now feel free to write your idea for improvement. Thanks again 🙌 ❤️ --> When running `poetry shell` you have no idea your in the virtualenv or not. Please add the virtualenv's name to the $PROMPT or $PS1 variable. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/poetry/utils/shell.py` Content: ``` 1 import os 2 import signal 3 import sys 4 5 from pathlib import Path 6 from typing import TYPE_CHECKING 7 from typing import Any 8 from typing import Optional 9 10 import pexpect 11 12 from cleo.terminal import Terminal 13 from shellingham import ShellDetectionFailure 14 from shellingham import detect_shell 15 16 from poetry.utils._compat import WINDOWS 17 18 19 if TYPE_CHECKING: 20 from poetry.utils.env import VirtualEnv 21 22 23 class Shell: 24 """ 25 Represents the current shell. 26 """ 27 28 _shell = None 29 30 def __init__(self, name: str, path: str) -> None: 31 self._name = name 32 self._path = path 33 34 @property 35 def name(self) -> str: 36 return self._name 37 38 @property 39 def path(self) -> str: 40 return self._path 41 42 @classmethod 43 def get(cls) -> "Shell": 44 """ 45 Retrieve the current shell. 46 """ 47 if cls._shell is not None: 48 return cls._shell 49 50 try: 51 name, path = detect_shell(os.getpid()) 52 except (RuntimeError, ShellDetectionFailure): 53 shell = None 54 55 if os.name == "posix": 56 shell = os.environ.get("SHELL") 57 elif os.name == "nt": 58 shell = os.environ.get("COMSPEC") 59 60 if not shell: 61 raise RuntimeError("Unable to detect the current shell.") 62 63 name, path = Path(shell).stem, shell 64 65 cls._shell = cls(name, path) 66 67 return cls._shell 68 69 def activate(self, env: "VirtualEnv") -> Optional[int]: 70 if WINDOWS: 71 return env.execute(self.path) 72 73 import shlex 74 75 terminal = Terminal() 76 with env.temp_environ(): 77 c = pexpect.spawn( 78 self._path, ["-i"], dimensions=(terminal.height, terminal.width) 79 ) 80 81 if self._name == "zsh": 82 c.setecho(False) 83 84 activate_script = self._get_activate_script() 85 bin_dir = "Scripts" if WINDOWS else "bin" 86 activate_path = env.path / bin_dir / activate_script 87 c.sendline(f"{self._get_source_command()} {shlex.quote(str(activate_path))}") 88 89 def resize(sig: Any, data: Any) -> None: 90 terminal = Terminal() 91 c.setwinsize(terminal.height, terminal.width) 92 93 signal.signal(signal.SIGWINCH, resize) 94 95 # Interact with the new shell. 96 c.interact(escape_character=None) 97 c.close() 98 99 sys.exit(c.exitstatus) 100 101 def _get_activate_script(self) -> str: 102 if self._name == "fish": 103 suffix = ".fish" 104 elif self._name in ("csh", "tcsh"): 105 suffix = ".csh" 106 else: 107 suffix = "" 108 109 return "activate" + suffix 110 111 def _get_source_command(self) -> str: 112 if self._name in ("fish", "csh", "tcsh"): 113 return "source" 114 return "." 115 116 def __repr__(self) -> str: 117 return f'{self.__class__.__name__}("{self._name}", "{self._path}")' 118 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/poetry/utils/shell.py b/src/poetry/utils/shell.py --- a/src/poetry/utils/shell.py +++ b/src/poetry/utils/shell.py @@ -1,5 +1,6 @@ import os import signal +import subprocess import sys from pathlib import Path @@ -67,8 +68,19 @@ return cls._shell def activate(self, env: "VirtualEnv") -> Optional[int]: + activate_script = self._get_activate_script() + bin_dir = "Scripts" if WINDOWS else "bin" + activate_path = env.path / bin_dir / activate_script + if WINDOWS: - return env.execute(self.path) + if self._name in ("powershell", "pwsh"): + args = ["-NoExit", "-File", str(activate_path)] + else: + # /K will execute the bat file and + # keep the cmd process from terminating + args = ["/K", str(activate_path)] + completed_proc = subprocess.run([self.path, *args]) + return completed_proc.returncode import shlex @@ -81,9 +93,6 @@ if self._name == "zsh": c.setecho(False) - activate_script = self._get_activate_script() - bin_dir = "Scripts" if WINDOWS else "bin" - activate_path = env.path / bin_dir / activate_script c.sendline(f"{self._get_source_command()} {shlex.quote(str(activate_path))}") def resize(sig: Any, data: Any) -> None: @@ -103,6 +112,10 @@ suffix = ".fish" elif self._name in ("csh", "tcsh"): suffix = ".csh" + elif self._name in ("powershell", "pwsh"): + suffix = ".ps1" + elif self._name == "cmd": + suffix = ".bat" else: suffix = ""
{"golden_diff": "diff --git a/src/poetry/utils/shell.py b/src/poetry/utils/shell.py\n--- a/src/poetry/utils/shell.py\n+++ b/src/poetry/utils/shell.py\n@@ -1,5 +1,6 @@\n import os\n import signal\n+import subprocess\n import sys\n \n from pathlib import Path\n@@ -67,8 +68,19 @@\n return cls._shell\n \n def activate(self, env: \"VirtualEnv\") -> Optional[int]:\n+ activate_script = self._get_activate_script()\n+ bin_dir = \"Scripts\" if WINDOWS else \"bin\"\n+ activate_path = env.path / bin_dir / activate_script\n+\n if WINDOWS:\n- return env.execute(self.path)\n+ if self._name in (\"powershell\", \"pwsh\"):\n+ args = [\"-NoExit\", \"-File\", str(activate_path)]\n+ else:\n+ # /K will execute the bat file and\n+ # keep the cmd process from terminating\n+ args = [\"/K\", str(activate_path)]\n+ completed_proc = subprocess.run([self.path, *args])\n+ return completed_proc.returncode\n \n import shlex\n \n@@ -81,9 +93,6 @@\n if self._name == \"zsh\":\n c.setecho(False)\n \n- activate_script = self._get_activate_script()\n- bin_dir = \"Scripts\" if WINDOWS else \"bin\"\n- activate_path = env.path / bin_dir / activate_script\n c.sendline(f\"{self._get_source_command()} {shlex.quote(str(activate_path))}\")\n \n def resize(sig: Any, data: Any) -> None:\n@@ -103,6 +112,10 @@\n suffix = \".fish\"\n elif self._name in (\"csh\", \"tcsh\"):\n suffix = \".csh\"\n+ elif self._name in (\"powershell\", \"pwsh\"):\n+ suffix = \".ps1\"\n+ elif self._name == \"cmd\":\n+ suffix = \".bat\"\n else:\n suffix = \"\"\n", "issue": "Update prompt environment variable when opening shell\n<!--\r\n Hi there! Thank you for wanting to make Poetry better.\r\n\r\n Before you submit this; let's make sure of a few things.\r\n Please make sure the following boxes are ticked if they are correct.\r\n If not, please try and fulfill these first.\r\n-->\r\n\r\n<!-- Checked checkbox should look like this: [x] -->\r\n- [x] I have searched the [issues](https://github.com/sdispater/poetry/issues) of this repo and believe that this is not a duplicate.\r\n- [x] I have searched the [documentation](https://poetry.eustace.io/docs/) and believe that my question is not covered.\r\n\r\n## Feature Request\r\n<!-- Now feel free to write your idea for improvement. Thanks again \ud83d\ude4c \u2764\ufe0f -->\r\nWhen running `poetry shell` you have no idea your in the virtualenv or not. Please add the virtualenv's name to the $PROMPT or $PS1 variable.\n", "before_files": [{"content": "import os\nimport signal\nimport sys\n\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\nfrom typing import Any\nfrom typing import Optional\n\nimport pexpect\n\nfrom cleo.terminal import Terminal\nfrom shellingham import ShellDetectionFailure\nfrom shellingham import detect_shell\n\nfrom poetry.utils._compat import WINDOWS\n\n\nif TYPE_CHECKING:\n from poetry.utils.env import VirtualEnv\n\n\nclass Shell:\n \"\"\"\n Represents the current shell.\n \"\"\"\n\n _shell = None\n\n def __init__(self, name: str, path: str) -> None:\n self._name = name\n self._path = path\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def path(self) -> str:\n return self._path\n\n @classmethod\n def get(cls) -> \"Shell\":\n \"\"\"\n Retrieve the current shell.\n \"\"\"\n if cls._shell is not None:\n return cls._shell\n\n try:\n name, path = detect_shell(os.getpid())\n except (RuntimeError, ShellDetectionFailure):\n shell = None\n\n if os.name == \"posix\":\n shell = os.environ.get(\"SHELL\")\n elif os.name == \"nt\":\n shell = os.environ.get(\"COMSPEC\")\n\n if not shell:\n raise RuntimeError(\"Unable to detect the current shell.\")\n\n name, path = Path(shell).stem, shell\n\n cls._shell = cls(name, path)\n\n return cls._shell\n\n def activate(self, env: \"VirtualEnv\") -> Optional[int]:\n if WINDOWS:\n return env.execute(self.path)\n\n import shlex\n\n terminal = Terminal()\n with env.temp_environ():\n c = pexpect.spawn(\n self._path, [\"-i\"], dimensions=(terminal.height, terminal.width)\n )\n\n if self._name == \"zsh\":\n c.setecho(False)\n\n activate_script = self._get_activate_script()\n bin_dir = \"Scripts\" if WINDOWS else \"bin\"\n activate_path = env.path / bin_dir / activate_script\n c.sendline(f\"{self._get_source_command()} {shlex.quote(str(activate_path))}\")\n\n def resize(sig: Any, data: Any) -> None:\n terminal = Terminal()\n c.setwinsize(terminal.height, terminal.width)\n\n signal.signal(signal.SIGWINCH, resize)\n\n # Interact with the new shell.\n c.interact(escape_character=None)\n c.close()\n\n sys.exit(c.exitstatus)\n\n def _get_activate_script(self) -> str:\n if self._name == \"fish\":\n suffix = \".fish\"\n elif self._name in (\"csh\", \"tcsh\"):\n suffix = \".csh\"\n else:\n suffix = \"\"\n\n return \"activate\" + suffix\n\n def _get_source_command(self) -> str:\n if self._name in (\"fish\", \"csh\", \"tcsh\"):\n return \"source\"\n return \".\"\n\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}(\"{self._name}\", \"{self._path}\")'\n", "path": "src/poetry/utils/shell.py"}], "after_files": [{"content": "import os\nimport signal\nimport subprocess\nimport sys\n\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\nfrom typing import Any\nfrom typing import Optional\n\nimport pexpect\n\nfrom cleo.terminal import Terminal\nfrom shellingham import ShellDetectionFailure\nfrom shellingham import detect_shell\n\nfrom poetry.utils._compat import WINDOWS\n\n\nif TYPE_CHECKING:\n from poetry.utils.env import VirtualEnv\n\n\nclass Shell:\n \"\"\"\n Represents the current shell.\n \"\"\"\n\n _shell = None\n\n def __init__(self, name: str, path: str) -> None:\n self._name = name\n self._path = path\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def path(self) -> str:\n return self._path\n\n @classmethod\n def get(cls) -> \"Shell\":\n \"\"\"\n Retrieve the current shell.\n \"\"\"\n if cls._shell is not None:\n return cls._shell\n\n try:\n name, path = detect_shell(os.getpid())\n except (RuntimeError, ShellDetectionFailure):\n shell = None\n\n if os.name == \"posix\":\n shell = os.environ.get(\"SHELL\")\n elif os.name == \"nt\":\n shell = os.environ.get(\"COMSPEC\")\n\n if not shell:\n raise RuntimeError(\"Unable to detect the current shell.\")\n\n name, path = Path(shell).stem, shell\n\n cls._shell = cls(name, path)\n\n return cls._shell\n\n def activate(self, env: \"VirtualEnv\") -> Optional[int]:\n activate_script = self._get_activate_script()\n bin_dir = \"Scripts\" if WINDOWS else \"bin\"\n activate_path = env.path / bin_dir / activate_script\n\n if WINDOWS:\n if self._name in (\"powershell\", \"pwsh\"):\n args = [\"-NoExit\", \"-File\", str(activate_path)]\n else:\n # /K will execute the bat file and\n # keep the cmd process from terminating\n args = [\"/K\", str(activate_path)]\n completed_proc = subprocess.run([self.path, *args])\n return completed_proc.returncode\n\n import shlex\n\n terminal = Terminal()\n with env.temp_environ():\n c = pexpect.spawn(\n self._path, [\"-i\"], dimensions=(terminal.height, terminal.width)\n )\n\n if self._name == \"zsh\":\n c.setecho(False)\n\n c.sendline(f\"{self._get_source_command()} {shlex.quote(str(activate_path))}\")\n\n def resize(sig: Any, data: Any) -> None:\n terminal = Terminal()\n c.setwinsize(terminal.height, terminal.width)\n\n signal.signal(signal.SIGWINCH, resize)\n\n # Interact with the new shell.\n c.interact(escape_character=None)\n c.close()\n\n sys.exit(c.exitstatus)\n\n def _get_activate_script(self) -> str:\n if self._name == \"fish\":\n suffix = \".fish\"\n elif self._name in (\"csh\", \"tcsh\"):\n suffix = \".csh\"\n elif self._name in (\"powershell\", \"pwsh\"):\n suffix = \".ps1\"\n elif self._name == \"cmd\":\n suffix = \".bat\"\n else:\n suffix = \"\"\n\n return \"activate\" + suffix\n\n def _get_source_command(self) -> str:\n if self._name in (\"fish\", \"csh\", \"tcsh\"):\n return \"source\"\n return \".\"\n\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}(\"{self._name}\", \"{self._path}\")'\n", "path": "src/poetry/utils/shell.py"}]}
1,404
450
gh_patches_debug_27038
rasdani/github-patches
git_diff
open-mmlab__mmocr-74
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Webcam demo script is not working properly **Checklist** 1. I have searched related issues but cannot get the expected help: Yes 2. The bug has not been fixed in the latest version: Yes **Describe the bug** The current model_inference function expects to receive a model and a path to an image as inputs but the webcam demo scripts tries to call it with a model and a numpy array (the return value from cv2.VideoCapture.read()). This raises an assertion error due to type mismatch (np.ndarray vs str) **Reproduction** 1. What command or script did you run? ```none python demo/webcam_demo.py ``` 2. Did you make any modifications on the code or config? Did you understand what you have modified? No. 3. What dataset did you use? **Environment** 1. Please run `python mmocr/utils/collect_env.py` to collect necessary environment information and paste it here. sys.platform: linux Python: 3.7.10 | packaged by conda-forge | (default, Feb 19 2021, 16:07:37) [GCC 9.3.0] CUDA available: True GPU 0: GeForce GTX 1050 Ti CUDA_HOME: /usr/local/cuda NVCC: Build cuda_11.1.TC455_06.29190527_0 GCC: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 PyTorch: 1.5.0 PyTorch compiling details: PyTorch built with: - GCC 7.3 - C++ Version: 201402 - Intel(R) Math Kernel Library Version 2020.0.4 Product Build 20200917 for Intel(R) 64 architecture applications - Intel(R) MKL-DNN v0.21.1 (Git Hash 7d2fd500bc78936d1d648ca713b901012f470dbc) - OpenMP 201511 (a.k.a. OpenMP 4.5) - NNPACK is enabled - CPU capability usage: AVX2 - CUDA Runtime 10.1 - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_37,code=compute_37 - CuDNN 7.6.3 - Magma 2.5.2 - Build settings: BLAS=MKL, BUILD_TYPE=Release, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -fopenmp -DNDEBUG -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DUSE_INTERNAL_THREADPOOL_IMPL -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, USE_CUDA=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_STATIC_DISPATCH=OFF, TorchVision: 0.6.0a0+82fd1c8 OpenCV: 4.5.1 MMCV: 1.2.7 MMCV Compiler: GCC 9.3 MMCV CUDA Compiler: not available MMOCR: 0.1.0+344cc9a 2. You may add addition that may be helpful for locating the problem, such as - How you installed PyTorch: conda **Error traceback** ```none Use load_from_local loader Press "Esc", "q" or "Q" to exit. Traceback (most recent call last): File "demo/webcam_demo.py", line 52, in <module> main() File "demo/webcam_demo.py", line 41, in main result = model_inference(model, img) File "/home/sbugallo/Projects/mmocr/mmocr/apis/inference.py", line 18, in model_inference assert isinstance(img, str) AssertionError ``` **Bug fix** The inference method should accept the following types as input image(s) (str/ndarray or list[str/ndarray] or tuple[str/ndarray]) like in MMDetection --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mmocr/apis/inference.py` Content: ``` 1 import torch 2 from mmcv.ops import RoIPool 3 from mmcv.parallel import collate, scatter 4 5 from mmdet.datasets.pipelines import Compose 6 7 8 def model_inference(model, img): 9 """Inference image(s) with the detector. 10 11 Args: 12 model (nn.Module): The loaded detector. 13 imgs (str): Image files. 14 15 Returns: 16 result (dict): Detection results. 17 """ 18 assert isinstance(img, str) 19 20 cfg = model.cfg 21 device = next(model.parameters()).device # model device 22 data = dict(img_info=dict(filename=img), img_prefix=None) 23 # build the data pipeline 24 test_pipeline = Compose(cfg.data.test.pipeline) 25 data = test_pipeline(data) 26 data = collate([data], samples_per_gpu=1) 27 28 # process img_metas 29 if isinstance(data['img_metas'], list): 30 data['img_metas'] = data['img_metas'][0].data 31 else: 32 data['img_metas'] = data['img_metas'].data[0] 33 34 if next(model.parameters()).is_cuda: 35 # scatter to specified GPU 36 data = scatter(data, [device])[0] 37 else: 38 for m in model.modules(): 39 assert not isinstance( 40 m, RoIPool 41 ), 'CPU inference with RoIPool is not supported currently.' 42 43 # forward the model 44 with torch.no_grad(): 45 result = model(return_loss=False, rescale=True, **data)[0] 46 return result 47 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/mmocr/apis/inference.py b/mmocr/apis/inference.py --- a/mmocr/apis/inference.py +++ b/mmocr/apis/inference.py @@ -1,7 +1,9 @@ +import numpy as np import torch from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter +from mmdet.datasets import replace_ImageToTensor from mmdet.datasets.pipelines import Compose @@ -10,18 +12,33 @@ Args: model (nn.Module): The loaded detector. - imgs (str): Image files. + imgs (str/ndarray): Image files. Returns: result (dict): Detection results. """ - assert isinstance(img, str) + + assert isinstance(img, (str, np.ndarray)) cfg = model.cfg device = next(model.parameters()).device # model device - data = dict(img_info=dict(filename=img), img_prefix=None) - # build the data pipeline + + if isinstance(img, np.ndarray): + cfg = cfg.copy() + # set loading pipeline type + cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam' + + cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline) test_pipeline = Compose(cfg.data.test.pipeline) + + if isinstance(img, np.ndarray): + # directly add img + data = dict(img=img) + else: + # add information into dict + data = dict(img_info=dict(filename=img), img_prefix=None) + + # build the data pipeline data = test_pipeline(data) data = collate([data], samples_per_gpu=1)
{"golden_diff": "diff --git a/mmocr/apis/inference.py b/mmocr/apis/inference.py\n--- a/mmocr/apis/inference.py\n+++ b/mmocr/apis/inference.py\n@@ -1,7 +1,9 @@\n+import numpy as np\n import torch\n from mmcv.ops import RoIPool\n from mmcv.parallel import collate, scatter\n \n+from mmdet.datasets import replace_ImageToTensor\n from mmdet.datasets.pipelines import Compose\n \n \n@@ -10,18 +12,33 @@\n \n Args:\n model (nn.Module): The loaded detector.\n- imgs (str): Image files.\n+ imgs (str/ndarray): Image files.\n \n Returns:\n result (dict): Detection results.\n \"\"\"\n- assert isinstance(img, str)\n+\n+ assert isinstance(img, (str, np.ndarray))\n \n cfg = model.cfg\n device = next(model.parameters()).device # model device\n- data = dict(img_info=dict(filename=img), img_prefix=None)\n- # build the data pipeline\n+\n+ if isinstance(img, np.ndarray):\n+ cfg = cfg.copy()\n+ # set loading pipeline type\n+ cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam'\n+\n+ cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline)\n test_pipeline = Compose(cfg.data.test.pipeline)\n+\n+ if isinstance(img, np.ndarray):\n+ # directly add img\n+ data = dict(img=img)\n+ else:\n+ # add information into dict\n+ data = dict(img_info=dict(filename=img), img_prefix=None)\n+\n+ # build the data pipeline\n data = test_pipeline(data)\n data = collate([data], samples_per_gpu=1)\n", "issue": "Webcam demo script is not working properly\n**Checklist**\r\n\r\n1. I have searched related issues but cannot get the expected help: Yes\r\n2. The bug has not been fixed in the latest version: Yes\r\n\r\n**Describe the bug**\r\n\r\nThe current model_inference function expects to receive a model and a path to an image as inputs but the webcam demo scripts tries to call it with a model and a numpy array (the return value from cv2.VideoCapture.read()). \r\n\r\nThis raises an assertion error due to type mismatch (np.ndarray vs str)\r\n\r\n**Reproduction**\r\n\r\n1. What command or script did you run?\r\n\r\n```none\r\npython demo/webcam_demo.py\r\n```\r\n\r\n2. Did you make any modifications on the code or config? Did you understand what you have modified?\r\n\r\nNo.\r\n\r\n3. What dataset did you use?\r\n\r\n**Environment**\r\n\r\n1. Please run `python mmocr/utils/collect_env.py` to collect necessary environment information and paste it here.\r\n\r\nsys.platform: linux\r\nPython: 3.7.10 | packaged by conda-forge | (default, Feb 19 2021, 16:07:37) [GCC 9.3.0]\r\nCUDA available: True\r\nGPU 0: GeForce GTX 1050 Ti\r\nCUDA_HOME: /usr/local/cuda\r\nNVCC: Build cuda_11.1.TC455_06.29190527_0\r\nGCC: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0\r\nPyTorch: 1.5.0\r\nPyTorch compiling details: PyTorch built with:\r\n - GCC 7.3\r\n - C++ Version: 201402\r\n - Intel(R) Math Kernel Library Version 2020.0.4 Product Build 20200917 for Intel(R) 64 architecture applications\r\n - Intel(R) MKL-DNN v0.21.1 (Git Hash 7d2fd500bc78936d1d648ca713b901012f470dbc)\r\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\r\n - NNPACK is enabled\r\n - CPU capability usage: AVX2\r\n - CUDA Runtime 10.1\r\n - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_37,code=compute_37\r\n - CuDNN 7.6.3\r\n - Magma 2.5.2\r\n - Build settings: BLAS=MKL, BUILD_TYPE=Release, CXX_FLAGS= -Wno-deprecated -fvisibility-inlines-hidden -fopenmp -DNDEBUG -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DUSE_INTERNAL_THREADPOOL_IMPL -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, USE_CUDA=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=ON, USE_NNPACK=ON, USE_OPENMP=ON, USE_STATIC_DISPATCH=OFF, \r\n\r\nTorchVision: 0.6.0a0+82fd1c8\r\nOpenCV: 4.5.1\r\nMMCV: 1.2.7\r\nMMCV Compiler: GCC 9.3\r\nMMCV CUDA Compiler: not available\r\nMMOCR: 0.1.0+344cc9a\r\n\r\n2. You may add addition that may be helpful for locating the problem, such as\r\n - How you installed PyTorch: conda\r\n\r\n**Error traceback**\r\n\r\n```none\r\nUse load_from_local loader\r\nPress \"Esc\", \"q\" or \"Q\" to exit.\r\nTraceback (most recent call last):\r\n File \"demo/webcam_demo.py\", line 52, in <module>\r\n main()\r\n File \"demo/webcam_demo.py\", line 41, in main\r\n result = model_inference(model, img)\r\n File \"/home/sbugallo/Projects/mmocr/mmocr/apis/inference.py\", line 18, in model_inference\r\n assert isinstance(img, str)\r\nAssertionError\r\n```\r\n\r\n**Bug fix**\r\n\r\nThe inference method should accept the following types as input image(s) (str/ndarray or list[str/ndarray] or tuple[str/ndarray]) like in MMDetection\n", "before_files": [{"content": "import torch\nfrom mmcv.ops import RoIPool\nfrom mmcv.parallel import collate, scatter\n\nfrom mmdet.datasets.pipelines import Compose\n\n\ndef model_inference(model, img):\n \"\"\"Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str): Image files.\n\n Returns:\n result (dict): Detection results.\n \"\"\"\n assert isinstance(img, str)\n\n cfg = model.cfg\n device = next(model.parameters()).device # model device\n data = dict(img_info=dict(filename=img), img_prefix=None)\n # build the data pipeline\n test_pipeline = Compose(cfg.data.test.pipeline)\n data = test_pipeline(data)\n data = collate([data], samples_per_gpu=1)\n\n # process img_metas\n if isinstance(data['img_metas'], list):\n data['img_metas'] = data['img_metas'][0].data\n else:\n data['img_metas'] = data['img_metas'].data[0]\n\n if next(model.parameters()).is_cuda:\n # scatter to specified GPU\n data = scatter(data, [device])[0]\n else:\n for m in model.modules():\n assert not isinstance(\n m, RoIPool\n ), 'CPU inference with RoIPool is not supported currently.'\n\n # forward the model\n with torch.no_grad():\n result = model(return_loss=False, rescale=True, **data)[0]\n return result\n", "path": "mmocr/apis/inference.py"}], "after_files": [{"content": "import numpy as np\nimport torch\nfrom mmcv.ops import RoIPool\nfrom mmcv.parallel import collate, scatter\n\nfrom mmdet.datasets import replace_ImageToTensor\nfrom mmdet.datasets.pipelines import Compose\n\n\ndef model_inference(model, img):\n \"\"\"Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str/ndarray): Image files.\n\n Returns:\n result (dict): Detection results.\n \"\"\"\n\n assert isinstance(img, (str, np.ndarray))\n\n cfg = model.cfg\n device = next(model.parameters()).device # model device\n\n if isinstance(img, np.ndarray):\n cfg = cfg.copy()\n # set loading pipeline type\n cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam'\n\n cfg.data.test.pipeline = replace_ImageToTensor(cfg.data.test.pipeline)\n test_pipeline = Compose(cfg.data.test.pipeline)\n\n if isinstance(img, np.ndarray):\n # directly add img\n data = dict(img=img)\n else:\n # add information into dict\n data = dict(img_info=dict(filename=img), img_prefix=None)\n\n # build the data pipeline\n data = test_pipeline(data)\n data = collate([data], samples_per_gpu=1)\n\n # process img_metas\n if isinstance(data['img_metas'], list):\n data['img_metas'] = data['img_metas'][0].data\n else:\n data['img_metas'] = data['img_metas'].data[0]\n\n if next(model.parameters()).is_cuda:\n # scatter to specified GPU\n data = scatter(data, [device])[0]\n else:\n for m in model.modules():\n assert not isinstance(\n m, RoIPool\n ), 'CPU inference with RoIPool is not supported currently.'\n\n # forward the model\n with torch.no_grad():\n result = model(return_loss=False, rescale=True, **data)[0]\n return result\n", "path": "mmocr/apis/inference.py"}]}
1,975
378
gh_patches_debug_61040
rasdani/github-patches
git_diff
google-research__text-to-text-transfer-transformer-480
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Running hf_model.py I am trying to run your models with [`hf_model`](https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/models/hf_model.py). The current blocker issue is that the code is using `num_parallel_calls` in [in multiple places](https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/models/hf_model.py#L128), however, this function seems to be [deprecated](https://github.com/google-research/text-to-text-transfer-transformer/blob/838157d433995473e96b773c9c761b6aadf01e37/t5/data/preprocessors.py#L2651). Wondering if there is a replacement for this function I can use as a quick fix. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `t5/version.py` Content: ``` 1 # Copyright 2020 The T5 Authors. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 # Lint as: python3 16 r"""Separate file for storing the current version of T5. 17 18 Stored in a separate file so that setup.py can reference the version without 19 pulling in all the dependencies in __init__.py. 20 """ 21 __version__ = '0.7.0' 22 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/t5/version.py b/t5/version.py --- a/t5/version.py +++ b/t5/version.py @@ -18,4 +18,4 @@ Stored in a separate file so that setup.py can reference the version without pulling in all the dependencies in __init__.py. """ -__version__ = '0.7.0' +__version__ = '0.7.1'
{"golden_diff": "diff --git a/t5/version.py b/t5/version.py\n--- a/t5/version.py\n+++ b/t5/version.py\n@@ -18,4 +18,4 @@\n Stored in a separate file so that setup.py can reference the version without\n pulling in all the dependencies in __init__.py.\n \"\"\"\n-__version__ = '0.7.0'\n+__version__ = '0.7.1'\n", "issue": "Running hf_model.py \nI am trying to run your models with [`hf_model`](https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/models/hf_model.py). The current blocker issue is that the code is using `num_parallel_calls` in [in multiple places](https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/models/hf_model.py#L128), however, this function seems to be [deprecated](https://github.com/google-research/text-to-text-transfer-transformer/blob/838157d433995473e96b773c9c761b6aadf01e37/t5/data/preprocessors.py#L2651).\r\n\r\nWondering if there is a replacement for this function I can use as a quick fix. \n", "before_files": [{"content": "# Copyright 2020 The T5 Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\nr\"\"\"Separate file for storing the current version of T5.\n\nStored in a separate file so that setup.py can reference the version without\npulling in all the dependencies in __init__.py.\n\"\"\"\n__version__ = '0.7.0'\n", "path": "t5/version.py"}], "after_files": [{"content": "# Copyright 2020 The T5 Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\nr\"\"\"Separate file for storing the current version of T5.\n\nStored in a separate file so that setup.py can reference the version without\npulling in all the dependencies in __init__.py.\n\"\"\"\n__version__ = '0.7.1'\n", "path": "t5/version.py"}]}
673
91
gh_patches_debug_21897
rasdani/github-patches
git_diff
weecology__retriever-1267
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- fetch method should return an ordered dict (not a dict) Hello, I noticed that `fetch` method returns a dict of dataframes. To preserve order of tables (which may have a meaning) it should return an ordered dict. [Datapackage](https://frictionlessdata.io/specs/data-package/) ressources are stored in a list so it's ordered. Kind regards --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `retriever/engines/sqlite.py` Content: ``` 1 import os 2 import pandas as pd 3 from builtins import range 4 5 from retriever.lib.defaults import DATA_DIR 6 from retriever.lib.models import Engine, no_cleanup 7 8 9 class engine(Engine): 10 """Engine instance for SQLite.""" 11 12 name = "SQLite" 13 abbreviation = "sqlite" 14 datatypes = { 15 "auto": ("INTEGER", "AUTOINCREMENT"), 16 "int": "INTEGER", 17 "bigint": "INTEGER", 18 "double": "REAL", 19 "decimal": "REAL", 20 "char": "TEXT", 21 "bool": "INTEGER", 22 } 23 placeholder = "?" 24 insert_limit = 1000 25 required_opts = [("file", 26 "Enter the filename of your SQLite database", 27 "sqlite.db"), 28 ("table_name", 29 "Format of table name", 30 "{db}_{table}"), 31 ("data_dir", 32 "Install directory", 33 DATA_DIR), 34 ] 35 36 def create_db(self): 37 """Don't create database for SQLite 38 39 SQLite doesn't create databases. Each database is a file and needs a separate 40 connection. This overloads`create_db` to do nothing in this case. 41 """ 42 return None 43 44 def fetch_tables(self, dataset, table_names): 45 """Return sqlite dataset as list of pandas dataframe.""" 46 connection = self.get_connection() 47 data = {table[len(dataset) + 1:]: pd.read_sql_query("SELECT * " 48 "FROM {};".format(table), 49 connection) 50 for table in table_names} 51 return data 52 53 def get_bulk_insert_statement(self): 54 """Get insert statement for bulk inserts 55 56 This places ?'s instead of the actual values so that executemany() can 57 operate as designed 58 """ 59 columns = self.table.get_insert_columns() 60 column_count = len(self.table.get_insert_columns(False)) 61 insert_stmt = "INSERT INTO " + self.table_name() 62 insert_stmt += " (" + columns + ")" 63 insert_stmt += " VALUES (" 64 for _ in range(0, column_count): 65 insert_stmt += "?, " 66 insert_stmt = insert_stmt.rstrip(", ") + ")" 67 return insert_stmt 68 69 def insert_data_from_file(self, filename): 70 """Perform a high speed bulk insert 71 72 Checks to see if a given file can be bulk inserted, and if so loads 73 it in chunks and inserts those chunks into the database using 74 executemany. 75 """ 76 chunk_size = 1000000 77 self.get_cursor() 78 79 # Determine if the dataset includes cross-tab data 80 crosstab = len([True for c in self.table.columns if c[1][0][:3] == "ct-"]) != 0 81 82 if (([self.table.cleanup.function, self.table.header_rows] == [no_cleanup, 1]) 83 and not self.table.fixed_width 84 and not crosstab 85 and (not hasattr(self.table, "do_not_bulk_insert") or not self.table.do_not_bulk_insert)): 86 filename = os.path.abspath(filename) 87 try: 88 bulk_insert_statement = self.get_bulk_insert_statement() 89 line_endings = set(['\n', '\r', '\r\n']) 90 with open(filename, 'r') as data_file: 91 data_chunk = data_file.readlines(chunk_size) 92 data_chunk = [line.rstrip('\r\n') for line in data_chunk if line not in line_endings] 93 del data_chunk[:self.table.header_rows] 94 while data_chunk: 95 data_chunk_split = [row.split(self.table.delimiter) 96 for row in data_chunk] 97 self.cursor.executemany(bulk_insert_statement, data_chunk_split) 98 data_chunk = data_file.readlines(chunk_size) 99 self.connection.commit() 100 except: 101 self.connection.rollback() 102 return Engine.insert_data_from_file(self, filename) 103 else: 104 return Engine.insert_data_from_file(self, filename) 105 106 def get_connection(self): 107 """Get db connection.""" 108 import sqlite3 as dbapi 109 110 self.get_input() 111 file = self.opts["file"] 112 db_file = self.opts["data_dir"] 113 full_path = os.path.join(db_file, file) 114 115 return dbapi.connect(os.path.normpath(full_path)) 116 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/retriever/engines/sqlite.py b/retriever/engines/sqlite.py --- a/retriever/engines/sqlite.py +++ b/retriever/engines/sqlite.py @@ -1,6 +1,7 @@ import os import pandas as pd from builtins import range +from collections import OrderedDict from retriever.lib.defaults import DATA_DIR from retriever.lib.models import Engine, no_cleanup @@ -44,10 +45,12 @@ def fetch_tables(self, dataset, table_names): """Return sqlite dataset as list of pandas dataframe.""" connection = self.get_connection() - data = {table[len(dataset) + 1:]: pd.read_sql_query("SELECT * " - "FROM {};".format(table), - connection) - for table in table_names} + sql_query = "SELECT * FROM {};" + data = OrderedDict({ + table[len(dataset) + 1:] + :pd.read_sql_query(sql_query.format(table), connection) + for table in table_names + }) return data def get_bulk_insert_statement(self):
{"golden_diff": "diff --git a/retriever/engines/sqlite.py b/retriever/engines/sqlite.py\n--- a/retriever/engines/sqlite.py\n+++ b/retriever/engines/sqlite.py\n@@ -1,6 +1,7 @@\n import os\n import pandas as pd\n from builtins import range\n+from collections import OrderedDict\n \n from retriever.lib.defaults import DATA_DIR\n from retriever.lib.models import Engine, no_cleanup\n@@ -44,10 +45,12 @@\n def fetch_tables(self, dataset, table_names):\n \"\"\"Return sqlite dataset as list of pandas dataframe.\"\"\"\n connection = self.get_connection()\n- data = {table[len(dataset) + 1:]: pd.read_sql_query(\"SELECT * \"\n- \"FROM {};\".format(table),\n- connection)\n- for table in table_names}\n+ sql_query = \"SELECT * FROM {};\"\n+ data = OrderedDict({\n+ table[len(dataset) + 1:]\n+ :pd.read_sql_query(sql_query.format(table), connection)\n+ for table in table_names\n+ })\n return data\n \n def get_bulk_insert_statement(self):\n", "issue": "fetch method should return an ordered dict (not a dict)\nHello,\r\n\r\nI noticed that `fetch` method returns a dict of dataframes.\r\nTo preserve order of tables (which may have a meaning) it should return an ordered dict.\r\n[Datapackage](https://frictionlessdata.io/specs/data-package/) ressources are stored in a list so it's ordered.\r\n\r\nKind regards\n", "before_files": [{"content": "import os\nimport pandas as pd\nfrom builtins import range\n\nfrom retriever.lib.defaults import DATA_DIR\nfrom retriever.lib.models import Engine, no_cleanup\n\n\nclass engine(Engine):\n \"\"\"Engine instance for SQLite.\"\"\"\n\n name = \"SQLite\"\n abbreviation = \"sqlite\"\n datatypes = {\n \"auto\": (\"INTEGER\", \"AUTOINCREMENT\"),\n \"int\": \"INTEGER\",\n \"bigint\": \"INTEGER\",\n \"double\": \"REAL\",\n \"decimal\": \"REAL\",\n \"char\": \"TEXT\",\n \"bool\": \"INTEGER\",\n }\n placeholder = \"?\"\n insert_limit = 1000\n required_opts = [(\"file\",\n \"Enter the filename of your SQLite database\",\n \"sqlite.db\"),\n (\"table_name\",\n \"Format of table name\",\n \"{db}_{table}\"),\n (\"data_dir\",\n \"Install directory\",\n DATA_DIR),\n ]\n\n def create_db(self):\n \"\"\"Don't create database for SQLite\n\n SQLite doesn't create databases. Each database is a file and needs a separate\n connection. This overloads`create_db` to do nothing in this case.\n \"\"\"\n return None\n\n def fetch_tables(self, dataset, table_names):\n \"\"\"Return sqlite dataset as list of pandas dataframe.\"\"\"\n connection = self.get_connection()\n data = {table[len(dataset) + 1:]: pd.read_sql_query(\"SELECT * \"\n \"FROM {};\".format(table),\n connection)\n for table in table_names}\n return data\n\n def get_bulk_insert_statement(self):\n \"\"\"Get insert statement for bulk inserts\n\n This places ?'s instead of the actual values so that executemany() can\n operate as designed\n \"\"\"\n columns = self.table.get_insert_columns()\n column_count = len(self.table.get_insert_columns(False))\n insert_stmt = \"INSERT INTO \" + self.table_name()\n insert_stmt += \" (\" + columns + \")\"\n insert_stmt += \" VALUES (\"\n for _ in range(0, column_count):\n insert_stmt += \"?, \"\n insert_stmt = insert_stmt.rstrip(\", \") + \")\"\n return insert_stmt\n\n def insert_data_from_file(self, filename):\n \"\"\"Perform a high speed bulk insert\n\n Checks to see if a given file can be bulk inserted, and if so loads\n it in chunks and inserts those chunks into the database using\n executemany.\n \"\"\"\n chunk_size = 1000000\n self.get_cursor()\n\n # Determine if the dataset includes cross-tab data\n crosstab = len([True for c in self.table.columns if c[1][0][:3] == \"ct-\"]) != 0\n\n if (([self.table.cleanup.function, self.table.header_rows] == [no_cleanup, 1])\n and not self.table.fixed_width\n and not crosstab\n and (not hasattr(self.table, \"do_not_bulk_insert\") or not self.table.do_not_bulk_insert)):\n filename = os.path.abspath(filename)\n try:\n bulk_insert_statement = self.get_bulk_insert_statement()\n line_endings = set(['\\n', '\\r', '\\r\\n'])\n with open(filename, 'r') as data_file:\n data_chunk = data_file.readlines(chunk_size)\n data_chunk = [line.rstrip('\\r\\n') for line in data_chunk if line not in line_endings]\n del data_chunk[:self.table.header_rows]\n while data_chunk:\n data_chunk_split = [row.split(self.table.delimiter)\n for row in data_chunk]\n self.cursor.executemany(bulk_insert_statement, data_chunk_split)\n data_chunk = data_file.readlines(chunk_size)\n self.connection.commit()\n except:\n self.connection.rollback()\n return Engine.insert_data_from_file(self, filename)\n else:\n return Engine.insert_data_from_file(self, filename)\n\n def get_connection(self):\n \"\"\"Get db connection.\"\"\"\n import sqlite3 as dbapi\n\n self.get_input()\n file = self.opts[\"file\"]\n db_file = self.opts[\"data_dir\"]\n full_path = os.path.join(db_file, file)\n\n return dbapi.connect(os.path.normpath(full_path))\n", "path": "retriever/engines/sqlite.py"}], "after_files": [{"content": "import os\nimport pandas as pd\nfrom builtins import range\nfrom collections import OrderedDict\n\nfrom retriever.lib.defaults import DATA_DIR\nfrom retriever.lib.models import Engine, no_cleanup\n\n\nclass engine(Engine):\n \"\"\"Engine instance for SQLite.\"\"\"\n\n name = \"SQLite\"\n abbreviation = \"sqlite\"\n datatypes = {\n \"auto\": (\"INTEGER\", \"AUTOINCREMENT\"),\n \"int\": \"INTEGER\",\n \"bigint\": \"INTEGER\",\n \"double\": \"REAL\",\n \"decimal\": \"REAL\",\n \"char\": \"TEXT\",\n \"bool\": \"INTEGER\",\n }\n placeholder = \"?\"\n insert_limit = 1000\n required_opts = [(\"file\",\n \"Enter the filename of your SQLite database\",\n \"sqlite.db\"),\n (\"table_name\",\n \"Format of table name\",\n \"{db}_{table}\"),\n (\"data_dir\",\n \"Install directory\",\n DATA_DIR),\n ]\n\n def create_db(self):\n \"\"\"Don't create database for SQLite\n\n SQLite doesn't create databases. Each database is a file and needs a separate\n connection. This overloads`create_db` to do nothing in this case.\n \"\"\"\n return None\n\n def fetch_tables(self, dataset, table_names):\n \"\"\"Return sqlite dataset as list of pandas dataframe.\"\"\"\n connection = self.get_connection()\n sql_query = \"SELECT * FROM {};\"\n data = OrderedDict({\n table[len(dataset) + 1:]\n :pd.read_sql_query(sql_query.format(table), connection)\n for table in table_names\n })\n return data\n\n def get_bulk_insert_statement(self):\n \"\"\"Get insert statement for bulk inserts\n\n This places ?'s instead of the actual values so that executemany() can\n operate as designed\n \"\"\"\n columns = self.table.get_insert_columns()\n column_count = len(self.table.get_insert_columns(False))\n insert_stmt = \"INSERT INTO \" + self.table_name()\n insert_stmt += \" (\" + columns + \")\"\n insert_stmt += \" VALUES (\"\n for _ in range(0, column_count):\n insert_stmt += \"?, \"\n insert_stmt = insert_stmt.rstrip(\", \") + \")\"\n return insert_stmt\n\n def insert_data_from_file(self, filename):\n \"\"\"Perform a high speed bulk insert\n\n Checks to see if a given file can be bulk inserted, and if so loads\n it in chunks and inserts those chunks into the database using\n executemany.\n \"\"\"\n chunk_size = 1000000\n self.get_cursor()\n\n # Determine if the dataset includes cross-tab data\n crosstab = len([True for c in self.table.columns if c[1][0][:3] == \"ct-\"]) != 0\n\n if (([self.table.cleanup.function, self.table.header_rows] == [no_cleanup, 1])\n and not self.table.fixed_width\n and not crosstab\n and (not hasattr(self.table, \"do_not_bulk_insert\") or not self.table.do_not_bulk_insert)):\n filename = os.path.abspath(filename)\n try:\n bulk_insert_statement = self.get_bulk_insert_statement()\n line_endings = set(['\\n', '\\r', '\\r\\n'])\n with open(filename, 'r') as data_file:\n data_chunk = data_file.readlines(chunk_size)\n data_chunk = [line.rstrip('\\r\\n') for line in data_chunk if line not in line_endings]\n del data_chunk[:self.table.header_rows]\n while data_chunk:\n data_chunk_split = [row.split(self.table.delimiter)\n for row in data_chunk]\n self.cursor.executemany(bulk_insert_statement, data_chunk_split)\n data_chunk = data_file.readlines(chunk_size)\n self.connection.commit()\n except:\n self.connection.rollback()\n return Engine.insert_data_from_file(self, filename)\n else:\n return Engine.insert_data_from_file(self, filename)\n\n def get_connection(self):\n \"\"\"Get db connection.\"\"\"\n import sqlite3 as dbapi\n\n self.get_input()\n file = self.opts[\"file\"]\n db_file = self.opts[\"data_dir\"]\n full_path = os.path.join(db_file, file)\n\n return dbapi.connect(os.path.normpath(full_path))\n", "path": "retriever/engines/sqlite.py"}]}
1,473
248
gh_patches_debug_8515
rasdani/github-patches
git_diff
Gallopsled__pwntools-1892
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- phd throws an exception when output pipe fails, as with e.g. `head` We should silence the BrokenPipeError exception when `pwn phd` output closes. ``` $ phd < /dev/random | head -n 1 00000000 43 18 3f 38 0e 45 9c 5d d9 b8 ed 44 7c 64 ee e3 │C·?8│·E·]│···D│|d··│ Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'> BrokenPipeError: [Errno 32] Broken pipe ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pwnlib/commandline/phd.py` Content: ``` 1 #!/usr/bin/env python2 2 from __future__ import absolute_import 3 from __future__ import division 4 5 import argparse 6 import os 7 import sys 8 import io 9 10 import pwnlib.args 11 pwnlib.args.free_form = False 12 13 from pwn import * 14 from pwnlib.commandline import common 15 16 parser = common.parser_commands.add_parser( 17 'phd', 18 help = 'Pretty hex dump', 19 description = 'Pretty hex dump' 20 ) 21 22 parser.add_argument( 23 'file', 24 metavar='file', 25 nargs='?', 26 help='File to hexdump. Reads from stdin if missing.', 27 type=argparse.FileType('rb'), 28 default=getattr(sys.stdin, 'buffer', sys.stdin) 29 ) 30 31 parser.add_argument( 32 "-w", "--width", 33 help="Number of bytes per line.", 34 default='16', 35 ) 36 37 parser.add_argument( 38 "-l", "--highlight", 39 help="Byte to highlight.", 40 nargs="*", 41 ) 42 43 parser.add_argument( 44 "-s", "--skip", 45 help="Skip this many initial bytes.", 46 default='0', 47 ) 48 49 parser.add_argument( 50 "-c", "--count", 51 help="Only show this many bytes.", 52 default='-1', 53 ) 54 55 parser.add_argument( 56 "-o", "--offset", 57 help="Addresses in left hand column starts at this address.", 58 default='0', 59 ) 60 61 parser.add_argument( 62 "--color", 63 nargs='?', 64 help="Colorize the output. When 'auto' output is colorized exactly when stdout is a TTY. Default is 'auto'.", 65 choices = ('always', 'never', 'auto'), 66 default='auto', 67 ) 68 69 def asint(s): 70 if s.startswith('0x'): 71 return int(s, 16) 72 elif s.startswith('0'): 73 return int(s, 8) 74 else: 75 return int(s, 10) 76 77 def main(args): 78 infile = args.file 79 width = asint(args.width) 80 skip = asint(args.skip) 81 count = asint(args.count) 82 offset = asint(args.offset) 83 84 # if `--color` has no argument it is `None` 85 color = args.color or 'always' 86 text.when = color 87 88 if skip: 89 try: 90 infile.seek(skip, os.SEEK_CUR) 91 except IOError: 92 infile.read(skip) 93 94 if count != -1: 95 infile = io.BytesIO(infile.read(count)) 96 97 hl = [] 98 if args.highlight: 99 for hs in args.highlight: 100 for h in hs.split(','): 101 hl.append(asint(h)) 102 103 try: 104 for line in hexdump_iter(infile, width, highlight = hl, begin = offset + skip): 105 print(line) 106 except (KeyboardInterrupt, IOError): 107 pass 108 109 if __name__ == '__main__': 110 pwnlib.commandline.common.main(__file__) 111 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pwnlib/commandline/phd.py b/pwnlib/commandline/phd.py --- a/pwnlib/commandline/phd.py +++ b/pwnlib/commandline/phd.py @@ -4,6 +4,7 @@ import argparse import os +import signal import sys import io @@ -100,6 +101,8 @@ for h in hs.split(','): hl.append(asint(h)) + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + try: for line in hexdump_iter(infile, width, highlight = hl, begin = offset + skip): print(line)
{"golden_diff": "diff --git a/pwnlib/commandline/phd.py b/pwnlib/commandline/phd.py\n--- a/pwnlib/commandline/phd.py\n+++ b/pwnlib/commandline/phd.py\n@@ -4,6 +4,7 @@\n \n import argparse\n import os\n+import signal\n import sys\n import io\n \n@@ -100,6 +101,8 @@\n for h in hs.split(','):\n hl.append(asint(h))\n \n+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n+\n try:\n for line in hexdump_iter(infile, width, highlight = hl, begin = offset + skip):\n print(line)\n", "issue": "phd throws an exception when output pipe fails, as with e.g. `head`\nWe should silence the BrokenPipeError exception when `pwn phd` output closes.\r\n\r\n```\r\n$ phd < /dev/random | head -n 1\r\n00000000 43 18 3f 38 0e 45 9c 5d d9 b8 ed 44 7c 64 ee e3 \u2502C\u00b7?8\u2502\u00b7E\u00b7]\u2502\u00b7\u00b7\u00b7D\u2502|d\u00b7\u00b7\u2502\r\nException ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>\r\nBrokenPipeError: [Errno 32] Broken pipe\r\n```\n", "before_files": [{"content": "#!/usr/bin/env python2\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport argparse\nimport os\nimport sys\nimport io\n\nimport pwnlib.args\npwnlib.args.free_form = False\n\nfrom pwn import *\nfrom pwnlib.commandline import common\n\nparser = common.parser_commands.add_parser(\n 'phd',\n help = 'Pretty hex dump',\n description = 'Pretty hex dump'\n)\n\nparser.add_argument(\n 'file',\n metavar='file',\n nargs='?',\n help='File to hexdump. Reads from stdin if missing.',\n type=argparse.FileType('rb'),\n default=getattr(sys.stdin, 'buffer', sys.stdin)\n)\n\nparser.add_argument(\n \"-w\", \"--width\",\n help=\"Number of bytes per line.\",\n default='16',\n)\n\nparser.add_argument(\n \"-l\", \"--highlight\",\n help=\"Byte to highlight.\",\n nargs=\"*\",\n)\n\nparser.add_argument(\n \"-s\", \"--skip\",\n help=\"Skip this many initial bytes.\",\n default='0',\n)\n\nparser.add_argument(\n \"-c\", \"--count\",\n help=\"Only show this many bytes.\",\n default='-1',\n)\n\nparser.add_argument(\n \"-o\", \"--offset\",\n help=\"Addresses in left hand column starts at this address.\",\n default='0',\n)\n\nparser.add_argument(\n \"--color\",\n nargs='?',\n help=\"Colorize the output. When 'auto' output is colorized exactly when stdout is a TTY. Default is 'auto'.\",\n choices = ('always', 'never', 'auto'),\n default='auto',\n)\n\ndef asint(s):\n if s.startswith('0x'):\n return int(s, 16)\n elif s.startswith('0'):\n return int(s, 8)\n else:\n return int(s, 10)\n\ndef main(args):\n infile = args.file\n width = asint(args.width)\n skip = asint(args.skip)\n count = asint(args.count)\n offset = asint(args.offset)\n\n # if `--color` has no argument it is `None`\n color = args.color or 'always'\n text.when = color\n\n if skip:\n try:\n infile.seek(skip, os.SEEK_CUR)\n except IOError:\n infile.read(skip)\n\n if count != -1:\n infile = io.BytesIO(infile.read(count))\n\n hl = []\n if args.highlight:\n for hs in args.highlight:\n for h in hs.split(','):\n hl.append(asint(h))\n\n try:\n for line in hexdump_iter(infile, width, highlight = hl, begin = offset + skip):\n print(line)\n except (KeyboardInterrupt, IOError):\n pass\n\nif __name__ == '__main__':\n pwnlib.commandline.common.main(__file__)\n", "path": "pwnlib/commandline/phd.py"}], "after_files": [{"content": "#!/usr/bin/env python2\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport argparse\nimport os\nimport signal\nimport sys\nimport io\n\nimport pwnlib.args\npwnlib.args.free_form = False\n\nfrom pwn import *\nfrom pwnlib.commandline import common\n\nparser = common.parser_commands.add_parser(\n 'phd',\n help = 'Pretty hex dump',\n description = 'Pretty hex dump'\n)\n\nparser.add_argument(\n 'file',\n metavar='file',\n nargs='?',\n help='File to hexdump. Reads from stdin if missing.',\n type=argparse.FileType('rb'),\n default=getattr(sys.stdin, 'buffer', sys.stdin)\n)\n\nparser.add_argument(\n \"-w\", \"--width\",\n help=\"Number of bytes per line.\",\n default='16',\n)\n\nparser.add_argument(\n \"-l\", \"--highlight\",\n help=\"Byte to highlight.\",\n nargs=\"*\",\n)\n\nparser.add_argument(\n \"-s\", \"--skip\",\n help=\"Skip this many initial bytes.\",\n default='0',\n)\n\nparser.add_argument(\n \"-c\", \"--count\",\n help=\"Only show this many bytes.\",\n default='-1',\n)\n\nparser.add_argument(\n \"-o\", \"--offset\",\n help=\"Addresses in left hand column starts at this address.\",\n default='0',\n)\n\nparser.add_argument(\n \"--color\",\n nargs='?',\n help=\"Colorize the output. When 'auto' output is colorized exactly when stdout is a TTY. Default is 'auto'.\",\n choices = ('always', 'never', 'auto'),\n default='auto',\n)\n\ndef asint(s):\n if s.startswith('0x'):\n return int(s, 16)\n elif s.startswith('0'):\n return int(s, 8)\n else:\n return int(s, 10)\n\ndef main(args):\n infile = args.file\n width = asint(args.width)\n skip = asint(args.skip)\n count = asint(args.count)\n offset = asint(args.offset)\n\n # if `--color` has no argument it is `None`\n color = args.color or 'always'\n text.when = color\n\n if skip:\n try:\n infile.seek(skip, os.SEEK_CUR)\n except IOError:\n infile.read(skip)\n\n if count != -1:\n infile = io.BytesIO(infile.read(count))\n\n hl = []\n if args.highlight:\n for hs in args.highlight:\n for h in hs.split(','):\n hl.append(asint(h))\n\n signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n\n try:\n for line in hexdump_iter(infile, width, highlight = hl, begin = offset + skip):\n print(line)\n except (KeyboardInterrupt, IOError):\n pass\n\nif __name__ == '__main__':\n pwnlib.commandline.common.main(__file__)\n", "path": "pwnlib/commandline/phd.py"}]}
1,275
143
gh_patches_debug_16435
rasdani/github-patches
git_diff
alltheplaces__alltheplaces-3324
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Spider tapetro is broken During the global build at 2021-10-06-14-42-44, spider **tapetro** failed with **0 features** and **1 errors**. Here's [the log](https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/logs/tapetro.txt) and [the output](https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/output/tapetro.geojson) ([on a map](https://data.alltheplaces.xyz/map.html?show=https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/output/tapetro.geojson)) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `locations/spiders/tapetro.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 import scrapy 3 4 from locations.items import GeojsonPointItem 5 from xlrd import open_workbook 6 7 BRANDS = { 8 'T': 'TravelCenters of America', 9 'P': 'Petro', 10 'TE': 'TA Express' 11 } 12 13 14 class TAPetroSpider(scrapy.Spider): 15 name = 'tapetro' 16 item_attributes = {'brand': "TravelCenters of America", 17 'brand_wikidata': "Q7835892"} 18 allowed_domains = ['www.ta-petro.com'] 19 start_urls = ( 20 'http://www.ta-petro.com/assets/ce/Documents/Master-Location-List.xls', 21 ) 22 23 def parse(self, response): 24 workbook = open_workbook(file_contents=response.body) 25 sheet = workbook.sheets()[0] # Sheet1 26 27 # read header 28 nrow = 0 29 columns = [] 30 for ncol in range(sheet.ncols): 31 columns.append((ncol, sheet.cell(nrow, ncol).value)) 32 33 for nrow in range(1, sheet.nrows): 34 store = {} 35 for ncol, column in columns: 36 value = sheet.cell(nrow, ncol).value 37 store[column] = value 38 39 if not (store.get("LATITUDE") and store.get("LONGITUDE")): 40 continue 41 42 ref = '%s-%s-%s' % ( 43 store['SITE ID#'], store['BRAND'], store['LOCATION_ID']) 44 yield GeojsonPointItem( 45 ref=ref, 46 lat=float(store['LATITUDE']), 47 lon=float(store['LONGITUDE']), 48 name=store['LOCATION'], 49 addr_full=store['ADDRESS'], 50 city=store['CITY'], 51 state=store['STATE'], 52 postcode=store['ZIPCODE'], 53 phone=store['PHONE'], 54 brand=BRANDS.get(store['BRAND'], BRANDS['T']), 55 extras={ 56 'amenity:fuel': True, 57 'fuel:diesel:class2': store['WINTERIZED DIESEL NOV-MAR(any temp)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 10 degrees or below)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 30 degrees or below)'] == 'y', 58 'fuel:diesel': True, 59 'fuel:HGV_diesel': True, 60 'fuel:lng': int(store['LNG(Liquified Natural Gas)/Lanes'] or 0) > 0, 61 'fuel:propane': store['PROPANE'] == 'Y', 62 'hgv': True 63 } 64 ) 65 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/locations/spiders/tapetro.py b/locations/spiders/tapetro.py --- a/locations/spiders/tapetro.py +++ b/locations/spiders/tapetro.py @@ -57,7 +57,7 @@ 'fuel:diesel:class2': store['WINTERIZED DIESEL NOV-MAR(any temp)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 10 degrees or below)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 30 degrees or below)'] == 'y', 'fuel:diesel': True, 'fuel:HGV_diesel': True, - 'fuel:lng': int(store['LNG(Liquified Natural Gas)/Lanes'] or 0) > 0, + 'fuel:lng': store['LNG(Liquified Natural Gas)'] == 'Y', 'fuel:propane': store['PROPANE'] == 'Y', 'hgv': True }
{"golden_diff": "diff --git a/locations/spiders/tapetro.py b/locations/spiders/tapetro.py\n--- a/locations/spiders/tapetro.py\n+++ b/locations/spiders/tapetro.py\n@@ -57,7 +57,7 @@\n 'fuel:diesel:class2': store['WINTERIZED DIESEL NOV-MAR(any temp)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 10 degrees or below)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 30 degrees or below)'] == 'y',\n 'fuel:diesel': True,\n 'fuel:HGV_diesel': True,\n- 'fuel:lng': int(store['LNG(Liquified Natural Gas)/Lanes'] or 0) > 0,\n+ 'fuel:lng': store['LNG(Liquified Natural Gas)'] == 'Y',\n 'fuel:propane': store['PROPANE'] == 'Y',\n 'hgv': True\n }\n", "issue": "Spider tapetro is broken\nDuring the global build at 2021-10-06-14-42-44, spider **tapetro** failed with **0 features** and **1 errors**.\n\nHere's [the log](https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/logs/tapetro.txt) and [the output](https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/output/tapetro.geojson) ([on a map](https://data.alltheplaces.xyz/map.html?show=https://data.alltheplaces.xyz/runs/2021-10-06-14-42-44/output/tapetro.geojson))\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom locations.items import GeojsonPointItem\nfrom xlrd import open_workbook\n\nBRANDS = {\n 'T': 'TravelCenters of America',\n 'P': 'Petro',\n 'TE': 'TA Express'\n}\n\n\nclass TAPetroSpider(scrapy.Spider):\n name = 'tapetro'\n item_attributes = {'brand': \"TravelCenters of America\",\n 'brand_wikidata': \"Q7835892\"}\n allowed_domains = ['www.ta-petro.com']\n start_urls = (\n 'http://www.ta-petro.com/assets/ce/Documents/Master-Location-List.xls',\n )\n\n def parse(self, response):\n workbook = open_workbook(file_contents=response.body)\n sheet = workbook.sheets()[0] # Sheet1\n\n # read header\n nrow = 0\n columns = []\n for ncol in range(sheet.ncols):\n columns.append((ncol, sheet.cell(nrow, ncol).value))\n\n for nrow in range(1, sheet.nrows):\n store = {}\n for ncol, column in columns:\n value = sheet.cell(nrow, ncol).value\n store[column] = value\n\n if not (store.get(\"LATITUDE\") and store.get(\"LONGITUDE\")):\n continue\n\n ref = '%s-%s-%s' % (\n store['SITE ID#'], store['BRAND'], store['LOCATION_ID'])\n yield GeojsonPointItem(\n ref=ref,\n lat=float(store['LATITUDE']),\n lon=float(store['LONGITUDE']),\n name=store['LOCATION'],\n addr_full=store['ADDRESS'],\n city=store['CITY'],\n state=store['STATE'],\n postcode=store['ZIPCODE'],\n phone=store['PHONE'],\n brand=BRANDS.get(store['BRAND'], BRANDS['T']),\n extras={\n 'amenity:fuel': True,\n 'fuel:diesel:class2': store['WINTERIZED DIESEL NOV-MAR(any temp)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 10 degrees or below)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 30 degrees or below)'] == 'y',\n 'fuel:diesel': True,\n 'fuel:HGV_diesel': True,\n 'fuel:lng': int(store['LNG(Liquified Natural Gas)/Lanes'] or 0) > 0,\n 'fuel:propane': store['PROPANE'] == 'Y',\n 'hgv': True\n }\n )\n", "path": "locations/spiders/tapetro.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nimport scrapy\n\nfrom locations.items import GeojsonPointItem\nfrom xlrd import open_workbook\n\nBRANDS = {\n 'T': 'TravelCenters of America',\n 'P': 'Petro',\n 'TE': 'TA Express'\n}\n\n\nclass TAPetroSpider(scrapy.Spider):\n name = 'tapetro'\n item_attributes = {'brand': \"TravelCenters of America\",\n 'brand_wikidata': \"Q7835892\"}\n allowed_domains = ['www.ta-petro.com']\n start_urls = (\n 'http://www.ta-petro.com/assets/ce/Documents/Master-Location-List.xls',\n )\n\n def parse(self, response):\n workbook = open_workbook(file_contents=response.body)\n sheet = workbook.sheets()[0] # Sheet1\n\n # read header\n nrow = 0\n columns = []\n for ncol in range(sheet.ncols):\n columns.append((ncol, sheet.cell(nrow, ncol).value))\n\n for nrow in range(1, sheet.nrows):\n store = {}\n for ncol, column in columns:\n value = sheet.cell(nrow, ncol).value\n store[column] = value\n\n if not (store.get(\"LATITUDE\") and store.get(\"LONGITUDE\")):\n continue\n\n ref = '%s-%s-%s' % (\n store['SITE ID#'], store['BRAND'], store['LOCATION_ID'])\n yield GeojsonPointItem(\n ref=ref,\n lat=float(store['LATITUDE']),\n lon=float(store['LONGITUDE']),\n name=store['LOCATION'],\n addr_full=store['ADDRESS'],\n city=store['CITY'],\n state=store['STATE'],\n postcode=store['ZIPCODE'],\n phone=store['PHONE'],\n brand=BRANDS.get(store['BRAND'], BRANDS['T']),\n extras={\n 'amenity:fuel': True,\n 'fuel:diesel:class2': store['WINTERIZED DIESEL NOV-MAR(any temp)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 10 degrees or below)'] == 'Y' or store['WINTERIZED DIESEL NOV-MAR (when temps are 30 degrees or below)'] == 'y',\n 'fuel:diesel': True,\n 'fuel:HGV_diesel': True,\n 'fuel:lng': store['LNG(Liquified Natural Gas)'] == 'Y',\n 'fuel:propane': store['PROPANE'] == 'Y',\n 'hgv': True\n }\n )\n", "path": "locations/spiders/tapetro.py"}]}
1,150
233
gh_patches_debug_3412
rasdani/github-patches
git_diff
dynaconf__dynaconf-767
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [bug] filter_strategy config not working **Describe the bug** It seems that the `filter_strategy` config (which by the way is misspelled int the [docs](https://github.com/rochacbruno/dynaconf/blob/master/docs/configuration.md)) is not taken into account when used in the `Dynaconf` constructor. **To Reproduce** Steps to reproduce the behavior: 1. Having the following folder structure Just a plain python script. 2. Having the following config files: No config file, just using env variables 4. Having the following app code: <details> <summary> Code </summary> **/test/test.py** ```python import dynaconf class CustomFilter: def __call__(self, data): print("this is never called") return { k: v for k, v in data.items() if k.startswith("PREFIX") } if __name__ == "__main__": dc = dynaconf.Dynaconf( envvar_prefix=False, filter_strategy=CustomFilter(), ) print(dc.as_dict()) ``` </details> 5. Executing under the following environment <details> <summary> Execution </summary> ```bash PREFIX_VAR="HELLO" OTHER_VAR="WORLD" python test.py ``` </details> **Expected behavior** `CustomFilter` should be called ("this is never called" should be displayed) and only the `PREFIX_VAR` should be in dict, not `OTHER_VAR` **Environment (please complete the following information):** - OS: Linux version 5.10.60.1-microsoft-standard-WSL2 - Dynaconf Version 3.1.9 - Framework: None **Context** I was looking for a way to filter out empty environment variables. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `dynaconf/loaders/env_loader.py` Content: ``` 1 from __future__ import annotations 2 3 from os import environ 4 5 from dynaconf.utils import missing 6 from dynaconf.utils import upperfy 7 from dynaconf.utils.parse_conf import parse_conf_data 8 from dynaconf.vendor.dotenv import cli as dotenv_cli 9 10 11 IDENTIFIER = "env" 12 13 14 def load(obj, env=None, silent=True, key=None): 15 """Loads envvars with prefixes: 16 17 `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_` 18 """ 19 global_prefix = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") 20 if global_prefix is False or global_prefix.upper() != "DYNACONF": 21 load_from_env(obj, "DYNACONF", key, silent, IDENTIFIER + "_global") 22 23 # Load the global env if exists and overwrite everything 24 load_from_env(obj, global_prefix, key, silent, IDENTIFIER + "_global") 25 26 27 def load_from_env( 28 obj, 29 prefix=False, 30 key=None, 31 silent=False, 32 identifier=IDENTIFIER, 33 env=False, # backwards compatibility bc renamed param 34 ): 35 if prefix is False and env is not False: 36 prefix = env 37 38 env_ = "" 39 if prefix is not False: 40 if not isinstance(prefix, str): 41 raise TypeError("`prefix/env` must be str or False") 42 43 prefix = prefix.upper() 44 env_ = f"{prefix}_" 45 46 # Load a single environment variable explicitly. 47 if key: 48 key = upperfy(key) 49 value = environ.get(f"{env_}{key}") 50 if value: 51 try: # obj is a Settings 52 obj.set(key, value, loader_identifier=identifier, tomlfy=True) 53 except AttributeError: # obj is a dict 54 obj[key] = parse_conf_data( 55 value, tomlfy=True, box_settings=obj 56 ) 57 58 # Load environment variables in bulk (when matching). 59 else: 60 # Only known variables should be loaded from environment? 61 ignore_unknown = obj.get("IGNORE_UNKNOWN_ENVVARS_FOR_DYNACONF") 62 63 trim_len = len(env_) 64 data = { 65 key[trim_len:]: parse_conf_data( 66 data, tomlfy=True, box_settings=obj 67 ) 68 for key, data in environ.items() 69 if key.startswith(env_) 70 and not ( 71 # Ignore environment variables that haven't been 72 # pre-defined in settings space. 73 ignore_unknown 74 and obj.get(key[trim_len:], default=missing) is missing 75 ) 76 } 77 # Update the settings space based on gathered data from environment. 78 if data: 79 obj.update(data, loader_identifier=identifier) 80 81 82 def write(settings_path, settings_data, **kwargs): 83 """Write data to .env file""" 84 for key, value in settings_data.items(): 85 quote_mode = ( 86 isinstance(value, str) 87 and (value.startswith("'") or value.startswith('"')) 88 ) or isinstance(value, (list, dict)) 89 dotenv_cli.set_key( 90 str(settings_path), 91 key, 92 str(value), 93 quote_mode="always" if quote_mode else "none", 94 ) 95 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/dynaconf/loaders/env_loader.py b/dynaconf/loaders/env_loader.py --- a/dynaconf/loaders/env_loader.py +++ b/dynaconf/loaders/env_loader.py @@ -76,6 +76,9 @@ } # Update the settings space based on gathered data from environment. if data: + filter_strategy = obj.get("FILTER_STRATEGY") + if filter_strategy: + data = filter_strategy(data) obj.update(data, loader_identifier=identifier)
{"golden_diff": "diff --git a/dynaconf/loaders/env_loader.py b/dynaconf/loaders/env_loader.py\n--- a/dynaconf/loaders/env_loader.py\n+++ b/dynaconf/loaders/env_loader.py\n@@ -76,6 +76,9 @@\n }\n # Update the settings space based on gathered data from environment.\n if data:\n+ filter_strategy = obj.get(\"FILTER_STRATEGY\")\n+ if filter_strategy:\n+ data = filter_strategy(data)\n obj.update(data, loader_identifier=identifier)\n", "issue": "[bug] filter_strategy config not working\n**Describe the bug**\r\nIt seems that the `filter_strategy` config (which by the way is misspelled int the [docs](https://github.com/rochacbruno/dynaconf/blob/master/docs/configuration.md)) is not taken into account when used in the `Dynaconf` constructor.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n\r\n1. Having the following folder structure\r\nJust a plain python script.\r\n\r\n2. Having the following config files:\r\nNo config file, just using env variables\r\n\r\n4. Having the following app code:\r\n\r\n<details>\r\n<summary> Code </summary>\r\n\r\n**/test/test.py**\r\n```python\r\nimport dynaconf\r\n\r\nclass CustomFilter:\r\n def __call__(self, data):\r\n print(\"this is never called\")\r\n return {\r\n k: v\r\n for k, v in data.items()\r\n if k.startswith(\"PREFIX\")\r\n }\r\n\r\n\r\nif __name__ == \"__main__\":\r\n dc = dynaconf.Dynaconf(\r\n envvar_prefix=False,\r\n filter_strategy=CustomFilter(),\r\n )\r\n print(dc.as_dict())\r\n```\r\n\r\n</details>\r\n\r\n5. Executing under the following environment\r\n\r\n<details>\r\n<summary> Execution </summary>\r\n\r\n```bash\r\nPREFIX_VAR=\"HELLO\" OTHER_VAR=\"WORLD\" python test.py\r\n```\r\n\r\n</details>\r\n\r\n**Expected behavior**\r\n`CustomFilter` should be called (\"this is never called\" should be displayed) and only the `PREFIX_VAR` should be in dict, not `OTHER_VAR`\r\n\r\n**Environment (please complete the following information):**\r\n - OS: Linux version 5.10.60.1-microsoft-standard-WSL2 \r\n - Dynaconf Version 3.1.9\r\n - Framework: None\r\n\r\n**Context**\r\n\r\nI was looking for a way to filter out empty environment variables.\r\n\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom os import environ\n\nfrom dynaconf.utils import missing\nfrom dynaconf.utils import upperfy\nfrom dynaconf.utils.parse_conf import parse_conf_data\nfrom dynaconf.vendor.dotenv import cli as dotenv_cli\n\n\nIDENTIFIER = \"env\"\n\n\ndef load(obj, env=None, silent=True, key=None):\n \"\"\"Loads envvars with prefixes:\n\n `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`\n \"\"\"\n global_prefix = obj.get(\"ENVVAR_PREFIX_FOR_DYNACONF\")\n if global_prefix is False or global_prefix.upper() != \"DYNACONF\":\n load_from_env(obj, \"DYNACONF\", key, silent, IDENTIFIER + \"_global\")\n\n # Load the global env if exists and overwrite everything\n load_from_env(obj, global_prefix, key, silent, IDENTIFIER + \"_global\")\n\n\ndef load_from_env(\n obj,\n prefix=False,\n key=None,\n silent=False,\n identifier=IDENTIFIER,\n env=False, # backwards compatibility bc renamed param\n):\n if prefix is False and env is not False:\n prefix = env\n\n env_ = \"\"\n if prefix is not False:\n if not isinstance(prefix, str):\n raise TypeError(\"`prefix/env` must be str or False\")\n\n prefix = prefix.upper()\n env_ = f\"{prefix}_\"\n\n # Load a single environment variable explicitly.\n if key:\n key = upperfy(key)\n value = environ.get(f\"{env_}{key}\")\n if value:\n try: # obj is a Settings\n obj.set(key, value, loader_identifier=identifier, tomlfy=True)\n except AttributeError: # obj is a dict\n obj[key] = parse_conf_data(\n value, tomlfy=True, box_settings=obj\n )\n\n # Load environment variables in bulk (when matching).\n else:\n # Only known variables should be loaded from environment?\n ignore_unknown = obj.get(\"IGNORE_UNKNOWN_ENVVARS_FOR_DYNACONF\")\n\n trim_len = len(env_)\n data = {\n key[trim_len:]: parse_conf_data(\n data, tomlfy=True, box_settings=obj\n )\n for key, data in environ.items()\n if key.startswith(env_)\n and not (\n # Ignore environment variables that haven't been\n # pre-defined in settings space.\n ignore_unknown\n and obj.get(key[trim_len:], default=missing) is missing\n )\n }\n # Update the settings space based on gathered data from environment.\n if data:\n obj.update(data, loader_identifier=identifier)\n\n\ndef write(settings_path, settings_data, **kwargs):\n \"\"\"Write data to .env file\"\"\"\n for key, value in settings_data.items():\n quote_mode = (\n isinstance(value, str)\n and (value.startswith(\"'\") or value.startswith('\"'))\n ) or isinstance(value, (list, dict))\n dotenv_cli.set_key(\n str(settings_path),\n key,\n str(value),\n quote_mode=\"always\" if quote_mode else \"none\",\n )\n", "path": "dynaconf/loaders/env_loader.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom os import environ\n\nfrom dynaconf.utils import missing\nfrom dynaconf.utils import upperfy\nfrom dynaconf.utils.parse_conf import parse_conf_data\nfrom dynaconf.vendor.dotenv import cli as dotenv_cli\n\n\nIDENTIFIER = \"env\"\n\n\ndef load(obj, env=None, silent=True, key=None):\n \"\"\"Loads envvars with prefixes:\n\n `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`\n \"\"\"\n global_prefix = obj.get(\"ENVVAR_PREFIX_FOR_DYNACONF\")\n if global_prefix is False or global_prefix.upper() != \"DYNACONF\":\n load_from_env(obj, \"DYNACONF\", key, silent, IDENTIFIER + \"_global\")\n\n # Load the global env if exists and overwrite everything\n load_from_env(obj, global_prefix, key, silent, IDENTIFIER + \"_global\")\n\n\ndef load_from_env(\n obj,\n prefix=False,\n key=None,\n silent=False,\n identifier=IDENTIFIER,\n env=False, # backwards compatibility bc renamed param\n):\n if prefix is False and env is not False:\n prefix = env\n\n env_ = \"\"\n if prefix is not False:\n if not isinstance(prefix, str):\n raise TypeError(\"`prefix/env` must be str or False\")\n\n prefix = prefix.upper()\n env_ = f\"{prefix}_\"\n\n # Load a single environment variable explicitly.\n if key:\n key = upperfy(key)\n value = environ.get(f\"{env_}{key}\")\n if value:\n try: # obj is a Settings\n obj.set(key, value, loader_identifier=identifier, tomlfy=True)\n except AttributeError: # obj is a dict\n obj[key] = parse_conf_data(\n value, tomlfy=True, box_settings=obj\n )\n\n # Load environment variables in bulk (when matching).\n else:\n # Only known variables should be loaded from environment?\n ignore_unknown = obj.get(\"IGNORE_UNKNOWN_ENVVARS_FOR_DYNACONF\")\n\n trim_len = len(env_)\n data = {\n key[trim_len:]: parse_conf_data(\n data, tomlfy=True, box_settings=obj\n )\n for key, data in environ.items()\n if key.startswith(env_)\n and not (\n # Ignore environment variables that haven't been\n # pre-defined in settings space.\n ignore_unknown\n and obj.get(key[trim_len:], default=missing) is missing\n )\n }\n # Update the settings space based on gathered data from environment.\n if data:\n filter_strategy = obj.get(\"FILTER_STRATEGY\")\n if filter_strategy:\n data = filter_strategy(data)\n obj.update(data, loader_identifier=identifier)\n\n\ndef write(settings_path, settings_data, **kwargs):\n \"\"\"Write data to .env file\"\"\"\n for key, value in settings_data.items():\n quote_mode = (\n isinstance(value, str)\n and (value.startswith(\"'\") or value.startswith('\"'))\n ) or isinstance(value, (list, dict))\n dotenv_cli.set_key(\n str(settings_path),\n key,\n str(value),\n quote_mode=\"always\" if quote_mode else \"none\",\n )\n", "path": "dynaconf/loaders/env_loader.py"}]}
1,514
111
gh_patches_debug_16832
rasdani/github-patches
git_diff
pantsbuild__pants-20984
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `stevedore_namespace` documentation shows `str`'s doc string **Describe the bug** The `stevedore_namespace` BUILD file symbol has a doc-string, but it isn't shown in `pants help-all`. It instead shows what looks like the doc string for `str`. https://github.com/pantsbuild/pants/blob/ec86d19cd954cd49a9562880a7c0dbc45632778c/src/python/pants/backend/python/framework/stevedore/target_types.py#L13-L30 To reproduce, enable the stevedore backend and look at `help` or `help-all`: ```shell PANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help stevedore_namespace ``` ``` `stevedore_namespace` BUILD file symbol --------------------------------------- str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. ``` ```shell PANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help-all | \ jq .name_to_build_file_info.stevedore_namespace ``` ```json { "documentation": "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'.", "is_target": false, "name": "stevedore_namespace", "signature": null } ``` **Pants version** Seems to be visible in 2.16 through to the currently latest. **OS** both **Additional info** - Will appear in online docs too after https://github.com/pantsbuild/pantsbuild.org/pull/216 - Relevant issues: - https://github.com/pantsbuild/pants/discussions/18117 - https://github.com/pantsbuild/pants/issues/14832 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/python/pants/backend/python/framework/stevedore/target_types.py` Content: ``` 1 # Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). 2 # Licensed under the Apache License, Version 2.0 (see LICENSE). 3 4 from __future__ import annotations 5 6 from dataclasses import dataclass 7 8 from pants.backend.python.target_types import PythonDistribution 9 from pants.engine.target import StringSequenceField, Targets 10 from pants.util.strutil import help_text 11 12 13 class StevedoreNamespace(str): 14 f"""Tag a namespace in entry_points as a stevedore namespace. 15 16 This is required for the entry_point to be visible to dep inference 17 based on the `stevedore_namespaces` field. 18 19 For example: 20 {PythonDistribution.alias}( 21 ... 22 entry_points={{ 23 stevedore_namespace("a.b.c"): {{ 24 "plugin_name": "some.entry:point", 25 }}, 26 }}, 27 ) 28 """ 29 30 alias = "stevedore_namespace" 31 32 33 # This is a lot like a SpecialCasedDependencies field, but it doesn't list targets directly. 34 class StevedoreNamespacesField(StringSequenceField): 35 alias = "stevedore_namespaces" 36 help = help_text( 37 f""" 38 List the stevedore namespaces required by this target. 39 40 Code for all `entry_points` on `{PythonDistribution.alias}` targets with 41 these namespaces will be added as dependencies so that they are 42 available on PYTHONPATH during tests. Note that this is only a subset 43 of the `{PythonDistribution.alias}`s dependencies, so the `entry_points` 44 only need to be defined on one `{PythonDistribution.alias}` even if the 45 test only needs some of the `entry_points` namespaces on it. 46 47 Plus, an `entry_points.txt` file will be generated in the sandbox so that 48 each of the `{PythonDistribution.alias}`s appear to be "installed". The 49 `entry_points.txt` file will only include the namespaces requested on this 50 field. Without this, stevedore would not be able to look up plugins in 51 the setuptools `entry_points` metadata. 52 53 NOTE: Each `{PythonDistribution.alias}` must opt-in to being included in 54 this repo-wide inference by tagging the namespaces with 55 `{StevedoreNamespace.alias}("my.stevedore.extension")`. 56 57 The stevedore namespace format (`my.stevedore.extension`) is similar 58 to a Python namespace. 59 """ 60 ) 61 62 63 class AllStevedoreExtensionTargets(Targets): 64 pass 65 66 67 @dataclass(frozen=True) 68 class StevedoreNamespacesProviderTargetsRequest: 69 stevedore_namespaces: StevedoreNamespacesField 70 71 72 class StevedoreExtensionTargets(Targets): 73 pass 74 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/python/pants/backend/python/framework/stevedore/target_types.py b/src/python/pants/backend/python/framework/stevedore/target_types.py --- a/src/python/pants/backend/python/framework/stevedore/target_types.py +++ b/src/python/pants/backend/python/framework/stevedore/target_types.py @@ -11,20 +11,22 @@ class StevedoreNamespace(str): - f"""Tag a namespace in entry_points as a stevedore namespace. + """Tag a namespace in entry_points as a stevedore namespace. This is required for the entry_point to be visible to dep inference based on the `stevedore_namespaces` field. For example: - {PythonDistribution.alias}( - ... - entry_points={{ - stevedore_namespace("a.b.c"): {{ - "plugin_name": "some.entry:point", - }}, - }}, - ) + ```python + python_distribution( + ... + entry_points={ + stevedore_namespace("a.b.c"): { + "plugin_name": "some.entry:point", + }, + }, + ) + ``` """ alias = "stevedore_namespace"
{"golden_diff": "diff --git a/src/python/pants/backend/python/framework/stevedore/target_types.py b/src/python/pants/backend/python/framework/stevedore/target_types.py\n--- a/src/python/pants/backend/python/framework/stevedore/target_types.py\n+++ b/src/python/pants/backend/python/framework/stevedore/target_types.py\n@@ -11,20 +11,22 @@\n \n \n class StevedoreNamespace(str):\n- f\"\"\"Tag a namespace in entry_points as a stevedore namespace.\n+ \"\"\"Tag a namespace in entry_points as a stevedore namespace.\n \n This is required for the entry_point to be visible to dep inference\n based on the `stevedore_namespaces` field.\n \n For example:\n- {PythonDistribution.alias}(\n- ...\n- entry_points={{\n- stevedore_namespace(\"a.b.c\"): {{\n- \"plugin_name\": \"some.entry:point\",\n- }},\n- }},\n- )\n+ ```python\n+ python_distribution(\n+ ...\n+ entry_points={\n+ stevedore_namespace(\"a.b.c\"): {\n+ \"plugin_name\": \"some.entry:point\",\n+ },\n+ },\n+ )\n+ ```\n \"\"\"\n \n alias = \"stevedore_namespace\"\n", "issue": "`stevedore_namespace` documentation shows `str`'s doc string\n**Describe the bug**\r\n\r\nThe `stevedore_namespace` BUILD file symbol has a doc-string, but it isn't shown in `pants help-all`. It instead shows what looks like the doc string for `str`.\r\n\r\nhttps://github.com/pantsbuild/pants/blob/ec86d19cd954cd49a9562880a7c0dbc45632778c/src/python/pants/backend/python/framework/stevedore/target_types.py#L13-L30\r\n\r\nTo reproduce, enable the stevedore backend and look at `help` or `help-all`:\r\n\r\n```shell\r\nPANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help stevedore_namespace\r\n```\r\n```\r\n`stevedore_namespace` BUILD file symbol\r\n---------------------------------------\r\n\r\nstr(object='') -> str\r\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\r\n\r\nCreate a new string object from the given object. If encoding or\r\nerrors is specified, then the object must expose a data buffer\r\nthat will be decoded using the given encoding and error handler.\r\nOtherwise, returns the result of object.__str__() (if defined)\r\nor repr(object).\r\nencoding defaults to sys.getdefaultencoding().\r\nerrors defaults to 'strict'.\r\n```\r\n\r\n```shell\r\nPANTS_VERSION=2.22.0.dev3 pants --backend-packages=pants.backend.experimental.python.framework.stevedore help-all | \\\r\n jq .name_to_build_file_info.stevedore_namespace\r\n```\r\n```json\r\n{\r\n \"documentation\": \"str(object='') -> str\\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\\n\\nCreate a new string object from the given object. If encoding or\\nerrors is specified, then the object must expose a data buffer\\nthat will be decoded using the given encoding and error handler.\\nOtherwise, returns the result of object.__str__() (if defined)\\nor repr(object).\\nencoding defaults to sys.getdefaultencoding().\\nerrors defaults to 'strict'.\",\r\n \"is_target\": false,\r\n \"name\": \"stevedore_namespace\",\r\n \"signature\": null\r\n}\r\n```\r\n\r\n**Pants version**\r\nSeems to be visible in 2.16 through to the currently latest.\r\n\r\n**OS**\r\nboth\r\n\r\n**Additional info**\r\n\r\n- Will appear in online docs too after https://github.com/pantsbuild/pantsbuild.org/pull/216\r\n- Relevant issues:\r\n - https://github.com/pantsbuild/pants/discussions/18117\r\n - https://github.com/pantsbuild/pants/issues/14832\n", "before_files": [{"content": "# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom pants.backend.python.target_types import PythonDistribution\nfrom pants.engine.target import StringSequenceField, Targets\nfrom pants.util.strutil import help_text\n\n\nclass StevedoreNamespace(str):\n f\"\"\"Tag a namespace in entry_points as a stevedore namespace.\n\n This is required for the entry_point to be visible to dep inference\n based on the `stevedore_namespaces` field.\n\n For example:\n {PythonDistribution.alias}(\n ...\n entry_points={{\n stevedore_namespace(\"a.b.c\"): {{\n \"plugin_name\": \"some.entry:point\",\n }},\n }},\n )\n \"\"\"\n\n alias = \"stevedore_namespace\"\n\n\n# This is a lot like a SpecialCasedDependencies field, but it doesn't list targets directly.\nclass StevedoreNamespacesField(StringSequenceField):\n alias = \"stevedore_namespaces\"\n help = help_text(\n f\"\"\"\n List the stevedore namespaces required by this target.\n\n Code for all `entry_points` on `{PythonDistribution.alias}` targets with\n these namespaces will be added as dependencies so that they are\n available on PYTHONPATH during tests. Note that this is only a subset\n of the `{PythonDistribution.alias}`s dependencies, so the `entry_points`\n only need to be defined on one `{PythonDistribution.alias}` even if the\n test only needs some of the `entry_points` namespaces on it.\n\n Plus, an `entry_points.txt` file will be generated in the sandbox so that\n each of the `{PythonDistribution.alias}`s appear to be \"installed\". The\n `entry_points.txt` file will only include the namespaces requested on this\n field. Without this, stevedore would not be able to look up plugins in\n the setuptools `entry_points` metadata.\n\n NOTE: Each `{PythonDistribution.alias}` must opt-in to being included in\n this repo-wide inference by tagging the namespaces with\n `{StevedoreNamespace.alias}(\"my.stevedore.extension\")`.\n\n The stevedore namespace format (`my.stevedore.extension`) is similar\n to a Python namespace.\n \"\"\"\n )\n\n\nclass AllStevedoreExtensionTargets(Targets):\n pass\n\n\n@dataclass(frozen=True)\nclass StevedoreNamespacesProviderTargetsRequest:\n stevedore_namespaces: StevedoreNamespacesField\n\n\nclass StevedoreExtensionTargets(Targets):\n pass\n", "path": "src/python/pants/backend/python/framework/stevedore/target_types.py"}], "after_files": [{"content": "# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom pants.backend.python.target_types import PythonDistribution\nfrom pants.engine.target import StringSequenceField, Targets\nfrom pants.util.strutil import help_text\n\n\nclass StevedoreNamespace(str):\n \"\"\"Tag a namespace in entry_points as a stevedore namespace.\n\n This is required for the entry_point to be visible to dep inference\n based on the `stevedore_namespaces` field.\n\n For example:\n ```python\n python_distribution(\n ...\n entry_points={\n stevedore_namespace(\"a.b.c\"): {\n \"plugin_name\": \"some.entry:point\",\n },\n },\n )\n ```\n \"\"\"\n\n alias = \"stevedore_namespace\"\n\n\n# This is a lot like a SpecialCasedDependencies field, but it doesn't list targets directly.\nclass StevedoreNamespacesField(StringSequenceField):\n alias = \"stevedore_namespaces\"\n help = help_text(\n f\"\"\"\n List the stevedore namespaces required by this target.\n\n Code for all `entry_points` on `{PythonDistribution.alias}` targets with\n these namespaces will be added as dependencies so that they are\n available on PYTHONPATH during tests. Note that this is only a subset\n of the `{PythonDistribution.alias}`s dependencies, so the `entry_points`\n only need to be defined on one `{PythonDistribution.alias}` even if the\n test only needs some of the `entry_points` namespaces on it.\n\n Plus, an `entry_points.txt` file will be generated in the sandbox so that\n each of the `{PythonDistribution.alias}`s appear to be \"installed\". The\n `entry_points.txt` file will only include the namespaces requested on this\n field. Without this, stevedore would not be able to look up plugins in\n the setuptools `entry_points` metadata.\n\n NOTE: Each `{PythonDistribution.alias}` must opt-in to being included in\n this repo-wide inference by tagging the namespaces with\n `{StevedoreNamespace.alias}(\"my.stevedore.extension\")`.\n\n The stevedore namespace format (`my.stevedore.extension`) is similar\n to a Python namespace.\n \"\"\"\n )\n\n\nclass AllStevedoreExtensionTargets(Targets):\n pass\n\n\n@dataclass(frozen=True)\nclass StevedoreNamespacesProviderTargetsRequest:\n stevedore_namespaces: StevedoreNamespacesField\n\n\nclass StevedoreExtensionTargets(Targets):\n pass\n", "path": "src/python/pants/backend/python/framework/stevedore/target_types.py"}]}
1,552
272
gh_patches_debug_18816
rasdani/github-patches
git_diff
encode__uvicorn-646
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add support for --reload to monitor additional file types. The "reload" process currently only monitors ".py" files in various directories. I have a changes that will pass in a list of additional "reload_suffixes" that the process will monitor. This allows the service to monitor data files in addition to code files. Any feedback on whether this is useful to others? <!-- POLAR PLEDGE BADGE START --> > [!IMPORTANT] > - We're using [Polar.sh](https://polar.sh/encode) so you can upvote and help fund this issue. > - We receive the funding once the issue is completed & confirmed by you. > - Thank you in advance for helping prioritize & fund our backlog. <a href="https://polar.sh/encode/uvicorn/issues/528"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/encode/uvicorn/issues/528/pledge.svg?darkmode=1"> <img alt="Fund with Polar" src="https://polar.sh/api/github/encode/uvicorn/issues/528/pledge.svg"> </picture> </a> <!-- POLAR PLEDGE BADGE END --> --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `uvicorn/supervisors/statreload.py` Content: ``` 1 import logging 2 import os 3 from pathlib import Path 4 5 from uvicorn.supervisors.basereload import BaseReload 6 7 logger = logging.getLogger("uvicorn.error") 8 9 10 class StatReload(BaseReload): 11 def __init__(self, config, target, sockets): 12 super().__init__(config, target, sockets) 13 self.reloader_name = "statreload" 14 self.mtimes = {} 15 16 def should_restart(self): 17 for filename in self.iter_py_files(): 18 try: 19 mtime = os.path.getmtime(filename) 20 except OSError: # pragma: nocover 21 continue 22 23 old_time = self.mtimes.get(filename) 24 if old_time is None: 25 self.mtimes[filename] = mtime 26 continue 27 elif mtime > old_time: 28 display_path = os.path.normpath(filename) 29 if Path.cwd() in Path(filename).parents: 30 display_path = os.path.normpath(os.path.relpath(filename)) 31 message = "Detected file change in '%s'. Reloading..." 32 logger.warning(message, display_path) 33 return True 34 return False 35 36 def iter_py_files(self): 37 for reload_dir in self.config.reload_dirs: 38 for subdir, dirs, files in os.walk(reload_dir): 39 for file in files: 40 if file.endswith(".py"): 41 yield subdir + os.sep + file 42 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/uvicorn/supervisors/statreload.py b/uvicorn/supervisors/statreload.py --- a/uvicorn/supervisors/statreload.py +++ b/uvicorn/supervisors/statreload.py @@ -14,7 +14,7 @@ self.mtimes = {} def should_restart(self): - for filename in self.iter_py_files(): + for filename in self.iter_files(): try: mtime = os.path.getmtime(filename) except OSError: # pragma: nocover @@ -33,9 +33,9 @@ return True return False - def iter_py_files(self): + def iter_files(self): for reload_dir in self.config.reload_dirs: for subdir, dirs, files in os.walk(reload_dir): for file in files: - if file.endswith(".py"): + if not file.startswith("."): yield subdir + os.sep + file
{"golden_diff": "diff --git a/uvicorn/supervisors/statreload.py b/uvicorn/supervisors/statreload.py\n--- a/uvicorn/supervisors/statreload.py\n+++ b/uvicorn/supervisors/statreload.py\n@@ -14,7 +14,7 @@\n self.mtimes = {}\n \n def should_restart(self):\n- for filename in self.iter_py_files():\n+ for filename in self.iter_files():\n try:\n mtime = os.path.getmtime(filename)\n except OSError: # pragma: nocover\n@@ -33,9 +33,9 @@\n return True\n return False\n \n- def iter_py_files(self):\n+ def iter_files(self):\n for reload_dir in self.config.reload_dirs:\n for subdir, dirs, files in os.walk(reload_dir):\n for file in files:\n- if file.endswith(\".py\"):\n+ if not file.startswith(\".\"):\n yield subdir + os.sep + file\n", "issue": "Add support for --reload to monitor additional file types.\nThe \"reload\" process currently only monitors \".py\" files in various directories. I have a changes that will pass in a list of additional \"reload_suffixes\" that the process will monitor. This allows the service to monitor data files in addition to code files.\r\n\r\nAny feedback on whether this is useful to others?\n\n<!-- POLAR PLEDGE BADGE START -->\n> [!IMPORTANT]\n> - We're using [Polar.sh](https://polar.sh/encode) so you can upvote and help fund this issue.\n> - We receive the funding once the issue is completed & confirmed by you.\n> - Thank you in advance for helping prioritize & fund our backlog.\n\n<a href=\"https://polar.sh/encode/uvicorn/issues/528\">\n<picture>\n <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://polar.sh/api/github/encode/uvicorn/issues/528/pledge.svg?darkmode=1\">\n <img alt=\"Fund with Polar\" src=\"https://polar.sh/api/github/encode/uvicorn/issues/528/pledge.svg\">\n</picture>\n</a>\n<!-- POLAR PLEDGE BADGE END -->\n\n", "before_files": [{"content": "import logging\nimport os\nfrom pathlib import Path\n\nfrom uvicorn.supervisors.basereload import BaseReload\n\nlogger = logging.getLogger(\"uvicorn.error\")\n\n\nclass StatReload(BaseReload):\n def __init__(self, config, target, sockets):\n super().__init__(config, target, sockets)\n self.reloader_name = \"statreload\"\n self.mtimes = {}\n\n def should_restart(self):\n for filename in self.iter_py_files():\n try:\n mtime = os.path.getmtime(filename)\n except OSError: # pragma: nocover\n continue\n\n old_time = self.mtimes.get(filename)\n if old_time is None:\n self.mtimes[filename] = mtime\n continue\n elif mtime > old_time:\n display_path = os.path.normpath(filename)\n if Path.cwd() in Path(filename).parents:\n display_path = os.path.normpath(os.path.relpath(filename))\n message = \"Detected file change in '%s'. Reloading...\"\n logger.warning(message, display_path)\n return True\n return False\n\n def iter_py_files(self):\n for reload_dir in self.config.reload_dirs:\n for subdir, dirs, files in os.walk(reload_dir):\n for file in files:\n if file.endswith(\".py\"):\n yield subdir + os.sep + file\n", "path": "uvicorn/supervisors/statreload.py"}], "after_files": [{"content": "import logging\nimport os\nfrom pathlib import Path\n\nfrom uvicorn.supervisors.basereload import BaseReload\n\nlogger = logging.getLogger(\"uvicorn.error\")\n\n\nclass StatReload(BaseReload):\n def __init__(self, config, target, sockets):\n super().__init__(config, target, sockets)\n self.reloader_name = \"statreload\"\n self.mtimes = {}\n\n def should_restart(self):\n for filename in self.iter_files():\n try:\n mtime = os.path.getmtime(filename)\n except OSError: # pragma: nocover\n continue\n\n old_time = self.mtimes.get(filename)\n if old_time is None:\n self.mtimes[filename] = mtime\n continue\n elif mtime > old_time:\n display_path = os.path.normpath(filename)\n if Path.cwd() in Path(filename).parents:\n display_path = os.path.normpath(os.path.relpath(filename))\n message = \"Detected file change in '%s'. Reloading...\"\n logger.warning(message, display_path)\n return True\n return False\n\n def iter_files(self):\n for reload_dir in self.config.reload_dirs:\n for subdir, dirs, files in os.walk(reload_dir):\n for file in files:\n if not file.startswith(\".\"):\n yield subdir + os.sep + file\n", "path": "uvicorn/supervisors/statreload.py"}]}
887
210
gh_patches_debug_31192
rasdani/github-patches
git_diff
meltano__meltano-6118
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Verify `meltano install` telemetry fires for malformed plugin entries In #6109 @pnadolny13 noticed that with the following entry no events where fired: ```yaml - name: tap-something-invalid variant: meltanolabs pip_url: git+https://github.com/foo/tap-something-invalid.git ``` I wasn't able to reproduce that at the time and did see two events (started/aborted) come across. We should double check though, its entirely possible that my local dev setup had a seperate issue that was triggering the `aborted` event. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/meltano/cli/install.py` Content: ``` 1 """CLI command `meltano install`.""" 2 from __future__ import annotations 3 4 import click 5 6 from meltano.core.legacy_tracking import LegacyTracker 7 from meltano.core.plugin import PluginType 8 from meltano.core.plugin.error import PluginNotFoundError 9 from meltano.core.project_plugins_service import ProjectPluginsService 10 from meltano.core.tracking import PluginsTrackingContext, Tracker 11 from meltano.core.tracking import cli as cli_tracking 12 from meltano.core.tracking import cli_context_builder 13 14 from . import cli 15 from .params import pass_project 16 from .utils import CliError, install_plugins 17 18 19 @cli.command(short_help="Install project dependencies.") 20 @click.argument( 21 "plugin_type", type=click.Choice(PluginType.cli_arguments()), required=False 22 ) 23 @click.argument("plugin_name", nargs=-1, required=False) 24 @click.option( 25 "--clean", 26 is_flag=True, 27 help="Completely reinstall a plugin rather than simply upgrading if necessary.", 28 ) 29 @click.option( 30 "--parallelism", 31 "-p", 32 type=click.INT, 33 default=None, 34 help="Limit the number of plugins to install in parallel. Defaults to the number of cores.", 35 ) 36 @pass_project(migrate=True) 37 def install(project, plugin_type, plugin_name, clean, parallelism): 38 """ 39 Install all the dependencies of your project based on the meltano.yml file. 40 41 \b\nRead more at https://www.meltano.com/docs/command-line-interface.html#install 42 """ 43 tracker = Tracker(project) 44 tracker.add_contexts( 45 cli_context_builder( 46 "install", 47 None, 48 clean=clean, 49 parallelism=parallelism, 50 ) 51 ) 52 53 plugins_service = ProjectPluginsService(project) 54 55 if plugin_type: 56 try: 57 plugin_type = PluginType.from_cli_argument(plugin_type) 58 except ValueError: 59 # if we fail because plugin_type is not valid we have no plugins to instrument 60 tracker.track_command_event(cli_tracking.STARTED) 61 tracker.track_command_event(cli_tracking.ABORTED) 62 raise 63 plugins = plugins_service.get_plugins_of_type(plugin_type) 64 if plugin_name: 65 plugins = [plugin for plugin in plugins if plugin.name in plugin_name] 66 else: 67 try: 68 plugins = list(plugins_service.plugins()) 69 except PluginNotFoundError: 70 tracker.track_command_event(cli_tracking.STARTED) 71 tracker.track_command_event(cli_tracking.ABORTED) 72 raise 73 74 click.echo(f"Installing {len(plugins)} plugins...") 75 tracker.add_contexts( 76 PluginsTrackingContext([(candidate, None) for candidate in plugins]) 77 ) 78 tracker.track_command_event(cli_tracking.STARTED) 79 80 success = install_plugins(project, plugins, parallelism=parallelism, clean=clean) 81 82 legacy_tracker = LegacyTracker(project) 83 legacy_tracker.track_meltano_install() 84 85 if not success: 86 tracker.track_command_event(cli_tracking.FAILED) 87 raise CliError("Failed to install plugin(s)") 88 tracker.track_command_event(cli_tracking.COMPLETED) 89 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/meltano/cli/install.py b/src/meltano/cli/install.py --- a/src/meltano/cli/install.py +++ b/src/meltano/cli/install.py @@ -5,7 +5,6 @@ from meltano.core.legacy_tracking import LegacyTracker from meltano.core.plugin import PluginType -from meltano.core.plugin.error import PluginNotFoundError from meltano.core.project_plugins_service import ProjectPluginsService from meltano.core.tracking import PluginsTrackingContext, Tracker from meltano.core.tracking import cli as cli_tracking @@ -52,24 +51,18 @@ plugins_service = ProjectPluginsService(project) - if plugin_type: - try: + try: + if plugin_type: plugin_type = PluginType.from_cli_argument(plugin_type) - except ValueError: - # if we fail because plugin_type is not valid we have no plugins to instrument - tracker.track_command_event(cli_tracking.STARTED) - tracker.track_command_event(cli_tracking.ABORTED) - raise - plugins = plugins_service.get_plugins_of_type(plugin_type) - if plugin_name: - plugins = [plugin for plugin in plugins if plugin.name in plugin_name] - else: - try: + plugins = plugins_service.get_plugins_of_type(plugin_type) + if plugin_name: + plugins = [plugin for plugin in plugins if plugin.name in plugin_name] + else: plugins = list(plugins_service.plugins()) - except PluginNotFoundError: - tracker.track_command_event(cli_tracking.STARTED) - tracker.track_command_event(cli_tracking.ABORTED) - raise + except Exception: + tracker.track_command_event(cli_tracking.STARTED) + tracker.track_command_event(cli_tracking.ABORTED) + raise click.echo(f"Installing {len(plugins)} plugins...") tracker.add_contexts(
{"golden_diff": "diff --git a/src/meltano/cli/install.py b/src/meltano/cli/install.py\n--- a/src/meltano/cli/install.py\n+++ b/src/meltano/cli/install.py\n@@ -5,7 +5,6 @@\n \n from meltano.core.legacy_tracking import LegacyTracker\n from meltano.core.plugin import PluginType\n-from meltano.core.plugin.error import PluginNotFoundError\n from meltano.core.project_plugins_service import ProjectPluginsService\n from meltano.core.tracking import PluginsTrackingContext, Tracker\n from meltano.core.tracking import cli as cli_tracking\n@@ -52,24 +51,18 @@\n \n plugins_service = ProjectPluginsService(project)\n \n- if plugin_type:\n- try:\n+ try:\n+ if plugin_type:\n plugin_type = PluginType.from_cli_argument(plugin_type)\n- except ValueError:\n- # if we fail because plugin_type is not valid we have no plugins to instrument\n- tracker.track_command_event(cli_tracking.STARTED)\n- tracker.track_command_event(cli_tracking.ABORTED)\n- raise\n- plugins = plugins_service.get_plugins_of_type(plugin_type)\n- if plugin_name:\n- plugins = [plugin for plugin in plugins if plugin.name in plugin_name]\n- else:\n- try:\n+ plugins = plugins_service.get_plugins_of_type(plugin_type)\n+ if plugin_name:\n+ plugins = [plugin for plugin in plugins if plugin.name in plugin_name]\n+ else:\n plugins = list(plugins_service.plugins())\n- except PluginNotFoundError:\n- tracker.track_command_event(cli_tracking.STARTED)\n- tracker.track_command_event(cli_tracking.ABORTED)\n- raise\n+ except Exception:\n+ tracker.track_command_event(cli_tracking.STARTED)\n+ tracker.track_command_event(cli_tracking.ABORTED)\n+ raise\n \n click.echo(f\"Installing {len(plugins)} plugins...\")\n tracker.add_contexts(\n", "issue": "Verify `meltano install` telemetry fires for malformed plugin entries\nIn #6109 @pnadolny13 noticed that with the following entry no events where fired:\r\n\r\n```yaml\r\n - name: tap-something-invalid\r\n variant: meltanolabs\r\n pip_url: git+https://github.com/foo/tap-something-invalid.git\r\n```\r\n\r\nI wasn't able to reproduce that at the time and did see two events (started/aborted) come across. We should double check though, its entirely possible that my local dev setup had a seperate issue that was triggering the `aborted` event.\n", "before_files": [{"content": "\"\"\"CLI command `meltano install`.\"\"\"\nfrom __future__ import annotations\n\nimport click\n\nfrom meltano.core.legacy_tracking import LegacyTracker\nfrom meltano.core.plugin import PluginType\nfrom meltano.core.plugin.error import PluginNotFoundError\nfrom meltano.core.project_plugins_service import ProjectPluginsService\nfrom meltano.core.tracking import PluginsTrackingContext, Tracker\nfrom meltano.core.tracking import cli as cli_tracking\nfrom meltano.core.tracking import cli_context_builder\n\nfrom . import cli\nfrom .params import pass_project\nfrom .utils import CliError, install_plugins\n\n\[email protected](short_help=\"Install project dependencies.\")\[email protected](\n \"plugin_type\", type=click.Choice(PluginType.cli_arguments()), required=False\n)\[email protected](\"plugin_name\", nargs=-1, required=False)\[email protected](\n \"--clean\",\n is_flag=True,\n help=\"Completely reinstall a plugin rather than simply upgrading if necessary.\",\n)\[email protected](\n \"--parallelism\",\n \"-p\",\n type=click.INT,\n default=None,\n help=\"Limit the number of plugins to install in parallel. Defaults to the number of cores.\",\n)\n@pass_project(migrate=True)\ndef install(project, plugin_type, plugin_name, clean, parallelism):\n \"\"\"\n Install all the dependencies of your project based on the meltano.yml file.\n\n \\b\\nRead more at https://www.meltano.com/docs/command-line-interface.html#install\n \"\"\"\n tracker = Tracker(project)\n tracker.add_contexts(\n cli_context_builder(\n \"install\",\n None,\n clean=clean,\n parallelism=parallelism,\n )\n )\n\n plugins_service = ProjectPluginsService(project)\n\n if plugin_type:\n try:\n plugin_type = PluginType.from_cli_argument(plugin_type)\n except ValueError:\n # if we fail because plugin_type is not valid we have no plugins to instrument\n tracker.track_command_event(cli_tracking.STARTED)\n tracker.track_command_event(cli_tracking.ABORTED)\n raise\n plugins = plugins_service.get_plugins_of_type(plugin_type)\n if plugin_name:\n plugins = [plugin for plugin in plugins if plugin.name in plugin_name]\n else:\n try:\n plugins = list(plugins_service.plugins())\n except PluginNotFoundError:\n tracker.track_command_event(cli_tracking.STARTED)\n tracker.track_command_event(cli_tracking.ABORTED)\n raise\n\n click.echo(f\"Installing {len(plugins)} plugins...\")\n tracker.add_contexts(\n PluginsTrackingContext([(candidate, None) for candidate in plugins])\n )\n tracker.track_command_event(cli_tracking.STARTED)\n\n success = install_plugins(project, plugins, parallelism=parallelism, clean=clean)\n\n legacy_tracker = LegacyTracker(project)\n legacy_tracker.track_meltano_install()\n\n if not success:\n tracker.track_command_event(cli_tracking.FAILED)\n raise CliError(\"Failed to install plugin(s)\")\n tracker.track_command_event(cli_tracking.COMPLETED)\n", "path": "src/meltano/cli/install.py"}], "after_files": [{"content": "\"\"\"CLI command `meltano install`.\"\"\"\nfrom __future__ import annotations\n\nimport click\n\nfrom meltano.core.legacy_tracking import LegacyTracker\nfrom meltano.core.plugin import PluginType\nfrom meltano.core.project_plugins_service import ProjectPluginsService\nfrom meltano.core.tracking import PluginsTrackingContext, Tracker\nfrom meltano.core.tracking import cli as cli_tracking\nfrom meltano.core.tracking import cli_context_builder\n\nfrom . import cli\nfrom .params import pass_project\nfrom .utils import CliError, install_plugins\n\n\[email protected](short_help=\"Install project dependencies.\")\[email protected](\n \"plugin_type\", type=click.Choice(PluginType.cli_arguments()), required=False\n)\[email protected](\"plugin_name\", nargs=-1, required=False)\[email protected](\n \"--clean\",\n is_flag=True,\n help=\"Completely reinstall a plugin rather than simply upgrading if necessary.\",\n)\[email protected](\n \"--parallelism\",\n \"-p\",\n type=click.INT,\n default=None,\n help=\"Limit the number of plugins to install in parallel. Defaults to the number of cores.\",\n)\n@pass_project(migrate=True)\ndef install(project, plugin_type, plugin_name, clean, parallelism):\n \"\"\"\n Install all the dependencies of your project based on the meltano.yml file.\n\n \\b\\nRead more at https://www.meltano.com/docs/command-line-interface.html#install\n \"\"\"\n tracker = Tracker(project)\n tracker.add_contexts(\n cli_context_builder(\n \"install\",\n None,\n clean=clean,\n parallelism=parallelism,\n )\n )\n\n plugins_service = ProjectPluginsService(project)\n\n try:\n if plugin_type:\n plugin_type = PluginType.from_cli_argument(plugin_type)\n plugins = plugins_service.get_plugins_of_type(plugin_type)\n if plugin_name:\n plugins = [plugin for plugin in plugins if plugin.name in plugin_name]\n else:\n plugins = list(plugins_service.plugins())\n except Exception:\n tracker.track_command_event(cli_tracking.STARTED)\n tracker.track_command_event(cli_tracking.ABORTED)\n raise\n\n click.echo(f\"Installing {len(plugins)} plugins...\")\n tracker.add_contexts(\n PluginsTrackingContext([(candidate, None) for candidate in plugins])\n )\n tracker.track_command_event(cli_tracking.STARTED)\n\n success = install_plugins(project, plugins, parallelism=parallelism, clean=clean)\n\n legacy_tracker = LegacyTracker(project)\n legacy_tracker.track_meltano_install()\n\n if not success:\n tracker.track_command_event(cli_tracking.FAILED)\n raise CliError(\"Failed to install plugin(s)\")\n tracker.track_command_event(cli_tracking.COMPLETED)\n", "path": "src/meltano/cli/install.py"}]}
1,187
406
gh_patches_debug_34990
rasdani/github-patches
git_diff
streamlink__streamlink-838
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- azubu.tv: remove plugin http://www.azubu.tv/ `Soon a new future for Azubu and Hitbox, together as a single force in the world of eSports and competitive gaming, will be revealed. We will be launching a new brand, website, and mobile apps. There you will find the best offerings from both Azubu and Hitbox in one new place.` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/streamlink/plugins/azubutv.py` Content: ``` 1 #!/usr/bin/env python 2 import json 3 import requests 4 5 import re 6 7 from io import BytesIO 8 from time import sleep 9 10 from streamlink.exceptions import PluginError 11 12 from streamlink.plugin import Plugin 13 from streamlink.plugin.api import http, validate 14 from streamlink.stream import HLSStream 15 16 17 HTTP_HEADERS = { 18 "User-Agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " 19 "(KHTML, like Gecko) Chrome/36.0.1944.9 Safari/537.36"), 20 'Accept': 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV' 21 22 } 23 24 _url_re = re.compile(r"http(s)?://(\w+\.)?azubu.tv/(?P<domain>\w+)") 25 26 PARAMS_REGEX = r"(\w+)=({.+?}|\[.+?\]|\(.+?\)|'(?:[^'\\]|\\')*'|\"(?:[^\"\\]|\\\")*\"|\S+)" 27 stream_video_url = "http://api.azubu.tv/public/channel/{}/player" 28 29 30 class AzubuTV(Plugin): 31 @classmethod 32 def can_handle_url(cls, url): 33 return _url_re.match(url) 34 35 @classmethod 36 def stream_weight(cls, stream): 37 if stream == "source": 38 weight = 1080 39 else: 40 weight, group = Plugin.stream_weight(stream) 41 42 return weight, "azubutv" 43 44 def _parse_params(self, params): 45 rval = {} 46 matches = re.findall(PARAMS_REGEX, params) 47 48 for key, value in matches: 49 try: 50 value = ast.literal_eval(value) 51 except Exception: 52 pass 53 54 rval[key] = value 55 56 return rval 57 58 def _get_stream_url(self, o): 59 60 match = _url_re.match(self.url) 61 channel = match.group('domain') 62 63 channel_info = requests.get(stream_video_url.format(channel)) 64 j = json.loads(channel_info.text) 65 66 if j["data"]["is_live"] is not True: 67 return "", False 68 else: 69 is_live = True 70 71 stream_url = 'https://edge.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:{0}' 72 73 r = requests.get(stream_url.format(j["data"]["stream_video"]["reference_id"]), headers=HTTP_HEADERS) 74 t = json.loads(r.text) 75 76 stream_url = t["sources"][0]["src"] 77 return stream_url, is_live 78 79 def _get_streams(self): 80 hls_url, is_live = self._get_stream_url(self) 81 82 if not is_live: 83 return 84 85 split = self.url.split(" ") 86 params = (" ").join(split[1:]) 87 params = self._parse_params(params) 88 89 try: 90 streams = HLSStream.parse_variant_playlist(self.session, hls_url, **params) 91 except IOError as err: 92 raise PluginError(err) 93 94 return streams 95 96 97 __plugin__ = AzubuTV 98 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/streamlink/plugins/azubutv.py b/src/streamlink/plugins/azubutv.py deleted file mode 100644 --- a/src/streamlink/plugins/azubutv.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -import json -import requests - -import re - -from io import BytesIO -from time import sleep - -from streamlink.exceptions import PluginError - -from streamlink.plugin import Plugin -from streamlink.plugin.api import http, validate -from streamlink.stream import HLSStream - - -HTTP_HEADERS = { - "User-Agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " - "(KHTML, like Gecko) Chrome/36.0.1944.9 Safari/537.36"), - 'Accept': 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV' - -} - -_url_re = re.compile(r"http(s)?://(\w+\.)?azubu.tv/(?P<domain>\w+)") - -PARAMS_REGEX = r"(\w+)=({.+?}|\[.+?\]|\(.+?\)|'(?:[^'\\]|\\')*'|\"(?:[^\"\\]|\\\")*\"|\S+)" -stream_video_url = "http://api.azubu.tv/public/channel/{}/player" - - -class AzubuTV(Plugin): - @classmethod - def can_handle_url(cls, url): - return _url_re.match(url) - - @classmethod - def stream_weight(cls, stream): - if stream == "source": - weight = 1080 - else: - weight, group = Plugin.stream_weight(stream) - - return weight, "azubutv" - - def _parse_params(self, params): - rval = {} - matches = re.findall(PARAMS_REGEX, params) - - for key, value in matches: - try: - value = ast.literal_eval(value) - except Exception: - pass - - rval[key] = value - - return rval - - def _get_stream_url(self, o): - - match = _url_re.match(self.url) - channel = match.group('domain') - - channel_info = requests.get(stream_video_url.format(channel)) - j = json.loads(channel_info.text) - - if j["data"]["is_live"] is not True: - return "", False - else: - is_live = True - - stream_url = 'https://edge.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:{0}' - - r = requests.get(stream_url.format(j["data"]["stream_video"]["reference_id"]), headers=HTTP_HEADERS) - t = json.loads(r.text) - - stream_url = t["sources"][0]["src"] - return stream_url, is_live - - def _get_streams(self): - hls_url, is_live = self._get_stream_url(self) - - if not is_live: - return - - split = self.url.split(" ") - params = (" ").join(split[1:]) - params = self._parse_params(params) - - try: - streams = HLSStream.parse_variant_playlist(self.session, hls_url, **params) - except IOError as err: - raise PluginError(err) - - return streams - - -__plugin__ = AzubuTV
{"golden_diff": "diff --git a/src/streamlink/plugins/azubutv.py b/src/streamlink/plugins/azubutv.py\ndeleted file mode 100644\n--- a/src/streamlink/plugins/azubutv.py\n+++ /dev/null\n@@ -1,97 +0,0 @@\n-#!/usr/bin/env python\n-import json\n-import requests\n-\n-import re\n-\n-from io import BytesIO\n-from time import sleep\n-\n-from streamlink.exceptions import PluginError\n-\n-from streamlink.plugin import Plugin\n-from streamlink.plugin.api import http, validate\n-from streamlink.stream import HLSStream\n-\n-\n-HTTP_HEADERS = {\n- \"User-Agent\": (\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \"\n- \"(KHTML, like Gecko) Chrome/36.0.1944.9 Safari/537.36\"),\n- 'Accept': 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV'\n-\n-}\n-\n-_url_re = re.compile(r\"http(s)?://(\\w+\\.)?azubu.tv/(?P<domain>\\w+)\")\n-\n-PARAMS_REGEX = r\"(\\w+)=({.+?}|\\[.+?\\]|\\(.+?\\)|'(?:[^'\\\\]|\\\\')*'|\\\"(?:[^\\\"\\\\]|\\\\\\\")*\\\"|\\S+)\"\n-stream_video_url = \"http://api.azubu.tv/public/channel/{}/player\"\n-\n-\n-class AzubuTV(Plugin):\n- @classmethod\n- def can_handle_url(cls, url):\n- return _url_re.match(url)\n-\n- @classmethod\n- def stream_weight(cls, stream):\n- if stream == \"source\":\n- weight = 1080\n- else:\n- weight, group = Plugin.stream_weight(stream)\n-\n- return weight, \"azubutv\"\n-\n- def _parse_params(self, params):\n- rval = {}\n- matches = re.findall(PARAMS_REGEX, params)\n-\n- for key, value in matches:\n- try:\n- value = ast.literal_eval(value)\n- except Exception:\n- pass\n-\n- rval[key] = value\n-\n- return rval\n-\n- def _get_stream_url(self, o):\n-\n- match = _url_re.match(self.url)\n- channel = match.group('domain')\n-\n- channel_info = requests.get(stream_video_url.format(channel))\n- j = json.loads(channel_info.text)\n-\n- if j[\"data\"][\"is_live\"] is not True:\n- return \"\", False\n- else:\n- is_live = True\n-\n- stream_url = 'https://edge.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:{0}'\n-\n- r = requests.get(stream_url.format(j[\"data\"][\"stream_video\"][\"reference_id\"]), headers=HTTP_HEADERS)\n- t = json.loads(r.text)\n-\n- stream_url = t[\"sources\"][0][\"src\"]\n- return stream_url, is_live\n-\n- def _get_streams(self):\n- hls_url, is_live = self._get_stream_url(self)\n-\n- if not is_live:\n- return\n-\n- split = self.url.split(\" \")\n- params = (\" \").join(split[1:])\n- params = self._parse_params(params)\n-\n- try:\n- streams = HLSStream.parse_variant_playlist(self.session, hls_url, **params)\n- except IOError as err:\n- raise PluginError(err)\n-\n- return streams\n-\n-\n-__plugin__ = AzubuTV\n", "issue": "azubu.tv: remove plugin\nhttp://www.azubu.tv/\r\n`Soon a new future for Azubu and Hitbox, together as a single force in the world of eSports and competitive gaming, will be revealed. We will be launching a new brand, website, and mobile apps. There you will find the best offerings from both Azubu and Hitbox in one new place.`\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\nimport json\nimport requests\n\nimport re\n\nfrom io import BytesIO\nfrom time import sleep\n\nfrom streamlink.exceptions import PluginError\n\nfrom streamlink.plugin import Plugin\nfrom streamlink.plugin.api import http, validate\nfrom streamlink.stream import HLSStream\n\n\nHTTP_HEADERS = {\n \"User-Agent\": (\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/36.0.1944.9 Safari/537.36\"),\n 'Accept': 'application/json;pk=BCpkADawqM1gvI0oGWg8dxQHlgT8HkdE2LnAlWAZkOlznO39bSZX726u4JqnDsK3MDXcO01JxXK2tZtJbgQChxgaFzEVdHRjaDoxaOu8hHOO8NYhwdxw9BzvgkvLUlpbDNUuDoc4E4wxDToV'\n\n}\n\n_url_re = re.compile(r\"http(s)?://(\\w+\\.)?azubu.tv/(?P<domain>\\w+)\")\n\nPARAMS_REGEX = r\"(\\w+)=({.+?}|\\[.+?\\]|\\(.+?\\)|'(?:[^'\\\\]|\\\\')*'|\\\"(?:[^\\\"\\\\]|\\\\\\\")*\\\"|\\S+)\"\nstream_video_url = \"http://api.azubu.tv/public/channel/{}/player\"\n\n\nclass AzubuTV(Plugin):\n @classmethod\n def can_handle_url(cls, url):\n return _url_re.match(url)\n\n @classmethod\n def stream_weight(cls, stream):\n if stream == \"source\":\n weight = 1080\n else:\n weight, group = Plugin.stream_weight(stream)\n\n return weight, \"azubutv\"\n\n def _parse_params(self, params):\n rval = {}\n matches = re.findall(PARAMS_REGEX, params)\n\n for key, value in matches:\n try:\n value = ast.literal_eval(value)\n except Exception:\n pass\n\n rval[key] = value\n\n return rval\n\n def _get_stream_url(self, o):\n\n match = _url_re.match(self.url)\n channel = match.group('domain')\n\n channel_info = requests.get(stream_video_url.format(channel))\n j = json.loads(channel_info.text)\n\n if j[\"data\"][\"is_live\"] is not True:\n return \"\", False\n else:\n is_live = True\n\n stream_url = 'https://edge.api.brightcove.com/playback/v1/accounts/3361910549001/videos/ref:{0}'\n\n r = requests.get(stream_url.format(j[\"data\"][\"stream_video\"][\"reference_id\"]), headers=HTTP_HEADERS)\n t = json.loads(r.text)\n\n stream_url = t[\"sources\"][0][\"src\"]\n return stream_url, is_live\n\n def _get_streams(self):\n hls_url, is_live = self._get_stream_url(self)\n\n if not is_live:\n return\n\n split = self.url.split(\" \")\n params = (\" \").join(split[1:])\n params = self._parse_params(params)\n\n try:\n streams = HLSStream.parse_variant_playlist(self.session, hls_url, **params)\n except IOError as err:\n raise PluginError(err)\n\n return streams\n\n\n__plugin__ = AzubuTV\n", "path": "src/streamlink/plugins/azubutv.py"}], "after_files": [{"content": null, "path": "src/streamlink/plugins/azubutv.py"}]}
1,314
898
gh_patches_debug_48199
rasdani/github-patches
git_diff
secdev__scapy-1779
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Scapy crashes when tcpdump is not in $PATH Here is the fix: ```diff git diff scapy/arch/common.py diff --git a/scapy/arch/common.py b/scapy/arch/common.py index 9da19141..f103bebe 100644 --- a/scapy/arch/common.py +++ b/scapy/arch/common.py @@ -27,8 +27,11 @@ import scapy.modules.six as six def _check_tcpdump(): with open(os.devnull, 'wb') as devnull: - proc = subprocess.Popen([conf.prog.tcpdump, "--version"], - stdout=devnull, stderr=subprocess.STDOUT) + try: + proc = subprocess.Popen([conf.prog.tcpdump, "--version"], + stdout=devnull, stderr=subprocess.STDOUT) + except OSError: + return False return proc.wait() == 0 ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `scapy/arch/common.py` Content: ``` 1 # This file is part of Scapy 2 # See http://www.secdev.org/projects/scapy for more information 3 # Copyright (C) Philippe Biondi <[email protected]> 4 # This program is published under a GPLv2 license 5 6 """ 7 Functions common to different architectures 8 """ 9 10 # Important Note: This file is not needed on Windows, and mustn't be loaded 11 12 import socket 13 import subprocess 14 from fcntl import ioctl 15 import os 16 import struct 17 import ctypes 18 from ctypes import POINTER, Structure 19 from ctypes import c_uint, c_uint32, c_ushort, c_ubyte 20 from scapy.config import conf 21 from scapy.data import MTU 22 from scapy.error import Scapy_Exception 23 import scapy.modules.six as six 24 25 # BOOT 26 27 28 def _check_tcpdump(): 29 with open(os.devnull, 'wb') as devnull: 30 proc = subprocess.Popen([conf.prog.tcpdump, "--version"], 31 stdout=devnull, stderr=subprocess.STDOUT) 32 return proc.wait() == 0 33 34 35 TCPDUMP = _check_tcpdump() 36 37 # UTILS 38 39 40 def get_if(iff, cmd): 41 """Ease SIOCGIF* ioctl calls""" 42 43 sck = socket.socket() 44 ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8"))) 45 sck.close() 46 return ifreq 47 48 # BPF HANDLERS 49 50 51 class bpf_insn(Structure): 52 """"The BPF instruction data structure""" 53 _fields_ = [("code", c_ushort), 54 ("jt", c_ubyte), 55 ("jf", c_ubyte), 56 ("k", c_uint32)] 57 58 59 class bpf_program(Structure): 60 """"Structure for BIOCSETF""" 61 _fields_ = [("bf_len", c_uint), 62 ("bf_insns", POINTER(bpf_insn))] 63 64 65 def _legacy_bpf_pointer(tcpdump_lines): 66 """Get old-format BPF Pointer. Deprecated""" 67 X86_64 = os.uname()[4] in ['x86_64', 'aarch64'] 68 size = int(tcpdump_lines[0]) 69 bpf = b"" 70 for l in tcpdump_lines[1:]: 71 if six.PY2: 72 int_type = long # noqa: F821 73 else: 74 int_type = int 75 bpf += struct.pack("HBBI", *map(int_type, l.split())) 76 77 # Thanks to http://www.netprojects.de/scapy-with-pypy-solved/ for the pypy trick # noqa: E501 78 if conf.use_pypy: 79 str_buffer = ctypes.create_string_buffer(bpf) 80 return struct.pack('HL', size, ctypes.addressof(str_buffer)) 81 else: 82 # XXX. Argl! We need to give the kernel a pointer on the BPF, 83 # Python object header seems to be 20 bytes. 36 bytes for x86 64bits arch. # noqa: E501 84 if X86_64: 85 return struct.pack("HL", size, id(bpf) + 36) 86 else: 87 return struct.pack("HI", size, id(bpf) + 20) 88 89 90 def get_bpf_pointer(tcpdump_lines): 91 """Create a BPF Pointer for TCPDump filter""" 92 if conf.use_pypy: 93 return _legacy_bpf_pointer(tcpdump_lines) 94 95 # Allocate BPF instructions 96 size = int(tcpdump_lines[0]) 97 bpf_insn_a = bpf_insn * size 98 bip = bpf_insn_a() 99 100 # Fill the BPF instruction structures with the byte code 101 tcpdump_lines = tcpdump_lines[1:] 102 i = 0 103 for line in tcpdump_lines: 104 values = [int(v) for v in line.split()] 105 bip[i].code = c_ushort(values[0]) 106 bip[i].jt = c_ubyte(values[1]) 107 bip[i].jf = c_ubyte(values[2]) 108 bip[i].k = c_uint(values[3]) 109 i += 1 110 111 # Create the BPF program 112 return bpf_program(size, bip) 113 114 115 def compile_filter(bpf_filter, iface=None): 116 """Asks Tcpdump to parse the filter, then build the matching 117 BPF bytecode using get_bpf_pointer. 118 """ 119 if not TCPDUMP: 120 raise Scapy_Exception("tcpdump is not available. Cannot use filter !") 121 try: 122 process = subprocess.Popen([ 123 conf.prog.tcpdump, 124 "-p", 125 "-i", (conf.iface if iface is None else iface), 126 "-ddd", 127 "-s", str(MTU), 128 bpf_filter], 129 stdout=subprocess.PIPE, 130 stderr=subprocess.PIPE 131 ) 132 except OSError as ex: 133 raise Scapy_Exception("Failed to attach filter: %s" % ex) 134 lines, err = process.communicate() 135 ret = process.returncode 136 if ret: 137 raise Scapy_Exception( 138 "Failed to attach filter: tcpdump returned: %s" % err 139 ) 140 lines = lines.strip().split(b"\n") 141 return get_bpf_pointer(lines) 142 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/scapy/arch/common.py b/scapy/arch/common.py --- a/scapy/arch/common.py +++ b/scapy/arch/common.py @@ -26,9 +26,15 @@ def _check_tcpdump(): + """ + Return True if the tcpdump command can be started + """ with open(os.devnull, 'wb') as devnull: - proc = subprocess.Popen([conf.prog.tcpdump, "--version"], - stdout=devnull, stderr=subprocess.STDOUT) + try: + proc = subprocess.Popen([conf.prog.tcpdump, "--version"], + stdout=devnull, stderr=subprocess.STDOUT) + except OSError: + return False return proc.wait() == 0
{"golden_diff": "diff --git a/scapy/arch/common.py b/scapy/arch/common.py\n--- a/scapy/arch/common.py\n+++ b/scapy/arch/common.py\n@@ -26,9 +26,15 @@\n \n \n def _check_tcpdump():\n+ \"\"\"\n+ Return True if the tcpdump command can be started\n+ \"\"\"\n with open(os.devnull, 'wb') as devnull:\n- proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\n- stdout=devnull, stderr=subprocess.STDOUT)\n+ try:\n+ proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\n+ stdout=devnull, stderr=subprocess.STDOUT)\n+ except OSError:\n+ return False\n return proc.wait() == 0\n", "issue": "Scapy crashes when tcpdump is not in $PATH\nHere is the fix:\r\n\r\n```diff\r\ngit diff scapy/arch/common.py\r\ndiff --git a/scapy/arch/common.py b/scapy/arch/common.py\r\nindex 9da19141..f103bebe 100644\r\n--- a/scapy/arch/common.py\r\n+++ b/scapy/arch/common.py\r\n@@ -27,8 +27,11 @@ import scapy.modules.six as six\r\n \r\n def _check_tcpdump():\r\n with open(os.devnull, 'wb') as devnull:\r\n- proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\r\n- stdout=devnull, stderr=subprocess.STDOUT)\r\n+ try:\r\n+ proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\r\n+ stdout=devnull, stderr=subprocess.STDOUT)\r\n+ except OSError:\r\n+ return False\r\n return proc.wait() == 0\r\n```\n", "before_files": [{"content": "# This file is part of Scapy\n# See http://www.secdev.org/projects/scapy for more information\n# Copyright (C) Philippe Biondi <[email protected]>\n# This program is published under a GPLv2 license\n\n\"\"\"\nFunctions common to different architectures\n\"\"\"\n\n# Important Note: This file is not needed on Windows, and mustn't be loaded\n\nimport socket\nimport subprocess\nfrom fcntl import ioctl\nimport os\nimport struct\nimport ctypes\nfrom ctypes import POINTER, Structure\nfrom ctypes import c_uint, c_uint32, c_ushort, c_ubyte\nfrom scapy.config import conf\nfrom scapy.data import MTU\nfrom scapy.error import Scapy_Exception\nimport scapy.modules.six as six\n\n# BOOT\n\n\ndef _check_tcpdump():\n with open(os.devnull, 'wb') as devnull:\n proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\n stdout=devnull, stderr=subprocess.STDOUT)\n return proc.wait() == 0\n\n\nTCPDUMP = _check_tcpdump()\n\n# UTILS\n\n\ndef get_if(iff, cmd):\n \"\"\"Ease SIOCGIF* ioctl calls\"\"\"\n\n sck = socket.socket()\n ifreq = ioctl(sck, cmd, struct.pack(\"16s16x\", iff.encode(\"utf8\")))\n sck.close()\n return ifreq\n\n# BPF HANDLERS\n\n\nclass bpf_insn(Structure):\n \"\"\"\"The BPF instruction data structure\"\"\"\n _fields_ = [(\"code\", c_ushort),\n (\"jt\", c_ubyte),\n (\"jf\", c_ubyte),\n (\"k\", c_uint32)]\n\n\nclass bpf_program(Structure):\n \"\"\"\"Structure for BIOCSETF\"\"\"\n _fields_ = [(\"bf_len\", c_uint),\n (\"bf_insns\", POINTER(bpf_insn))]\n\n\ndef _legacy_bpf_pointer(tcpdump_lines):\n \"\"\"Get old-format BPF Pointer. Deprecated\"\"\"\n X86_64 = os.uname()[4] in ['x86_64', 'aarch64']\n size = int(tcpdump_lines[0])\n bpf = b\"\"\n for l in tcpdump_lines[1:]:\n if six.PY2:\n int_type = long # noqa: F821\n else:\n int_type = int\n bpf += struct.pack(\"HBBI\", *map(int_type, l.split()))\n\n # Thanks to http://www.netprojects.de/scapy-with-pypy-solved/ for the pypy trick # noqa: E501\n if conf.use_pypy:\n str_buffer = ctypes.create_string_buffer(bpf)\n return struct.pack('HL', size, ctypes.addressof(str_buffer))\n else:\n # XXX. Argl! We need to give the kernel a pointer on the BPF,\n # Python object header seems to be 20 bytes. 36 bytes for x86 64bits arch. # noqa: E501\n if X86_64:\n return struct.pack(\"HL\", size, id(bpf) + 36)\n else:\n return struct.pack(\"HI\", size, id(bpf) + 20)\n\n\ndef get_bpf_pointer(tcpdump_lines):\n \"\"\"Create a BPF Pointer for TCPDump filter\"\"\"\n if conf.use_pypy:\n return _legacy_bpf_pointer(tcpdump_lines)\n\n # Allocate BPF instructions\n size = int(tcpdump_lines[0])\n bpf_insn_a = bpf_insn * size\n bip = bpf_insn_a()\n\n # Fill the BPF instruction structures with the byte code\n tcpdump_lines = tcpdump_lines[1:]\n i = 0\n for line in tcpdump_lines:\n values = [int(v) for v in line.split()]\n bip[i].code = c_ushort(values[0])\n bip[i].jt = c_ubyte(values[1])\n bip[i].jf = c_ubyte(values[2])\n bip[i].k = c_uint(values[3])\n i += 1\n\n # Create the BPF program\n return bpf_program(size, bip)\n\n\ndef compile_filter(bpf_filter, iface=None):\n \"\"\"Asks Tcpdump to parse the filter, then build the matching\n BPF bytecode using get_bpf_pointer.\n \"\"\"\n if not TCPDUMP:\n raise Scapy_Exception(\"tcpdump is not available. Cannot use filter !\")\n try:\n process = subprocess.Popen([\n conf.prog.tcpdump,\n \"-p\",\n \"-i\", (conf.iface if iface is None else iface),\n \"-ddd\",\n \"-s\", str(MTU),\n bpf_filter],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n except OSError as ex:\n raise Scapy_Exception(\"Failed to attach filter: %s\" % ex)\n lines, err = process.communicate()\n ret = process.returncode\n if ret:\n raise Scapy_Exception(\n \"Failed to attach filter: tcpdump returned: %s\" % err\n )\n lines = lines.strip().split(b\"\\n\")\n return get_bpf_pointer(lines)\n", "path": "scapy/arch/common.py"}], "after_files": [{"content": "# This file is part of Scapy\n# See http://www.secdev.org/projects/scapy for more information\n# Copyright (C) Philippe Biondi <[email protected]>\n# This program is published under a GPLv2 license\n\n\"\"\"\nFunctions common to different architectures\n\"\"\"\n\n# Important Note: This file is not needed on Windows, and mustn't be loaded\n\nimport socket\nimport subprocess\nfrom fcntl import ioctl\nimport os\nimport struct\nimport ctypes\nfrom ctypes import POINTER, Structure\nfrom ctypes import c_uint, c_uint32, c_ushort, c_ubyte\nfrom scapy.config import conf\nfrom scapy.data import MTU\nfrom scapy.error import Scapy_Exception\nimport scapy.modules.six as six\n\n# BOOT\n\n\ndef _check_tcpdump():\n \"\"\"\n Return True if the tcpdump command can be started\n \"\"\"\n with open(os.devnull, 'wb') as devnull:\n try:\n proc = subprocess.Popen([conf.prog.tcpdump, \"--version\"],\n stdout=devnull, stderr=subprocess.STDOUT)\n except OSError:\n return False\n return proc.wait() == 0\n\n\nTCPDUMP = _check_tcpdump()\n\n# UTILS\n\n\ndef get_if(iff, cmd):\n \"\"\"Ease SIOCGIF* ioctl calls\"\"\"\n\n sck = socket.socket()\n ifreq = ioctl(sck, cmd, struct.pack(\"16s16x\", iff.encode(\"utf8\")))\n sck.close()\n return ifreq\n\n# BPF HANDLERS\n\n\nclass bpf_insn(Structure):\n \"\"\"\"The BPF instruction data structure\"\"\"\n _fields_ = [(\"code\", c_ushort),\n (\"jt\", c_ubyte),\n (\"jf\", c_ubyte),\n (\"k\", c_uint32)]\n\n\nclass bpf_program(Structure):\n \"\"\"\"Structure for BIOCSETF\"\"\"\n _fields_ = [(\"bf_len\", c_uint),\n (\"bf_insns\", POINTER(bpf_insn))]\n\n\ndef _legacy_bpf_pointer(tcpdump_lines):\n \"\"\"Get old-format BPF Pointer. Deprecated\"\"\"\n X86_64 = os.uname()[4] in ['x86_64', 'aarch64']\n size = int(tcpdump_lines[0])\n bpf = b\"\"\n for l in tcpdump_lines[1:]:\n if six.PY2:\n int_type = long # noqa: F821\n else:\n int_type = int\n bpf += struct.pack(\"HBBI\", *map(int_type, l.split()))\n\n # Thanks to http://www.netprojects.de/scapy-with-pypy-solved/ for the pypy trick # noqa: E501\n if conf.use_pypy:\n str_buffer = ctypes.create_string_buffer(bpf)\n return struct.pack('HL', size, ctypes.addressof(str_buffer))\n else:\n # XXX. Argl! We need to give the kernel a pointer on the BPF,\n # Python object header seems to be 20 bytes. 36 bytes for x86 64bits arch. # noqa: E501\n if X86_64:\n return struct.pack(\"HL\", size, id(bpf) + 36)\n else:\n return struct.pack(\"HI\", size, id(bpf) + 20)\n\n\ndef get_bpf_pointer(tcpdump_lines):\n \"\"\"Create a BPF Pointer for TCPDump filter\"\"\"\n if conf.use_pypy:\n return _legacy_bpf_pointer(tcpdump_lines)\n\n # Allocate BPF instructions\n size = int(tcpdump_lines[0])\n bpf_insn_a = bpf_insn * size\n bip = bpf_insn_a()\n\n # Fill the BPF instruction structures with the byte code\n tcpdump_lines = tcpdump_lines[1:]\n i = 0\n for line in tcpdump_lines:\n values = [int(v) for v in line.split()]\n bip[i].code = c_ushort(values[0])\n bip[i].jt = c_ubyte(values[1])\n bip[i].jf = c_ubyte(values[2])\n bip[i].k = c_uint(values[3])\n i += 1\n\n # Create the BPF program\n return bpf_program(size, bip)\n\n\ndef compile_filter(bpf_filter, iface=None):\n \"\"\"Asks Tcpdump to parse the filter, then build the matching\n BPF bytecode using get_bpf_pointer.\n \"\"\"\n if not TCPDUMP:\n raise Scapy_Exception(\"tcpdump is not available. Cannot use filter !\")\n try:\n process = subprocess.Popen([\n conf.prog.tcpdump,\n \"-p\",\n \"-i\", (conf.iface if iface is None else iface),\n \"-ddd\",\n \"-s\", str(MTU),\n bpf_filter],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n except OSError as ex:\n raise Scapy_Exception(\"Failed to attach filter: %s\" % ex)\n lines, err = process.communicate()\n ret = process.returncode\n if ret:\n raise Scapy_Exception(\n \"Failed to attach filter: tcpdump returned: %s\" % err\n )\n lines = lines.strip().split(b\"\\n\")\n return get_bpf_pointer(lines)\n", "path": "scapy/arch/common.py"}]}
1,917
166
gh_patches_debug_22072
rasdani/github-patches
git_diff
dask__distributed-3056
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- cpu cores estimate based on cgroups I was reading the announcement for 2.4.0 and got interested in https://github.com/dask/distributed/pull/3039 by @jcrist That did lead me to this part of the code: https://github.com/dask/distributed/blob/7d017c467590c758fa4b8cb2b1193205fe5aa7ad/distributed/system.py#L62 Just by looking at it (and although I'm not an expert I think I know what's going on), I have to observations -- half way between a question and a bugreport. 1. in my docker environment I have here (ubuntu 18.04), the filename is different: ``` ~$ cat /sys/fs/cgroup/cpu,cpuacct/cpu.cfs_period_us 100000 ~$ cat /sys/fs/cgroup/cpu,cpuacct/cpu.cfs_quota_us 220000 ``` in the code is that path: ``` ~$ ls /sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us ls: cannot access '/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us': No such file or directory ``` 2. The actual calculation is `int(quota / period)`. I think this should round up, not down. The point is, if you have a fraction like "2.5 cores", it will report 2 cores and keep half a core unused. It would be better if it reports 3 cores and then cgroups limits to the actual 2.5. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `distributed/system.py` Content: ``` 1 import os 2 import sys 3 4 import psutil 5 6 __all__ = ("memory_limit", "cpu_count", "MEMORY_LIMIT", "CPU_COUNT") 7 8 9 def memory_limit(): 10 """Get the memory limit (in bytes) for this system. 11 12 Takes the minimum value from the following locations: 13 14 - Total system host memory 15 - Cgroups limit (if set) 16 - RSS rlimit (if set) 17 """ 18 limit = psutil.virtual_memory().total 19 20 # Check cgroups if available 21 if sys.platform == "linux": 22 try: 23 with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f: 24 cgroups_limit = int(f.read()) 25 if cgroups_limit > 0: 26 limit = min(limit, cgroups_limit) 27 except Exception: 28 pass 29 30 # Check rlimit if available 31 try: 32 import resource 33 34 hard_limit = resource.getrlimit(resource.RLIMIT_RSS)[1] 35 if hard_limit > 0: 36 limit = min(limit, hard_limit) 37 except (ImportError, OSError): 38 pass 39 40 return limit 41 42 43 def cpu_count(): 44 """Get the available CPU count for this system. 45 46 Takes the minimum value from the following locations: 47 48 - Total system cpus available on the host. 49 - CPU Affinity (if set) 50 - Cgroups limit (if set) 51 """ 52 count = os.cpu_count() 53 54 # Check CPU affinity if available 55 try: 56 affinity_count = len(psutil.Process().cpu_affinity()) 57 if affinity_count > 0: 58 count = min(count, affinity_count) 59 except Exception: 60 pass 61 62 # Check cgroups if available 63 if sys.platform == "linux": 64 try: 65 with open("/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us") as f: 66 quota = int(f.read()) 67 with open("/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_period_us") as f: 68 period = int(f.read()) 69 cgroups_count = int(quota / period) 70 if cgroups_count > 0: 71 count = min(count, cgroups_count) 72 except Exception: 73 pass 74 75 return count 76 77 78 MEMORY_LIMIT = memory_limit() 79 CPU_COUNT = cpu_count() 80 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/distributed/system.py b/distributed/system.py --- a/distributed/system.py +++ b/distributed/system.py @@ -1,3 +1,4 @@ +import math import os import sys @@ -61,16 +62,20 @@ # Check cgroups if available if sys.platform == "linux": - try: - with open("/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us") as f: - quota = int(f.read()) - with open("/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_period_us") as f: - period = int(f.read()) - cgroups_count = int(quota / period) - if cgroups_count > 0: - count = min(count, cgroups_count) - except Exception: - pass + # The directory name isn't standardized across linux distros, check both + for dirname in ["cpuacct,cpu", "cpu,cpuacct"]: + try: + with open("/sys/fs/cgroup/%s/cpu.cfs_quota_us" % dirname) as f: + quota = int(f.read()) + with open("/sys/fs/cgroup/%s/cpu.cfs_period_us" % dirname) as f: + period = int(f.read()) + # We round up on fractional CPUs + cgroups_count = math.ceil(quota / period) + if cgroups_count > 0: + count = min(count, cgroups_count) + break + except Exception: + pass return count
{"golden_diff": "diff --git a/distributed/system.py b/distributed/system.py\n--- a/distributed/system.py\n+++ b/distributed/system.py\n@@ -1,3 +1,4 @@\n+import math\n import os\n import sys\n \n@@ -61,16 +62,20 @@\n \n # Check cgroups if available\n if sys.platform == \"linux\":\n- try:\n- with open(\"/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us\") as f:\n- quota = int(f.read())\n- with open(\"/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_period_us\") as f:\n- period = int(f.read())\n- cgroups_count = int(quota / period)\n- if cgroups_count > 0:\n- count = min(count, cgroups_count)\n- except Exception:\n- pass\n+ # The directory name isn't standardized across linux distros, check both\n+ for dirname in [\"cpuacct,cpu\", \"cpu,cpuacct\"]:\n+ try:\n+ with open(\"/sys/fs/cgroup/%s/cpu.cfs_quota_us\" % dirname) as f:\n+ quota = int(f.read())\n+ with open(\"/sys/fs/cgroup/%s/cpu.cfs_period_us\" % dirname) as f:\n+ period = int(f.read())\n+ # We round up on fractional CPUs\n+ cgroups_count = math.ceil(quota / period)\n+ if cgroups_count > 0:\n+ count = min(count, cgroups_count)\n+ break\n+ except Exception:\n+ pass\n \n return count\n", "issue": "cpu cores estimate based on cgroups\nI was reading the announcement for 2.4.0 and got interested in https://github.com/dask/distributed/pull/3039 by @jcrist \r\n\r\nThat did lead me to this part of the code:\r\nhttps://github.com/dask/distributed/blob/7d017c467590c758fa4b8cb2b1193205fe5aa7ad/distributed/system.py#L62\r\n\r\nJust by looking at it (and although I'm not an expert I think I know what's going on), I have to observations -- half way between a question and a bugreport.\r\n\r\n1. in my docker environment I have here (ubuntu 18.04), the filename is different:\r\n\r\n```\r\n~$ cat /sys/fs/cgroup/cpu,cpuacct/cpu.cfs_period_us \r\n100000\r\n~$ cat /sys/fs/cgroup/cpu,cpuacct/cpu.cfs_quota_us \r\n220000\r\n```\r\nin the code is that path:\r\n```\r\n~$ ls /sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us\r\nls: cannot access '/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us': No such file or directory\r\n```\r\n\r\n2. The actual calculation is `int(quota / period)`. I think this should round up, not down. The point is, if you have a fraction like \"2.5 cores\", it will report 2 cores and keep half a core unused. It would be better if it reports 3 cores and then cgroups limits to the actual 2.5.\r\n\r\n\n", "before_files": [{"content": "import os\nimport sys\n\nimport psutil\n\n__all__ = (\"memory_limit\", \"cpu_count\", \"MEMORY_LIMIT\", \"CPU_COUNT\")\n\n\ndef memory_limit():\n \"\"\"Get the memory limit (in bytes) for this system.\n\n Takes the minimum value from the following locations:\n\n - Total system host memory\n - Cgroups limit (if set)\n - RSS rlimit (if set)\n \"\"\"\n limit = psutil.virtual_memory().total\n\n # Check cgroups if available\n if sys.platform == \"linux\":\n try:\n with open(\"/sys/fs/cgroup/memory/memory.limit_in_bytes\") as f:\n cgroups_limit = int(f.read())\n if cgroups_limit > 0:\n limit = min(limit, cgroups_limit)\n except Exception:\n pass\n\n # Check rlimit if available\n try:\n import resource\n\n hard_limit = resource.getrlimit(resource.RLIMIT_RSS)[1]\n if hard_limit > 0:\n limit = min(limit, hard_limit)\n except (ImportError, OSError):\n pass\n\n return limit\n\n\ndef cpu_count():\n \"\"\"Get the available CPU count for this system.\n\n Takes the minimum value from the following locations:\n\n - Total system cpus available on the host.\n - CPU Affinity (if set)\n - Cgroups limit (if set)\n \"\"\"\n count = os.cpu_count()\n\n # Check CPU affinity if available\n try:\n affinity_count = len(psutil.Process().cpu_affinity())\n if affinity_count > 0:\n count = min(count, affinity_count)\n except Exception:\n pass\n\n # Check cgroups if available\n if sys.platform == \"linux\":\n try:\n with open(\"/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_quota_us\") as f:\n quota = int(f.read())\n with open(\"/sys/fs/cgroup/cpuacct,cpu/cpu.cfs_period_us\") as f:\n period = int(f.read())\n cgroups_count = int(quota / period)\n if cgroups_count > 0:\n count = min(count, cgroups_count)\n except Exception:\n pass\n\n return count\n\n\nMEMORY_LIMIT = memory_limit()\nCPU_COUNT = cpu_count()\n", "path": "distributed/system.py"}], "after_files": [{"content": "import math\nimport os\nimport sys\n\nimport psutil\n\n__all__ = (\"memory_limit\", \"cpu_count\", \"MEMORY_LIMIT\", \"CPU_COUNT\")\n\n\ndef memory_limit():\n \"\"\"Get the memory limit (in bytes) for this system.\n\n Takes the minimum value from the following locations:\n\n - Total system host memory\n - Cgroups limit (if set)\n - RSS rlimit (if set)\n \"\"\"\n limit = psutil.virtual_memory().total\n\n # Check cgroups if available\n if sys.platform == \"linux\":\n try:\n with open(\"/sys/fs/cgroup/memory/memory.limit_in_bytes\") as f:\n cgroups_limit = int(f.read())\n if cgroups_limit > 0:\n limit = min(limit, cgroups_limit)\n except Exception:\n pass\n\n # Check rlimit if available\n try:\n import resource\n\n hard_limit = resource.getrlimit(resource.RLIMIT_RSS)[1]\n if hard_limit > 0:\n limit = min(limit, hard_limit)\n except (ImportError, OSError):\n pass\n\n return limit\n\n\ndef cpu_count():\n \"\"\"Get the available CPU count for this system.\n\n Takes the minimum value from the following locations:\n\n - Total system cpus available on the host.\n - CPU Affinity (if set)\n - Cgroups limit (if set)\n \"\"\"\n count = os.cpu_count()\n\n # Check CPU affinity if available\n try:\n affinity_count = len(psutil.Process().cpu_affinity())\n if affinity_count > 0:\n count = min(count, affinity_count)\n except Exception:\n pass\n\n # Check cgroups if available\n if sys.platform == \"linux\":\n # The directory name isn't standardized across linux distros, check both\n for dirname in [\"cpuacct,cpu\", \"cpu,cpuacct\"]:\n try:\n with open(\"/sys/fs/cgroup/%s/cpu.cfs_quota_us\" % dirname) as f:\n quota = int(f.read())\n with open(\"/sys/fs/cgroup/%s/cpu.cfs_period_us\" % dirname) as f:\n period = int(f.read())\n # We round up on fractional CPUs\n cgroups_count = math.ceil(quota / period)\n if cgroups_count > 0:\n count = min(count, cgroups_count)\n break\n except Exception:\n pass\n\n return count\n\n\nMEMORY_LIMIT = memory_limit()\nCPU_COUNT = cpu_count()\n", "path": "distributed/system.py"}]}
1,250
346
gh_patches_debug_1615
rasdani/github-patches
git_diff
urllib3__urllib3-987
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- urllib3 fails to install on centos7 due to old setuptools not supporting <=, < environment markers. Current urllib3 fails to install on centos7. This bug was most likely introduced after https://github.com/shazow/urllib3/commit/9f5454eac808a105307b2d363c99ce97e5109821. centos7 ships a very old version of setuptools (0.9.8) which does not support `<=` as an environment marker. See https://github.com/pypa/setuptools/issues/380. ``` $ python --version Python 2.7.5 $ rpm -qa python-setuptools python-setuptools-0.9.8-4.el7.noarch $ lsb_release -a ... Description: CentOS Linux release 7.2.1511 (Core) Release: 7.2.1511 $ virtualenv venv ... $ venv/bin/pip install urllib3 Downloading/unpacking urllib3 Downloading urllib3-1.18.tar.gz (183kB): 183kB downloaded Running setup.py egg_info for package urllib3 error in urllib3 setup command: Invalid environment marker: python_version <= "2.7" Complete output from command python setup.py egg_info: error in urllib3 setup command: Invalid environment marker: python_version <= "2.7" ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /home/rene/src/venv/build/urllib3 Storing complete log in /home/rene/.pip/pip.log ``` Installing https://github.com/shazow/urllib3/commit/f620d997134708b09560ca5797aa79a59a2ef4c0 (commit before 9f5454eac808a105307b2d363c99ce97e5109821) works fine. ``` $ venv/bin/pip install git+git://github.com/shazow/urllib3.git@f620d997134708b09560ca5797aa79a59a2ef4c0 ... Successfully installed urllib3 Cleaning up... ``` But 9f5454eac808a105307b2d363c99ce97e5109821 fails. ``` $ venv/bin/pip install git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821 Downloading/unpacking git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821 Cloning git://github.com/shazow/urllib3.git (to 9f5454eac808a105307b2d363c99ce97e5109821) to /tmp/pip-lnVDAG-build Could not find a tag or branch '9f5454eac808a105307b2d363c99ce97e5109821', assuming commit. Running setup.py egg_info for package from git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821 error in urllib3 setup command: Invalid environment marker: python_version < "3.3" Complete output from command python setup.py egg_info: error in urllib3 setup command: Invalid environment marker: python_version < "3.3" ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /tmp/pip-lnVDAG-build Storing complete log in /home/rene/.pip/pip.log ``` urllib3 1.17 setup.py does not ship with < or <= markers so my workaround right now is to install urllib3==1.17. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 #!/usr/bin/env python 2 3 from setuptools import setup 4 5 import os 6 import re 7 import codecs 8 9 base_path = os.path.dirname(__file__) 10 11 # Get the version (borrowed from SQLAlchemy) 12 with open(os.path.join(base_path, 'urllib3', '__init__.py')) as fp: 13 VERSION = re.compile(r".*__version__ = '(.*?)'", 14 re.S).match(fp.read()).group(1) 15 16 with codecs.open('README.rst', encoding='utf-8') as fp: 17 readme = fp.read() 18 with codecs.open('CHANGES.rst', encoding='utf-8') as fp: 19 changes = fp.read() 20 version = VERSION 21 22 setup(name='urllib3', 23 version=version, 24 description="HTTP library with thread-safe connection pooling, file post, and more.", 25 long_description=u'\n\n'.join([readme, changes]), 26 classifiers=[ 27 'Environment :: Web Environment', 28 'Intended Audience :: Developers', 29 'License :: OSI Approved :: MIT License', 30 'Operating System :: OS Independent', 31 'Programming Language :: Python', 32 'Programming Language :: Python :: 2', 33 'Programming Language :: Python :: 3', 34 'Topic :: Internet :: WWW/HTTP', 35 'Topic :: Software Development :: Libraries', 36 ], 37 keywords='urllib httplib threadsafe filepost http https ssl pooling', 38 author='Andrey Petrov', 39 author_email='[email protected]', 40 url='https://urllib3.readthedocs.io/', 41 license='MIT', 42 packages=['urllib3', 43 'urllib3.packages', 'urllib3.packages.ssl_match_hostname', 44 'urllib3.packages.backports', 'urllib3.contrib', 45 'urllib3.util', 46 ], 47 requires=[], 48 tests_require=[ 49 # These are a less-specific subset of dev-requirements.txt, for the 50 # convenience of distro package maintainers. 51 'nose', 52 'mock', 53 'tornado', 54 ], 55 test_suite='test', 56 extras_require={ 57 'secure': [ 58 'pyOpenSSL>=0.14', 59 'cryptography>=1.3.4', 60 'idna>=2.0.0', 61 'certifi', 62 ], 63 'secure:python_version <= "2.7"': [ 64 "ipaddress", 65 ], 66 'socks': [ 67 'PySocks>=1.5.6,<2.0,!=1.5.7', 68 ] 69 }, 70 ) 71 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -59,8 +59,6 @@ 'cryptography>=1.3.4', 'idna>=2.0.0', 'certifi', - ], - 'secure:python_version <= "2.7"': [ "ipaddress", ], 'socks': [
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -59,8 +59,6 @@\n 'cryptography>=1.3.4',\n 'idna>=2.0.0',\n 'certifi',\n- ],\n- 'secure:python_version <= \"2.7\"': [\n \"ipaddress\",\n ],\n 'socks': [\n", "issue": "urllib3 fails to install on centos7 due to old setuptools not supporting <=, < environment markers.\nCurrent urllib3 fails to install on centos7. This bug was most likely introduced after https://github.com/shazow/urllib3/commit/9f5454eac808a105307b2d363c99ce97e5109821.\n\ncentos7 ships a very old version of setuptools (0.9.8) which does not support `<=` as an environment marker. See https://github.com/pypa/setuptools/issues/380.\n\n```\n$ python --version\nPython 2.7.5\n\n$ rpm -qa python-setuptools\npython-setuptools-0.9.8-4.el7.noarch\n\n$ lsb_release -a\n...\nDescription: CentOS Linux release 7.2.1511 (Core) \nRelease: 7.2.1511\n\n$ virtualenv venv\n...\n\n$ venv/bin/pip install urllib3\nDownloading/unpacking urllib3\n Downloading urllib3-1.18.tar.gz (183kB): 183kB downloaded\n Running setup.py egg_info for package urllib3\n error in urllib3 setup command: Invalid environment marker: python_version <= \"2.7\"\n Complete output from command python setup.py egg_info:\n error in urllib3 setup command: Invalid environment marker: python_version <= \"2.7\"\n\n----------------------------------------\nCleaning up...\nCommand python setup.py egg_info failed with error code 1 in /home/rene/src/venv/build/urllib3\nStoring complete log in /home/rene/.pip/pip.log\n```\n\nInstalling https://github.com/shazow/urllib3/commit/f620d997134708b09560ca5797aa79a59a2ef4c0 (commit before 9f5454eac808a105307b2d363c99ce97e5109821) works fine.\n\n```\n$ venv/bin/pip install git+git://github.com/shazow/urllib3.git@f620d997134708b09560ca5797aa79a59a2ef4c0\n...\nSuccessfully installed urllib3\nCleaning up...\n```\n\nBut 9f5454eac808a105307b2d363c99ce97e5109821 fails.\n\n```\n$ venv/bin/pip install git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821\nDownloading/unpacking git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821\n Cloning git://github.com/shazow/urllib3.git (to 9f5454eac808a105307b2d363c99ce97e5109821) to /tmp/pip-lnVDAG-build\n Could not find a tag or branch '9f5454eac808a105307b2d363c99ce97e5109821', assuming commit.\n Running setup.py egg_info for package from git+git://github.com/shazow/urllib3.git@9f5454eac808a105307b2d363c99ce97e5109821\n error in urllib3 setup command: Invalid environment marker: python_version < \"3.3\"\n Complete output from command python setup.py egg_info:\n error in urllib3 setup command: Invalid environment marker: python_version < \"3.3\"\n\n----------------------------------------\nCleaning up...\nCommand python setup.py egg_info failed with error code 1 in /tmp/pip-lnVDAG-build\nStoring complete log in /home/rene/.pip/pip.log\n```\n\nurllib3 1.17 setup.py does not ship with < or <= markers so my workaround right now is to install urllib3==1.17.\n\n", "before_files": [{"content": "#!/usr/bin/env python\n\nfrom setuptools import setup\n\nimport os\nimport re\nimport codecs\n\nbase_path = os.path.dirname(__file__)\n\n# Get the version (borrowed from SQLAlchemy)\nwith open(os.path.join(base_path, 'urllib3', '__init__.py')) as fp:\n VERSION = re.compile(r\".*__version__ = '(.*?)'\",\n re.S).match(fp.read()).group(1)\n\nwith codecs.open('README.rst', encoding='utf-8') as fp:\n readme = fp.read()\nwith codecs.open('CHANGES.rst', encoding='utf-8') as fp:\n changes = fp.read()\nversion = VERSION\n\nsetup(name='urllib3',\n version=version,\n description=\"HTTP library with thread-safe connection pooling, file post, and more.\",\n long_description=u'\\n\\n'.join([readme, changes]),\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Software Development :: Libraries',\n ],\n keywords='urllib httplib threadsafe filepost http https ssl pooling',\n author='Andrey Petrov',\n author_email='[email protected]',\n url='https://urllib3.readthedocs.io/',\n license='MIT',\n packages=['urllib3',\n 'urllib3.packages', 'urllib3.packages.ssl_match_hostname',\n 'urllib3.packages.backports', 'urllib3.contrib',\n 'urllib3.util',\n ],\n requires=[],\n tests_require=[\n # These are a less-specific subset of dev-requirements.txt, for the\n # convenience of distro package maintainers.\n 'nose',\n 'mock',\n 'tornado',\n ],\n test_suite='test',\n extras_require={\n 'secure': [\n 'pyOpenSSL>=0.14',\n 'cryptography>=1.3.4',\n 'idna>=2.0.0',\n 'certifi',\n ],\n 'secure:python_version <= \"2.7\"': [\n \"ipaddress\",\n ],\n 'socks': [\n 'PySocks>=1.5.6,<2.0,!=1.5.7',\n ]\n },\n )\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\nfrom setuptools import setup\n\nimport os\nimport re\nimport codecs\n\nbase_path = os.path.dirname(__file__)\n\n# Get the version (borrowed from SQLAlchemy)\nwith open(os.path.join(base_path, 'urllib3', '__init__.py')) as fp:\n VERSION = re.compile(r\".*__version__ = '(.*?)'\",\n re.S).match(fp.read()).group(1)\n\nwith codecs.open('README.rst', encoding='utf-8') as fp:\n readme = fp.read()\nwith codecs.open('CHANGES.rst', encoding='utf-8') as fp:\n changes = fp.read()\nversion = VERSION\n\nsetup(name='urllib3',\n version=version,\n description=\"HTTP library with thread-safe connection pooling, file post, and more.\",\n long_description=u'\\n\\n'.join([readme, changes]),\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Software Development :: Libraries',\n ],\n keywords='urllib httplib threadsafe filepost http https ssl pooling',\n author='Andrey Petrov',\n author_email='[email protected]',\n url='https://urllib3.readthedocs.io/',\n license='MIT',\n packages=['urllib3',\n 'urllib3.packages', 'urllib3.packages.ssl_match_hostname',\n 'urllib3.packages.backports', 'urllib3.contrib',\n 'urllib3.util',\n ],\n requires=[],\n tests_require=[\n # These are a less-specific subset of dev-requirements.txt, for the\n # convenience of distro package maintainers.\n 'nose',\n 'mock',\n 'tornado',\n ],\n test_suite='test',\n extras_require={\n 'secure': [\n 'pyOpenSSL>=0.14',\n 'cryptography>=1.3.4',\n 'idna>=2.0.0',\n 'certifi',\n \"ipaddress\",\n ],\n 'socks': [\n 'PySocks>=1.5.6,<2.0,!=1.5.7',\n ]\n },\n )\n", "path": "setup.py"}]}
1,950
90
gh_patches_debug_13457
rasdani/github-patches
git_diff
modin-project__modin-3382
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- JSON dispatcher data file split correction Originated from https://github.com/modin-project/modin/pull/2607#discussion_r571989125. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `modin/engines/base/io/text/json_dispatcher.py` Content: ``` 1 # Licensed to Modin Development Team under one or more contributor license agreements. 2 # See the NOTICE file distributed with this work for additional information regarding 3 # copyright ownership. The Modin Development Team licenses this file to you under the 4 # Apache License, Version 2.0 (the "License"); you may not use this file except in 5 # compliance with the License. You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software distributed under 10 # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 11 # ANY KIND, either express or implied. See the License for the specific language 12 # governing permissions and limitations under the License. 13 14 """Module houses `JSONDispatcher` class, that is used for reading `.json` files.""" 15 16 from modin.engines.base.io.text.text_file_dispatcher import TextFileDispatcher 17 from io import BytesIO 18 import pandas 19 import numpy as np 20 from csv import QUOTE_NONE 21 22 from modin.config import NPartitions 23 24 25 class JSONDispatcher(TextFileDispatcher): 26 """ 27 Class handles utils for reading `.json` files. 28 29 Inherits some common for text files util functions from `TextFileDispatcher` class. 30 """ 31 32 @classmethod 33 def _read(cls, path_or_buf, **kwargs): 34 """ 35 Read data from `path_or_buf` according to the passed `read_json` `kwargs` parameters. 36 37 Parameters 38 ---------- 39 path_or_buf : str, path object or file-like object 40 `path_or_buf` parameter of `read_json` function. 41 **kwargs : dict 42 Parameters of `read_json` function. 43 44 Returns 45 ------- 46 BaseQueryCompiler 47 Query compiler with imported data for further processing. 48 """ 49 path_or_buf = cls.get_path_or_buffer(path_or_buf) 50 if isinstance(path_or_buf, str): 51 if not cls.file_exists(path_or_buf): 52 return cls.single_worker_read(path_or_buf, **kwargs) 53 path_or_buf = cls.get_path(path_or_buf) 54 elif not cls.pathlib_or_pypath(path_or_buf): 55 return cls.single_worker_read(path_or_buf, **kwargs) 56 if not kwargs.get("lines", False): 57 return cls.single_worker_read(path_or_buf, **kwargs) 58 columns = pandas.read_json( 59 BytesIO(b"" + open(path_or_buf, "rb").readline()), lines=True 60 ).columns 61 kwargs["columns"] = columns 62 empty_pd_df = pandas.DataFrame(columns=columns) 63 64 with cls.file_open(path_or_buf, "rb", kwargs.get("compression", "infer")) as f: 65 partition_ids = [] 66 index_ids = [] 67 dtypes_ids = [] 68 69 column_widths, num_splits = cls._define_metadata(empty_pd_df, columns) 70 71 args = {"fname": path_or_buf, "num_splits": num_splits, **kwargs} 72 73 splits = cls.partitioned_file( 74 f, 75 num_partitions=NPartitions.get(), 76 is_quoting=(args.get("quoting", "") != QUOTE_NONE), 77 ) 78 for start, end in splits: 79 args.update({"start": start, "end": end}) 80 partition_id = cls.deploy(cls.parse, num_splits + 3, args) 81 partition_ids.append(partition_id[:-3]) 82 index_ids.append(partition_id[-3]) 83 dtypes_ids.append(partition_id[-2]) 84 85 # partition_id[-1] contains the columns for each partition, which will be useful 86 # for implementing when `lines=False`. 87 row_lengths = cls.materialize(index_ids) 88 new_index = pandas.RangeIndex(sum(row_lengths)) 89 90 dtypes = cls.get_dtypes(dtypes_ids) 91 partition_ids = cls.build_partition(partition_ids, row_lengths, column_widths) 92 93 if isinstance(dtypes, pandas.Series): 94 dtypes.index = columns 95 else: 96 dtypes = pandas.Series(dtypes, index=columns) 97 98 new_frame = cls.frame_cls( 99 np.array(partition_ids), 100 new_index, 101 columns, 102 row_lengths, 103 column_widths, 104 dtypes=dtypes, 105 ) 106 new_frame.synchronize_labels(axis=0) 107 return cls.query_compiler_cls(new_frame) 108 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/modin/engines/base/io/text/json_dispatcher.py b/modin/engines/base/io/text/json_dispatcher.py --- a/modin/engines/base/io/text/json_dispatcher.py +++ b/modin/engines/base/io/text/json_dispatcher.py @@ -17,7 +17,6 @@ from io import BytesIO import pandas import numpy as np -from csv import QUOTE_NONE from modin.config import NPartitions @@ -73,7 +72,6 @@ splits = cls.partitioned_file( f, num_partitions=NPartitions.get(), - is_quoting=(args.get("quoting", "") != QUOTE_NONE), ) for start, end in splits: args.update({"start": start, "end": end})
{"golden_diff": "diff --git a/modin/engines/base/io/text/json_dispatcher.py b/modin/engines/base/io/text/json_dispatcher.py\n--- a/modin/engines/base/io/text/json_dispatcher.py\n+++ b/modin/engines/base/io/text/json_dispatcher.py\n@@ -17,7 +17,6 @@\n from io import BytesIO\n import pandas\n import numpy as np\n-from csv import QUOTE_NONE\n \n from modin.config import NPartitions\n \n@@ -73,7 +72,6 @@\n splits = cls.partitioned_file(\n f,\n num_partitions=NPartitions.get(),\n- is_quoting=(args.get(\"quoting\", \"\") != QUOTE_NONE),\n )\n for start, end in splits:\n args.update({\"start\": start, \"end\": end})\n", "issue": "JSON dispatcher data file split correction\nOriginated from https://github.com/modin-project/modin/pull/2607#discussion_r571989125.\n", "before_files": [{"content": "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\n\"\"\"Module houses `JSONDispatcher` class, that is used for reading `.json` files.\"\"\"\n\nfrom modin.engines.base.io.text.text_file_dispatcher import TextFileDispatcher\nfrom io import BytesIO\nimport pandas\nimport numpy as np\nfrom csv import QUOTE_NONE\n\nfrom modin.config import NPartitions\n\n\nclass JSONDispatcher(TextFileDispatcher):\n \"\"\"\n Class handles utils for reading `.json` files.\n\n Inherits some common for text files util functions from `TextFileDispatcher` class.\n \"\"\"\n\n @classmethod\n def _read(cls, path_or_buf, **kwargs):\n \"\"\"\n Read data from `path_or_buf` according to the passed `read_json` `kwargs` parameters.\n\n Parameters\n ----------\n path_or_buf : str, path object or file-like object\n `path_or_buf` parameter of `read_json` function.\n **kwargs : dict\n Parameters of `read_json` function.\n\n Returns\n -------\n BaseQueryCompiler\n Query compiler with imported data for further processing.\n \"\"\"\n path_or_buf = cls.get_path_or_buffer(path_or_buf)\n if isinstance(path_or_buf, str):\n if not cls.file_exists(path_or_buf):\n return cls.single_worker_read(path_or_buf, **kwargs)\n path_or_buf = cls.get_path(path_or_buf)\n elif not cls.pathlib_or_pypath(path_or_buf):\n return cls.single_worker_read(path_or_buf, **kwargs)\n if not kwargs.get(\"lines\", False):\n return cls.single_worker_read(path_or_buf, **kwargs)\n columns = pandas.read_json(\n BytesIO(b\"\" + open(path_or_buf, \"rb\").readline()), lines=True\n ).columns\n kwargs[\"columns\"] = columns\n empty_pd_df = pandas.DataFrame(columns=columns)\n\n with cls.file_open(path_or_buf, \"rb\", kwargs.get(\"compression\", \"infer\")) as f:\n partition_ids = []\n index_ids = []\n dtypes_ids = []\n\n column_widths, num_splits = cls._define_metadata(empty_pd_df, columns)\n\n args = {\"fname\": path_or_buf, \"num_splits\": num_splits, **kwargs}\n\n splits = cls.partitioned_file(\n f,\n num_partitions=NPartitions.get(),\n is_quoting=(args.get(\"quoting\", \"\") != QUOTE_NONE),\n )\n for start, end in splits:\n args.update({\"start\": start, \"end\": end})\n partition_id = cls.deploy(cls.parse, num_splits + 3, args)\n partition_ids.append(partition_id[:-3])\n index_ids.append(partition_id[-3])\n dtypes_ids.append(partition_id[-2])\n\n # partition_id[-1] contains the columns for each partition, which will be useful\n # for implementing when `lines=False`.\n row_lengths = cls.materialize(index_ids)\n new_index = pandas.RangeIndex(sum(row_lengths))\n\n dtypes = cls.get_dtypes(dtypes_ids)\n partition_ids = cls.build_partition(partition_ids, row_lengths, column_widths)\n\n if isinstance(dtypes, pandas.Series):\n dtypes.index = columns\n else:\n dtypes = pandas.Series(dtypes, index=columns)\n\n new_frame = cls.frame_cls(\n np.array(partition_ids),\n new_index,\n columns,\n row_lengths,\n column_widths,\n dtypes=dtypes,\n )\n new_frame.synchronize_labels(axis=0)\n return cls.query_compiler_cls(new_frame)\n", "path": "modin/engines/base/io/text/json_dispatcher.py"}], "after_files": [{"content": "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\n\"\"\"Module houses `JSONDispatcher` class, that is used for reading `.json` files.\"\"\"\n\nfrom modin.engines.base.io.text.text_file_dispatcher import TextFileDispatcher\nfrom io import BytesIO\nimport pandas\nimport numpy as np\n\nfrom modin.config import NPartitions\n\n\nclass JSONDispatcher(TextFileDispatcher):\n \"\"\"\n Class handles utils for reading `.json` files.\n\n Inherits some common for text files util functions from `TextFileDispatcher` class.\n \"\"\"\n\n @classmethod\n def _read(cls, path_or_buf, **kwargs):\n \"\"\"\n Read data from `path_or_buf` according to the passed `read_json` `kwargs` parameters.\n\n Parameters\n ----------\n path_or_buf : str, path object or file-like object\n `path_or_buf` parameter of `read_json` function.\n **kwargs : dict\n Parameters of `read_json` function.\n\n Returns\n -------\n BaseQueryCompiler\n Query compiler with imported data for further processing.\n \"\"\"\n path_or_buf = cls.get_path_or_buffer(path_or_buf)\n if isinstance(path_or_buf, str):\n if not cls.file_exists(path_or_buf):\n return cls.single_worker_read(path_or_buf, **kwargs)\n path_or_buf = cls.get_path(path_or_buf)\n elif not cls.pathlib_or_pypath(path_or_buf):\n return cls.single_worker_read(path_or_buf, **kwargs)\n if not kwargs.get(\"lines\", False):\n return cls.single_worker_read(path_or_buf, **kwargs)\n columns = pandas.read_json(\n BytesIO(b\"\" + open(path_or_buf, \"rb\").readline()), lines=True\n ).columns\n kwargs[\"columns\"] = columns\n empty_pd_df = pandas.DataFrame(columns=columns)\n\n with cls.file_open(path_or_buf, \"rb\", kwargs.get(\"compression\", \"infer\")) as f:\n partition_ids = []\n index_ids = []\n dtypes_ids = []\n\n column_widths, num_splits = cls._define_metadata(empty_pd_df, columns)\n\n args = {\"fname\": path_or_buf, \"num_splits\": num_splits, **kwargs}\n\n splits = cls.partitioned_file(\n f,\n num_partitions=NPartitions.get(),\n )\n for start, end in splits:\n args.update({\"start\": start, \"end\": end})\n partition_id = cls.deploy(cls.parse, num_splits + 3, args)\n partition_ids.append(partition_id[:-3])\n index_ids.append(partition_id[-3])\n dtypes_ids.append(partition_id[-2])\n\n # partition_id[-1] contains the columns for each partition, which will be useful\n # for implementing when `lines=False`.\n row_lengths = cls.materialize(index_ids)\n new_index = pandas.RangeIndex(sum(row_lengths))\n\n dtypes = cls.get_dtypes(dtypes_ids)\n partition_ids = cls.build_partition(partition_ids, row_lengths, column_widths)\n\n if isinstance(dtypes, pandas.Series):\n dtypes.index = columns\n else:\n dtypes = pandas.Series(dtypes, index=columns)\n\n new_frame = cls.frame_cls(\n np.array(partition_ids),\n new_index,\n columns,\n row_lengths,\n column_widths,\n dtypes=dtypes,\n )\n new_frame.synchronize_labels(axis=0)\n return cls.query_compiler_cls(new_frame)\n", "path": "modin/engines/base/io/text/json_dispatcher.py"}]}
1,428
170
gh_patches_debug_33856
rasdani/github-patches
git_diff
hpcaitech__ColossalAI-2674
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [tensor] fix some unittests [tensor] fix some unittests [tensor] fix some unittests [FEATURE]: Patch meta information of `torch.nn.functional.softmax()` This is a part of issue #2628, we will patch meta information of `torch.nn.functional.softmax()` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `colossalai/auto_parallel/meta_profiler/meta_registry/activation.py` Content: ``` 1 from typing import List, Tuple 2 3 import torch 4 5 from colossalai.auto_parallel.tensor_shard.sharding_strategy import MemoryCost, OperationDataType, TrainCycleItem 6 from colossalai.fx.profiler.memory_utils import activation_size 7 from colossalai.fx.profiler.opcount import flop_mapping 8 9 from ..registry import meta_register 10 11 __all__ = ["relu_meta_info"] 12 13 14 @meta_register.register(torch.nn.ReLU) 15 def relu_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: 16 """torch.nn.ReLU metainfo generator 17 The aten graph of torch.nn.ReLU is 18 graph(): 19 %input_2 : [#users=1] = placeholder[target=placeholder](default=) 20 %relu_default : [#users=2] = call_function[target=torch.ops.aten.relu.default](args = (%input_2,), kwargs = {}) 21 %zeros_like_default : [#users=1] = call_function[target=torch.ops.aten.zeros_like.default](args = (%relu_default,), kwargs = {dtype: None, layout: None, device: None, pin_memory: None}) 22 %detach_default : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%relu_default,), kwargs = {}) 23 %threshold_backward_default : [#users=1] = call_function[target=torch.ops.aten.threshold_backward.default](args = (%zeros_like_default, %detach_default, None), kwargs = {}) 24 %detach_default_1 : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%threshold_backward_default,), kwargs = {}) 25 %detach_default_2 : [#users=0] = call_function[target=torch.ops.aten.detach.default](args = (%detach_default_1,), kwargs = {}) 26 27 Returns: 28 Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs 29 """ 30 31 input_tensor = args[0].data 32 output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data 33 is_inplace = kwargs.get("inplace", False) 34 35 # construct input args for forward 36 fwd_in_args = [input_tensor] 37 38 # construct input args for backward 39 bwd_in_args = [output_tensor] 40 41 # calculate cost 42 # the fwd op with compute cost is relu.default 43 # the bwd op with compute cost is threshold_backward 44 45 # calculate compute cost 46 fwd_compute_cost = flop_mapping[torch.ops.aten.relu.default](fwd_in_args, (output_tensor,)) 47 bwd_compute_cost = flop_mapping[torch.ops.aten.threshold_backward.default](bwd_in_args, (input_tensor,)) 48 compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost) 49 50 # calculate memory cost 51 # NOTE: the inplace ReLU don't have forward memory cost 52 # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward 53 fwd_memory_cost = MemoryCost( 54 activation=activation_size(input_tensor) if is_inplace else activation_size([output_tensor, input_tensor]), 55 parameter=0, 56 temp=0, 57 buffer=0) 58 59 bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor), parameter=0, temp=0, buffer=0) 60 61 # total cost is the sum of forward and backward cost 62 total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation, 63 parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter) 64 65 memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost) 66 67 # store fwd_in, fwd_buffer, fwd_out 68 # NOTE: It might seems a little bit weird here, we just want to align it with the older version 69 # of MetaInfoProp. In the future we might modify this part to make it clearer. 70 fwd_in = [] 71 fwd_buffer = [torch.zeros_like(output_tensor, device='meta')] 72 fwd_out = [torch.zeros_like(output_tensor, device='meta')] 73 74 return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out 75 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py b/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py --- a/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py +++ b/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py @@ -72,3 +72,53 @@ fwd_out = [torch.zeros_like(output_tensor, device='meta')] return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out + + +@meta_register.register(torch.nn.Softmax) +@meta_register.register(torch.nn.functional.softmax) +def softmax_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: + """torch.nn.Softmax metainfo generator + Returns: + Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs + """ + input_tensor = next( + filter( + lambda x: + (x.type == OperationDataType.ARG or x.type == OperationDataType.PARAM) and x.name != 'softmax_dim', + args)).data + output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data + softmax_dim = next(filter(lambda x: x.name == 'softmax_dim', args)).data + + # calculate cost + + # calculate compute cost + fwd_compute_cost = flop_mapping[torch.ops.aten._softmax.default]([input_tensor], [output_tensor]) + bwd_compute_cost = flop_mapping[torch.ops.aten._softmax_backward_data.default]([output_tensor], [input_tensor]) + + compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost) + + # calculate memory cost + # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward + fwd_memory_cost = MemoryCost(activation=activation_size([input_tensor, output_tensor]), + parameter=0, + temp=0, + buffer=0) + bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor), + parameter=0, + temp=activation_size(input_tensor), + buffer=0) + + # total cost is the sum of forward and backward cost + total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation, + parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter, + temp=fwd_memory_cost.temp + bwd_memory_cost.temp, + buffer=fwd_memory_cost.buffer + bwd_memory_cost.buffer) + + memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost) + + # store fwd_in, fwd_buffer, fwd_out + fwd_in = [] + fwd_buffer = [torch.zeros_like(output_tensor, device='meta')] + fwd_out = [torch.zeros_like(output_tensor, device='meta')] + + return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out
{"golden_diff": "diff --git a/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py b/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py\n--- a/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py\n+++ b/colossalai/auto_parallel/meta_profiler/meta_registry/activation.py\n@@ -72,3 +72,53 @@\n fwd_out = [torch.zeros_like(output_tensor, device='meta')]\n \n return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out\n+\n+\n+@meta_register.register(torch.nn.Softmax)\n+@meta_register.register(torch.nn.functional.softmax)\n+def softmax_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]:\n+ \"\"\"torch.nn.Softmax metainfo generator\n+ Returns:\n+ Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs\n+ \"\"\"\n+ input_tensor = next(\n+ filter(\n+ lambda x:\n+ (x.type == OperationDataType.ARG or x.type == OperationDataType.PARAM) and x.name != 'softmax_dim',\n+ args)).data\n+ output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data\n+ softmax_dim = next(filter(lambda x: x.name == 'softmax_dim', args)).data\n+\n+ # calculate cost\n+\n+ # calculate compute cost\n+ fwd_compute_cost = flop_mapping[torch.ops.aten._softmax.default]([input_tensor], [output_tensor])\n+ bwd_compute_cost = flop_mapping[torch.ops.aten._softmax_backward_data.default]([output_tensor], [input_tensor])\n+\n+ compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost)\n+\n+ # calculate memory cost\n+ # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward\n+ fwd_memory_cost = MemoryCost(activation=activation_size([input_tensor, output_tensor]),\n+ parameter=0,\n+ temp=0,\n+ buffer=0)\n+ bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor),\n+ parameter=0,\n+ temp=activation_size(input_tensor),\n+ buffer=0)\n+\n+ # total cost is the sum of forward and backward cost\n+ total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation,\n+ parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter,\n+ temp=fwd_memory_cost.temp + bwd_memory_cost.temp,\n+ buffer=fwd_memory_cost.buffer + bwd_memory_cost.buffer)\n+\n+ memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost)\n+\n+ # store fwd_in, fwd_buffer, fwd_out\n+ fwd_in = []\n+ fwd_buffer = [torch.zeros_like(output_tensor, device='meta')]\n+ fwd_out = [torch.zeros_like(output_tensor, device='meta')]\n+\n+ return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out\n", "issue": "[tensor] fix some unittests\n\n[tensor] fix some unittests\n\n[tensor] fix some unittests\n\n[FEATURE]: Patch meta information of `torch.nn.functional.softmax()`\nThis is a part of issue #2628, we will patch meta information of `torch.nn.functional.softmax()`\n", "before_files": [{"content": "from typing import List, Tuple\n\nimport torch\n\nfrom colossalai.auto_parallel.tensor_shard.sharding_strategy import MemoryCost, OperationDataType, TrainCycleItem\nfrom colossalai.fx.profiler.memory_utils import activation_size\nfrom colossalai.fx.profiler.opcount import flop_mapping\n\nfrom ..registry import meta_register\n\n__all__ = [\"relu_meta_info\"]\n\n\n@meta_register.register(torch.nn.ReLU)\ndef relu_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]:\n \"\"\"torch.nn.ReLU metainfo generator\n The aten graph of torch.nn.ReLU is\n graph():\n %input_2 : [#users=1] = placeholder[target=placeholder](default=)\n %relu_default : [#users=2] = call_function[target=torch.ops.aten.relu.default](args = (%input_2,), kwargs = {})\n %zeros_like_default : [#users=1] = call_function[target=torch.ops.aten.zeros_like.default](args = (%relu_default,), kwargs = {dtype: None, layout: None, device: None, pin_memory: None})\n %detach_default : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%relu_default,), kwargs = {})\n %threshold_backward_default : [#users=1] = call_function[target=torch.ops.aten.threshold_backward.default](args = (%zeros_like_default, %detach_default, None), kwargs = {})\n %detach_default_1 : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%threshold_backward_default,), kwargs = {})\n %detach_default_2 : [#users=0] = call_function[target=torch.ops.aten.detach.default](args = (%detach_default_1,), kwargs = {})\n\n Returns:\n Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs\n \"\"\"\n\n input_tensor = args[0].data\n output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data\n is_inplace = kwargs.get(\"inplace\", False)\n\n # construct input args for forward\n fwd_in_args = [input_tensor]\n\n # construct input args for backward\n bwd_in_args = [output_tensor]\n\n # calculate cost\n # the fwd op with compute cost is relu.default\n # the bwd op with compute cost is threshold_backward\n\n # calculate compute cost\n fwd_compute_cost = flop_mapping[torch.ops.aten.relu.default](fwd_in_args, (output_tensor,))\n bwd_compute_cost = flop_mapping[torch.ops.aten.threshold_backward.default](bwd_in_args, (input_tensor,))\n compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost)\n\n # calculate memory cost\n # NOTE: the inplace ReLU don't have forward memory cost\n # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward\n fwd_memory_cost = MemoryCost(\n activation=activation_size(input_tensor) if is_inplace else activation_size([output_tensor, input_tensor]),\n parameter=0,\n temp=0,\n buffer=0)\n\n bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor), parameter=0, temp=0, buffer=0)\n\n # total cost is the sum of forward and backward cost\n total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation,\n parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter)\n\n memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost)\n\n # store fwd_in, fwd_buffer, fwd_out\n # NOTE: It might seems a little bit weird here, we just want to align it with the older version\n # of MetaInfoProp. In the future we might modify this part to make it clearer.\n fwd_in = []\n fwd_buffer = [torch.zeros_like(output_tensor, device='meta')]\n fwd_out = [torch.zeros_like(output_tensor, device='meta')]\n\n return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out\n", "path": "colossalai/auto_parallel/meta_profiler/meta_registry/activation.py"}], "after_files": [{"content": "from typing import List, Tuple\n\nimport torch\n\nfrom colossalai.auto_parallel.tensor_shard.sharding_strategy import MemoryCost, OperationDataType, TrainCycleItem\nfrom colossalai.fx.profiler.memory_utils import activation_size\nfrom colossalai.fx.profiler.opcount import flop_mapping\n\nfrom ..registry import meta_register\n\n__all__ = [\"relu_meta_info\"]\n\n\n@meta_register.register(torch.nn.ReLU)\ndef relu_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]:\n \"\"\"torch.nn.ReLU metainfo generator\n The aten graph of torch.nn.ReLU is\n graph():\n %input_2 : [#users=1] = placeholder[target=placeholder](default=)\n %relu_default : [#users=2] = call_function[target=torch.ops.aten.relu.default](args = (%input_2,), kwargs = {})\n %zeros_like_default : [#users=1] = call_function[target=torch.ops.aten.zeros_like.default](args = (%relu_default,), kwargs = {dtype: None, layout: None, device: None, pin_memory: None})\n %detach_default : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%relu_default,), kwargs = {})\n %threshold_backward_default : [#users=1] = call_function[target=torch.ops.aten.threshold_backward.default](args = (%zeros_like_default, %detach_default, None), kwargs = {})\n %detach_default_1 : [#users=1] = call_function[target=torch.ops.aten.detach.default](args = (%threshold_backward_default,), kwargs = {})\n %detach_default_2 : [#users=0] = call_function[target=torch.ops.aten.detach.default](args = (%detach_default_1,), kwargs = {})\n\n Returns:\n Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs\n \"\"\"\n\n input_tensor = args[0].data\n output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data\n is_inplace = kwargs.get(\"inplace\", False)\n\n # construct input args for forward\n fwd_in_args = [input_tensor]\n\n # construct input args for backward\n bwd_in_args = [output_tensor]\n\n # calculate cost\n # the fwd op with compute cost is relu.default\n # the bwd op with compute cost is threshold_backward\n\n # calculate compute cost\n fwd_compute_cost = flop_mapping[torch.ops.aten.relu.default](fwd_in_args, (output_tensor,))\n bwd_compute_cost = flop_mapping[torch.ops.aten.threshold_backward.default](bwd_in_args, (input_tensor,))\n compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost)\n\n # calculate memory cost\n # NOTE: the inplace ReLU don't have forward memory cost\n # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward\n fwd_memory_cost = MemoryCost(\n activation=activation_size(input_tensor) if is_inplace else activation_size([output_tensor, input_tensor]),\n parameter=0,\n temp=0,\n buffer=0)\n\n bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor), parameter=0, temp=0, buffer=0)\n\n # total cost is the sum of forward and backward cost\n total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation,\n parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter)\n\n memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost)\n\n # store fwd_in, fwd_buffer, fwd_out\n # NOTE: It might seems a little bit weird here, we just want to align it with the older version\n # of MetaInfoProp. In the future we might modify this part to make it clearer.\n fwd_in = []\n fwd_buffer = [torch.zeros_like(output_tensor, device='meta')]\n fwd_out = [torch.zeros_like(output_tensor, device='meta')]\n\n return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out\n\n\n@meta_register.register(torch.nn.Softmax)\n@meta_register.register(torch.nn.functional.softmax)\ndef softmax_meta_info(*args, **kwargs) -> Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]:\n \"\"\"torch.nn.Softmax metainfo generator\n Returns:\n Tuple[TrainCycleItem, TrainCycleItem, List[torch.Tensor]]: compute cost, memory cost and forward inputs\n \"\"\"\n input_tensor = next(\n filter(\n lambda x:\n (x.type == OperationDataType.ARG or x.type == OperationDataType.PARAM) and x.name != 'softmax_dim',\n args)).data\n output_tensor = next(filter(lambda x: x.type == OperationDataType.OUTPUT, args)).data\n softmax_dim = next(filter(lambda x: x.name == 'softmax_dim', args)).data\n\n # calculate cost\n\n # calculate compute cost\n fwd_compute_cost = flop_mapping[torch.ops.aten._softmax.default]([input_tensor], [output_tensor])\n bwd_compute_cost = flop_mapping[torch.ops.aten._softmax_backward_data.default]([output_tensor], [input_tensor])\n\n compute_cost = TrainCycleItem(fwd=fwd_compute_cost, bwd=bwd_compute_cost, total=fwd_compute_cost + bwd_compute_cost)\n\n # calculate memory cost\n # NOTE: currently in SPMD solver we always believe that there will be a new tensor created in forward\n fwd_memory_cost = MemoryCost(activation=activation_size([input_tensor, output_tensor]),\n parameter=0,\n temp=0,\n buffer=0)\n bwd_memory_cost = MemoryCost(activation=activation_size(input_tensor),\n parameter=0,\n temp=activation_size(input_tensor),\n buffer=0)\n\n # total cost is the sum of forward and backward cost\n total_cost = MemoryCost(activation=fwd_memory_cost.activation + bwd_memory_cost.activation,\n parameter=fwd_memory_cost.parameter + bwd_memory_cost.parameter,\n temp=fwd_memory_cost.temp + bwd_memory_cost.temp,\n buffer=fwd_memory_cost.buffer + bwd_memory_cost.buffer)\n\n memory_cost = TrainCycleItem(fwd=fwd_memory_cost, bwd=bwd_memory_cost, total=total_cost)\n\n # store fwd_in, fwd_buffer, fwd_out\n fwd_in = []\n fwd_buffer = [torch.zeros_like(output_tensor, device='meta')]\n fwd_out = [torch.zeros_like(output_tensor, device='meta')]\n\n return compute_cost, memory_cost, fwd_in, fwd_buffer, fwd_out\n", "path": "colossalai/auto_parallel/meta_profiler/meta_registry/activation.py"}]}
1,381
692
gh_patches_debug_4261
rasdani/github-patches
git_diff
Nitrate__Nitrate-406
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Fix call to DurationField.from_db_value() which will be removed in Django 3.0 Lots of such warning are output. ``` src/tests/xmlrpc/test_testcaseplan.py::TestCasePlanGet::test_get_with_negative_case_id /testenv/lib/python3.7/site-packages/django/db/models/sql/compiler.py:995: RemovedInDjango30Warning: Remove the context parameter from DurationField.from_db_value(). Support for it will be removed in Django 3.0. RemovedInDjango30Warning, ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/tcms/core/models/fields.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 import datetime 3 import six 4 5 from django.core.exceptions import ValidationError 6 from django.db.models.fields import IntegerField 7 from django.db.models.fields import BooleanField 8 9 from tcms.core.forms.fields import DurationField as DurationFormField 10 11 try: 12 from pymysql.constants import FIELD_TYPE 13 except ImportError: 14 # Refer to tcms/__init__.py for details. 15 pass 16 else: 17 from django.db.backends.mysql.base import django_conversions 18 django_conversions.update({FIELD_TYPE.TIME: None}) 19 20 21 class DurationField(IntegerField): 22 """Duration field for test run 23 24 Value is stored as number of seconds in database and presents in Nitrate in 25 timedelta type. 26 27 Value should also be able to be serialized to integer as seconds, and then 28 deserialized from value of seconds. 29 """ 30 31 def to_python(self, value): 32 if isinstance(value, six.integer_types): 33 return datetime.timedelta(seconds=value) 34 elif isinstance(value, datetime.timedelta): 35 return value 36 else: 37 raise TypeError('Unable to convert %s to timedelta.' % value) 38 39 def from_db_value(self, value, expression, connection, context): 40 if value is None: 41 return value 42 return datetime.timedelta(seconds=value) 43 44 def get_db_prep_value(self, value, connection, prepared=True): 45 """convert datetime.timedelta to seconds. 46 47 1 day equal to 86400 seconds 48 """ 49 if isinstance(value, datetime.timedelta): 50 return value.seconds + (86400 * value.days) 51 else: 52 value = super(DurationField, self).get_db_prep_value( 53 value, connection, prepared) 54 return value 55 56 def formfield(self, form_class=DurationFormField, **kwargs): 57 defaults = {'help_text': 'Enter duration in the format: DDHHMM'} 58 defaults.update(kwargs) 59 return form_class(**defaults) 60 61 62 class NitrateBooleanField(BooleanField): 63 """Custom boolean field to allow accepting arbitrary bool values""" 64 65 def to_python(self, value): 66 if value in (1, '1', 'true', 'True', True): 67 return True 68 if value in (0, '0', 'false', 'False', False): 69 return False 70 raise ValidationError( 71 '{} is not recognized as a bool value.'.format(value)) 72 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/tcms/core/models/fields.py b/src/tcms/core/models/fields.py --- a/src/tcms/core/models/fields.py +++ b/src/tcms/core/models/fields.py @@ -36,7 +36,7 @@ else: raise TypeError('Unable to convert %s to timedelta.' % value) - def from_db_value(self, value, expression, connection, context): + def from_db_value(self, value, *args, **kwargs): if value is None: return value return datetime.timedelta(seconds=value)
{"golden_diff": "diff --git a/src/tcms/core/models/fields.py b/src/tcms/core/models/fields.py\n--- a/src/tcms/core/models/fields.py\n+++ b/src/tcms/core/models/fields.py\n@@ -36,7 +36,7 @@\n else:\n raise TypeError('Unable to convert %s to timedelta.' % value)\n \n- def from_db_value(self, value, expression, connection, context):\n+ def from_db_value(self, value, *args, **kwargs):\n if value is None:\n return value\n return datetime.timedelta(seconds=value)\n", "issue": "Fix call to DurationField.from_db_value() which will be removed in Django 3.0\nLots of such warning are output.\r\n\r\n```\r\nsrc/tests/xmlrpc/test_testcaseplan.py::TestCasePlanGet::test_get_with_negative_case_id\r\n /testenv/lib/python3.7/site-packages/django/db/models/sql/compiler.py:995: RemovedInDjango30Warning: Remove the context parameter from DurationField.from_db_value(). Support for it will be removed in Django 3.0.\r\n RemovedInDjango30Warning,\r\n```\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nimport datetime\nimport six\n\nfrom django.core.exceptions import ValidationError\nfrom django.db.models.fields import IntegerField\nfrom django.db.models.fields import BooleanField\n\nfrom tcms.core.forms.fields import DurationField as DurationFormField\n\ntry:\n from pymysql.constants import FIELD_TYPE\nexcept ImportError:\n # Refer to tcms/__init__.py for details.\n pass\nelse:\n from django.db.backends.mysql.base import django_conversions\n django_conversions.update({FIELD_TYPE.TIME: None})\n\n\nclass DurationField(IntegerField):\n \"\"\"Duration field for test run\n\n Value is stored as number of seconds in database and presents in Nitrate in\n timedelta type.\n\n Value should also be able to be serialized to integer as seconds, and then\n deserialized from value of seconds.\n \"\"\"\n\n def to_python(self, value):\n if isinstance(value, six.integer_types):\n return datetime.timedelta(seconds=value)\n elif isinstance(value, datetime.timedelta):\n return value\n else:\n raise TypeError('Unable to convert %s to timedelta.' % value)\n\n def from_db_value(self, value, expression, connection, context):\n if value is None:\n return value\n return datetime.timedelta(seconds=value)\n\n def get_db_prep_value(self, value, connection, prepared=True):\n \"\"\"convert datetime.timedelta to seconds.\n\n 1 day equal to 86400 seconds\n \"\"\"\n if isinstance(value, datetime.timedelta):\n return value.seconds + (86400 * value.days)\n else:\n value = super(DurationField, self).get_db_prep_value(\n value, connection, prepared)\n return value\n\n def formfield(self, form_class=DurationFormField, **kwargs):\n defaults = {'help_text': 'Enter duration in the format: DDHHMM'}\n defaults.update(kwargs)\n return form_class(**defaults)\n\n\nclass NitrateBooleanField(BooleanField):\n \"\"\"Custom boolean field to allow accepting arbitrary bool values\"\"\"\n\n def to_python(self, value):\n if value in (1, '1', 'true', 'True', True):\n return True\n if value in (0, '0', 'false', 'False', False):\n return False\n raise ValidationError(\n '{} is not recognized as a bool value.'.format(value))\n", "path": "src/tcms/core/models/fields.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nimport datetime\nimport six\n\nfrom django.core.exceptions import ValidationError\nfrom django.db.models.fields import IntegerField\nfrom django.db.models.fields import BooleanField\n\nfrom tcms.core.forms.fields import DurationField as DurationFormField\n\ntry:\n from pymysql.constants import FIELD_TYPE\nexcept ImportError:\n # Refer to tcms/__init__.py for details.\n pass\nelse:\n from django.db.backends.mysql.base import django_conversions\n django_conversions.update({FIELD_TYPE.TIME: None})\n\n\nclass DurationField(IntegerField):\n \"\"\"Duration field for test run\n\n Value is stored as number of seconds in database and presents in Nitrate in\n timedelta type.\n\n Value should also be able to be serialized to integer as seconds, and then\n deserialized from value of seconds.\n \"\"\"\n\n def to_python(self, value):\n if isinstance(value, six.integer_types):\n return datetime.timedelta(seconds=value)\n elif isinstance(value, datetime.timedelta):\n return value\n else:\n raise TypeError('Unable to convert %s to timedelta.' % value)\n\n def from_db_value(self, value, *args, **kwargs):\n if value is None:\n return value\n return datetime.timedelta(seconds=value)\n\n def get_db_prep_value(self, value, connection, prepared=True):\n \"\"\"convert datetime.timedelta to seconds.\n\n 1 day equal to 86400 seconds\n \"\"\"\n if isinstance(value, datetime.timedelta):\n return value.seconds + (86400 * value.days)\n else:\n value = super(DurationField, self).get_db_prep_value(\n value, connection, prepared)\n return value\n\n def formfield(self, form_class=DurationFormField, **kwargs):\n defaults = {'help_text': 'Enter duration in the format: DDHHMM'}\n defaults.update(kwargs)\n return form_class(**defaults)\n\n\nclass NitrateBooleanField(BooleanField):\n \"\"\"Custom boolean field to allow accepting arbitrary bool values\"\"\"\n\n def to_python(self, value):\n if value in (1, '1', 'true', 'True', True):\n return True\n if value in (0, '0', 'false', 'False', False):\n return False\n raise ValidationError(\n '{} is not recognized as a bool value.'.format(value))\n", "path": "src/tcms/core/models/fields.py"}]}
1,007
124
gh_patches_debug_2642
rasdani/github-patches
git_diff
sunpy__sunpy-3676
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Removing astropy_helpers section in CONTRIBUTING.rst <!-- This comments are hidden when you submit the issue so you do not need to remove them! Please be sure to check out our contributing guidelines: https://github.com/sunpy/sunpy/blob/master/CONTRIBUTING.rst Please be sure to check out our code of conduct: https://github.com/sunpy/sunpy/blob/master/CODE_OF_CONDUCT.rst --> <!-- Please have a search on our GitHub repository to see if a similar issue has already been posted. If a similar issue is closed, have a quick look to see if you are satisfied by the resolution. If not please go ahead and open an issue! --> ### Description <!-- Provide a general description of the bug. --> As of PR https://github.com/sunpy/sunpy/pull/3598, sunpy no longer needs `astropy_helpers`, and even it is removed from the package. I think there should not be a section of Astropy Helpers in contribution guidelines as well. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `sunpy/version.py` Content: ``` 1 # This file is for compatibility with astropy_helpers 2 version = 'unknown.dev' 3 try: 4 from importlib_metadata import version as _version, PackageNotFoundError 5 version = _version('sunpy') 6 except ImportError: 7 from pkg_resources import get_distribution, DistributionNotFound 8 try: 9 version = get_distribution("sunpy").version 10 except DistributionNotFound: 11 pass 12 except PackageNotFoundError: 13 pass 14 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/sunpy/version.py b/sunpy/version.py deleted file mode 100644 --- a/sunpy/version.py +++ /dev/null @@ -1,13 +0,0 @@ -# This file is for compatibility with astropy_helpers -version = 'unknown.dev' -try: - from importlib_metadata import version as _version, PackageNotFoundError - version = _version('sunpy') -except ImportError: - from pkg_resources import get_distribution, DistributionNotFound - try: - version = get_distribution("sunpy").version - except DistributionNotFound: - pass -except PackageNotFoundError: - pass
{"golden_diff": "diff --git a/sunpy/version.py b/sunpy/version.py\ndeleted file mode 100644\n--- a/sunpy/version.py\n+++ /dev/null\n@@ -1,13 +0,0 @@\n-# This file is for compatibility with astropy_helpers\n-version = 'unknown.dev'\n-try:\n- from importlib_metadata import version as _version, PackageNotFoundError\n- version = _version('sunpy')\n-except ImportError:\n- from pkg_resources import get_distribution, DistributionNotFound\n- try:\n- version = get_distribution(\"sunpy\").version\n- except DistributionNotFound:\n- pass\n-except PackageNotFoundError:\n- pass\n", "issue": "Removing astropy_helpers section in CONTRIBUTING.rst\n<!-- This comments are hidden when you submit the issue so you do not need to remove them!\r\nPlease be sure to check out our contributing guidelines: https://github.com/sunpy/sunpy/blob/master/CONTRIBUTING.rst\r\nPlease be sure to check out our code of conduct:\r\nhttps://github.com/sunpy/sunpy/blob/master/CODE_OF_CONDUCT.rst -->\r\n\r\n<!-- Please have a search on our GitHub repository to see if a similar issue has already been posted.\r\nIf a similar issue is closed, have a quick look to see if you are satisfied by the resolution.\r\nIf not please go ahead and open an issue! -->\r\n\r\n### Description\r\n<!-- Provide a general description of the bug. -->\r\nAs of PR https://github.com/sunpy/sunpy/pull/3598, sunpy no longer needs `astropy_helpers`, and even it is removed from the package.\r\nI think there should not be a section of Astropy Helpers in contribution guidelines as well.\n", "before_files": [{"content": "# This file is for compatibility with astropy_helpers\nversion = 'unknown.dev'\ntry:\n from importlib_metadata import version as _version, PackageNotFoundError\n version = _version('sunpy')\nexcept ImportError:\n from pkg_resources import get_distribution, DistributionNotFound\n try:\n version = get_distribution(\"sunpy\").version\n except DistributionNotFound:\n pass\nexcept PackageNotFoundError:\n pass\n", "path": "sunpy/version.py"}], "after_files": [{"content": null, "path": "sunpy/version.py"}]}
576
148
gh_patches_debug_6051
rasdani/github-patches
git_diff
coala__coala-3888
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- aspects/meta.py: Typo error <!-- Hello! If you're filing a bug, please include every step so as to help us reproduce it on our machines. If you're unsure about how to file an issue, use the issue template. If you need any help regarding usage of coala, check out the documentation or hit us up on chat. You can ignore or delete this text, it is commented and won't appear when the issue is submitted or previewed. Chat: https://coala.io/chat Issue Template: https://github.com/coala/coala/blob/master/CONTRIBUTING.rst#filing-issues Documentation: https://docs.coala.io --> Replace `int` -> `in` in `search for tastes int the sub-aspectclass` difficulty/newcomer --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `coalib/bearlib/aspects/meta.py` Content: ``` 1 from inspect import getmembers, signature 2 3 from coala_utils.decorators import generate_repr 4 5 from .base import aspectbase 6 from .docs import Documentation 7 from .taste import Taste 8 9 10 class aspectclass(type): 11 """ 12 Metaclass for aspectclasses. 13 14 Root aspectclass is :class:`coalib.bearlib.aspectclasses.Root`. 15 """ 16 def __init__(cls, clsname, bases, clsattrs): 17 """ 18 Initializes the ``.subaspects`` dict on new aspectclasses. 19 """ 20 cls.subaspects = {} 21 22 @property 23 def tastes(cls): 24 """ 25 Get a dictionary of all taste names mapped to their 26 :class:`coalib.bearlib.aspectclasses.Taste` instances. 27 """ 28 if cls.parent: 29 return dict(cls.parent.tastes, **cls._tastes) 30 31 return dict(cls._tastes) 32 33 def subaspect(cls, subcls): 34 """ 35 The sub-aspectclass decorator. 36 37 See :class:`coalib.bearlib.aspectclasses.Root` for description 38 and usage. 39 """ 40 aspectname = subcls.__name__ 41 42 docs = getattr(subcls, 'docs', None) 43 aspectdocs = Documentation(subcls.__doc__, **{ 44 attr: getattr(docs, attr, '') for attr in 45 list(signature(Documentation).parameters.keys())[1:]}) 46 47 # search for tastes int the sub-aspectclass 48 subtastes = {} 49 for name, member in getmembers(subcls): 50 if isinstance(member, Taste): 51 # tell the taste its own name 52 member.name = name 53 subtastes[name] = member 54 55 class Sub(subcls, aspectbase, metaclass=aspectclass): 56 __module__ = subcls.__module__ 57 58 parent = cls 59 60 docs = aspectdocs 61 _tastes = subtastes 62 63 members = sorted(Sub.tastes) 64 if members: 65 Sub = generate_repr(*members)(Sub) 66 67 Sub.__name__ = aspectname 68 Sub.__qualname__ = '%s.%s' % (cls.__qualname__, aspectname) 69 cls.subaspects[aspectname] = Sub 70 setattr(cls, aspectname, Sub) 71 return Sub 72 73 def __repr__(cls): 74 return '<%s %s>' % (type(cls).__name__, repr(cls.__qualname__)) 75 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/coalib/bearlib/aspects/meta.py b/coalib/bearlib/aspects/meta.py --- a/coalib/bearlib/aspects/meta.py +++ b/coalib/bearlib/aspects/meta.py @@ -44,7 +44,7 @@ attr: getattr(docs, attr, '') for attr in list(signature(Documentation).parameters.keys())[1:]}) - # search for tastes int the sub-aspectclass + # search for tastes in the sub-aspectclass subtastes = {} for name, member in getmembers(subcls): if isinstance(member, Taste):
{"golden_diff": "diff --git a/coalib/bearlib/aspects/meta.py b/coalib/bearlib/aspects/meta.py\n--- a/coalib/bearlib/aspects/meta.py\n+++ b/coalib/bearlib/aspects/meta.py\n@@ -44,7 +44,7 @@\n attr: getattr(docs, attr, '') for attr in\n list(signature(Documentation).parameters.keys())[1:]})\n \n- # search for tastes int the sub-aspectclass\n+ # search for tastes in the sub-aspectclass\n subtastes = {}\n for name, member in getmembers(subcls):\n if isinstance(member, Taste):\n", "issue": "aspects/meta.py: Typo error\n<!-- Hello! If you're filing a bug, please include every step so as to help us reproduce it on our machines. If you're unsure about how to file an issue, use the issue template. If you need any help regarding usage of coala, check out the documentation or hit us up on chat. You can ignore or delete this text, it is commented and won't appear when the issue is submitted or previewed.\r\n\r\nChat: https://coala.io/chat\r\nIssue Template: https://github.com/coala/coala/blob/master/CONTRIBUTING.rst#filing-issues\r\nDocumentation: https://docs.coala.io\r\n-->\r\nReplace `int` -> `in` in `search for tastes int the sub-aspectclass`\r\n\r\ndifficulty/newcomer\n", "before_files": [{"content": "from inspect import getmembers, signature\n\nfrom coala_utils.decorators import generate_repr\n\nfrom .base import aspectbase\nfrom .docs import Documentation\nfrom .taste import Taste\n\n\nclass aspectclass(type):\n \"\"\"\n Metaclass for aspectclasses.\n\n Root aspectclass is :class:`coalib.bearlib.aspectclasses.Root`.\n \"\"\"\n def __init__(cls, clsname, bases, clsattrs):\n \"\"\"\n Initializes the ``.subaspects`` dict on new aspectclasses.\n \"\"\"\n cls.subaspects = {}\n\n @property\n def tastes(cls):\n \"\"\"\n Get a dictionary of all taste names mapped to their\n :class:`coalib.bearlib.aspectclasses.Taste` instances.\n \"\"\"\n if cls.parent:\n return dict(cls.parent.tastes, **cls._tastes)\n\n return dict(cls._tastes)\n\n def subaspect(cls, subcls):\n \"\"\"\n The sub-aspectclass decorator.\n\n See :class:`coalib.bearlib.aspectclasses.Root` for description\n and usage.\n \"\"\"\n aspectname = subcls.__name__\n\n docs = getattr(subcls, 'docs', None)\n aspectdocs = Documentation(subcls.__doc__, **{\n attr: getattr(docs, attr, '') for attr in\n list(signature(Documentation).parameters.keys())[1:]})\n\n # search for tastes int the sub-aspectclass\n subtastes = {}\n for name, member in getmembers(subcls):\n if isinstance(member, Taste):\n # tell the taste its own name\n member.name = name\n subtastes[name] = member\n\n class Sub(subcls, aspectbase, metaclass=aspectclass):\n __module__ = subcls.__module__\n\n parent = cls\n\n docs = aspectdocs\n _tastes = subtastes\n\n members = sorted(Sub.tastes)\n if members:\n Sub = generate_repr(*members)(Sub)\n\n Sub.__name__ = aspectname\n Sub.__qualname__ = '%s.%s' % (cls.__qualname__, aspectname)\n cls.subaspects[aspectname] = Sub\n setattr(cls, aspectname, Sub)\n return Sub\n\n def __repr__(cls):\n return '<%s %s>' % (type(cls).__name__, repr(cls.__qualname__))\n", "path": "coalib/bearlib/aspects/meta.py"}], "after_files": [{"content": "from inspect import getmembers, signature\n\nfrom coala_utils.decorators import generate_repr\n\nfrom .base import aspectbase\nfrom .docs import Documentation\nfrom .taste import Taste\n\n\nclass aspectclass(type):\n \"\"\"\n Metaclass for aspectclasses.\n\n Root aspectclass is :class:`coalib.bearlib.aspectclasses.Root`.\n \"\"\"\n def __init__(cls, clsname, bases, clsattrs):\n \"\"\"\n Initializes the ``.subaspects`` dict on new aspectclasses.\n \"\"\"\n cls.subaspects = {}\n\n @property\n def tastes(cls):\n \"\"\"\n Get a dictionary of all taste names mapped to their\n :class:`coalib.bearlib.aspectclasses.Taste` instances.\n \"\"\"\n if cls.parent:\n return dict(cls.parent.tastes, **cls._tastes)\n\n return dict(cls._tastes)\n\n def subaspect(cls, subcls):\n \"\"\"\n The sub-aspectclass decorator.\n\n See :class:`coalib.bearlib.aspectclasses.Root` for description\n and usage.\n \"\"\"\n aspectname = subcls.__name__\n\n docs = getattr(subcls, 'docs', None)\n aspectdocs = Documentation(subcls.__doc__, **{\n attr: getattr(docs, attr, '') for attr in\n list(signature(Documentation).parameters.keys())[1:]})\n\n # search for tastes in the sub-aspectclass\n subtastes = {}\n for name, member in getmembers(subcls):\n if isinstance(member, Taste):\n # tell the taste its own name\n member.name = name\n subtastes[name] = member\n\n class Sub(subcls, aspectbase, metaclass=aspectclass):\n __module__ = subcls.__module__\n\n parent = cls\n\n docs = aspectdocs\n _tastes = subtastes\n\n members = sorted(Sub.tastes)\n if members:\n Sub = generate_repr(*members)(Sub)\n\n Sub.__name__ = aspectname\n Sub.__qualname__ = '%s.%s' % (cls.__qualname__, aspectname)\n cls.subaspects[aspectname] = Sub\n setattr(cls, aspectname, Sub)\n return Sub\n\n def __repr__(cls):\n return '<%s %s>' % (type(cls).__name__, repr(cls.__qualname__))\n", "path": "coalib/bearlib/aspects/meta.py"}]}
1,075
139
gh_patches_debug_39017
rasdani/github-patches
git_diff
pypa__pip-2464
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Interrupting a pip download with CTRL-C does not unhide the cursor Version: pep 6.0.8 Pressing CTRL-C while pip is downloading a package (and displaying its progress bar) shows an "Operation cancelled by user" message and drops the user back to the shell prompt, but does not unhide the cursor that was hidden while displaying the progress bar. Glancing at the code, it looks like the `progress` library already offers a `SigIntMixin` helper for handling this, and that pip's progress bar isn't using it. Maybe including this mixin in the appropriate place(s) is all that's needed? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pip/utils/ui.py` Content: ``` 1 from __future__ import absolute_import 2 from __future__ import division 3 4 import itertools 5 import sys 6 7 from pip.compat import WINDOWS 8 from pip.utils import format_size 9 from pip.utils.logging import get_indentation 10 from pip._vendor import six 11 from pip._vendor.progress.bar import Bar, IncrementalBar 12 from pip._vendor.progress.helpers import WritelnMixin 13 from pip._vendor.progress.spinner import Spinner 14 15 try: 16 from pip._vendor import colorama 17 # Lots of different errors can come from this, including SystemError and 18 # ImportError. 19 except Exception: 20 colorama = None 21 22 23 def _select_progress_class(preferred, fallback): 24 encoding = getattr(preferred.file, "encoding", None) 25 26 # If we don't know what encoding this file is in, then we'll just assume 27 # that it doesn't support unicode and use the ASCII bar. 28 if not encoding: 29 return fallback 30 31 # Collect all of the possible characters we want to use with the preferred 32 # bar. 33 characters = [ 34 getattr(preferred, "empty_fill", six.text_type()), 35 getattr(preferred, "fill", six.text_type()), 36 ] 37 characters += list(getattr(preferred, "phases", [])) 38 39 # Try to decode the characters we're using for the bar using the encoding 40 # of the given file, if this works then we'll assume that we can use the 41 # fancier bar and if not we'll fall back to the plaintext bar. 42 try: 43 six.text_type().join(characters).encode(encoding) 44 except UnicodeEncodeError: 45 return fallback 46 else: 47 return preferred 48 49 50 _BaseBar = _select_progress_class(IncrementalBar, Bar) 51 52 53 class DownloadProgressMixin(object): 54 55 def __init__(self, *args, **kwargs): 56 super(DownloadProgressMixin, self).__init__(*args, **kwargs) 57 self.message = (" " * (get_indentation() + 2)) + self.message 58 59 @property 60 def downloaded(self): 61 return format_size(self.index) 62 63 @property 64 def download_speed(self): 65 # Avoid zero division errors... 66 if self.avg == 0.0: 67 return "..." 68 return format_size(1 / self.avg) + "/s" 69 70 @property 71 def pretty_eta(self): 72 if self.eta: 73 return "eta %s" % self.eta_td 74 return "" 75 76 def iter(self, it, n=1): 77 for x in it: 78 yield x 79 self.next(n) 80 self.finish() 81 82 83 class WindowsMixin(object): 84 85 def __init__(self, *args, **kwargs): 86 # The Windows terminal does not support the hide/show cursor ANSI codes 87 # even with colorama. So we'll ensure that hide_cursor is False on 88 # Windows. 89 # This call neds to go before the super() call, so that hide_cursor 90 # is set in time. The base progress bar class writes the "hide cursor" 91 # code to the terminal in its init, so if we don't set this soon 92 # enough, we get a "hide" with no corresponding "show"... 93 if WINDOWS and self.hide_cursor: 94 self.hide_cursor = False 95 96 super(WindowsMixin, self).__init__(*args, **kwargs) 97 98 # Check if we are running on Windows and we have the colorama module, 99 # if we do then wrap our file with it. 100 if WINDOWS and colorama: 101 self.file = colorama.AnsiToWin32(self.file) 102 # The progress code expects to be able to call self.file.isatty() 103 # but the colorama.AnsiToWin32() object doesn't have that, so we'll 104 # add it. 105 self.file.isatty = lambda: self.file.wrapped.isatty() 106 # The progress code expects to be able to call self.file.flush() 107 # but the colorama.AnsiToWin32() object doesn't have that, so we'll 108 # add it. 109 self.file.flush = lambda: self.file.wrapped.flush() 110 111 112 class DownloadProgressBar(WindowsMixin, DownloadProgressMixin, _BaseBar): 113 114 file = sys.stdout 115 message = "%(percent)d%%" 116 suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" 117 118 119 class DownloadProgressSpinner(WindowsMixin, DownloadProgressMixin, 120 WritelnMixin, Spinner): 121 122 file = sys.stdout 123 suffix = "%(downloaded)s %(download_speed)s" 124 125 def next_phase(self): 126 if not hasattr(self, "_phaser"): 127 self._phaser = itertools.cycle(self.phases) 128 return next(self._phaser) 129 130 def update(self): 131 message = self.message % self 132 phase = self.next_phase() 133 suffix = self.suffix % self 134 line = ''.join([ 135 message, 136 " " if message else "", 137 phase, 138 " " if suffix else "", 139 suffix, 140 ]) 141 142 self.writeln(line) 143 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/pip/utils/ui.py b/pip/utils/ui.py --- a/pip/utils/ui.py +++ b/pip/utils/ui.py @@ -3,6 +3,7 @@ import itertools import sys +from signal import signal, SIGINT, default_int_handler from pip.compat import WINDOWS from pip.utils import format_size @@ -50,6 +51,61 @@ _BaseBar = _select_progress_class(IncrementalBar, Bar) +class InterruptibleMixin(object): + """ + Helper to ensure that self.finish() gets called on keyboard interrupt. + + This allows downloads to be interrupted without leaving temporary state + (like hidden cursors) behind. + + This class is similar to the progress library's existing SigIntMixin + helper, but as of version 1.2, that helper has the following problems: + + 1. It calls sys.exit(). + 2. It discards the existing SIGINT handler completely. + 3. It leaves its own handler in place even after an uninterrupted finish, + which will have unexpected delayed effects if the user triggers an + unrelated keyboard interrupt some time after a progress-displaying + download has already completed, for example. + """ + + def __init__(self, *args, **kwargs): + """ + Save the original SIGINT handler for later. + """ + super(InterruptibleMixin, self).__init__(*args, **kwargs) + + self.original_handler = signal(SIGINT, self.handle_sigint) + + # If signal() returns None, the previous handler was not installed from + # Python, and we cannot restore it. This probably should not happen, + # but if it does, we must restore something sensible instead, at least. + # The least bad option should be Python's default SIGINT handler, which + # just raises KeyboardInterrupt. + if self.original_handler is None: + self.original_handler = default_int_handler + + def finish(self): + """ + Restore the original SIGINT handler after finishing. + + This should happen regardless of whether the progress display finishes + normally, or gets interrupted. + """ + super(InterruptibleMixin, self).finish() + signal(SIGINT, self.original_handler) + + def handle_sigint(self, signum, frame): + """ + Call self.finish() before delegating to the original SIGINT handler. + + This handler should only be in place while the progress display is + active. + """ + self.finish() + self.original_handler(signum, frame) + + class DownloadProgressMixin(object): def __init__(self, *args, **kwargs): @@ -109,15 +165,16 @@ self.file.flush = lambda: self.file.wrapped.flush() -class DownloadProgressBar(WindowsMixin, DownloadProgressMixin, _BaseBar): +class DownloadProgressBar(WindowsMixin, InterruptibleMixin, + DownloadProgressMixin, _BaseBar): file = sys.stdout message = "%(percent)d%%" suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s" -class DownloadProgressSpinner(WindowsMixin, DownloadProgressMixin, - WritelnMixin, Spinner): +class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin, + DownloadProgressMixin, WritelnMixin, Spinner): file = sys.stdout suffix = "%(downloaded)s %(download_speed)s"
{"golden_diff": "diff --git a/pip/utils/ui.py b/pip/utils/ui.py\n--- a/pip/utils/ui.py\n+++ b/pip/utils/ui.py\n@@ -3,6 +3,7 @@\n \n import itertools\n import sys\n+from signal import signal, SIGINT, default_int_handler\n \n from pip.compat import WINDOWS\n from pip.utils import format_size\n@@ -50,6 +51,61 @@\n _BaseBar = _select_progress_class(IncrementalBar, Bar)\n \n \n+class InterruptibleMixin(object):\n+ \"\"\"\n+ Helper to ensure that self.finish() gets called on keyboard interrupt.\n+\n+ This allows downloads to be interrupted without leaving temporary state\n+ (like hidden cursors) behind.\n+\n+ This class is similar to the progress library's existing SigIntMixin\n+ helper, but as of version 1.2, that helper has the following problems:\n+\n+ 1. It calls sys.exit().\n+ 2. It discards the existing SIGINT handler completely.\n+ 3. It leaves its own handler in place even after an uninterrupted finish,\n+ which will have unexpected delayed effects if the user triggers an\n+ unrelated keyboard interrupt some time after a progress-displaying\n+ download has already completed, for example.\n+ \"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ \"\"\"\n+ Save the original SIGINT handler for later.\n+ \"\"\"\n+ super(InterruptibleMixin, self).__init__(*args, **kwargs)\n+\n+ self.original_handler = signal(SIGINT, self.handle_sigint)\n+\n+ # If signal() returns None, the previous handler was not installed from\n+ # Python, and we cannot restore it. This probably should not happen,\n+ # but if it does, we must restore something sensible instead, at least.\n+ # The least bad option should be Python's default SIGINT handler, which\n+ # just raises KeyboardInterrupt.\n+ if self.original_handler is None:\n+ self.original_handler = default_int_handler\n+\n+ def finish(self):\n+ \"\"\"\n+ Restore the original SIGINT handler after finishing.\n+\n+ This should happen regardless of whether the progress display finishes\n+ normally, or gets interrupted.\n+ \"\"\"\n+ super(InterruptibleMixin, self).finish()\n+ signal(SIGINT, self.original_handler)\n+\n+ def handle_sigint(self, signum, frame):\n+ \"\"\"\n+ Call self.finish() before delegating to the original SIGINT handler.\n+\n+ This handler should only be in place while the progress display is\n+ active.\n+ \"\"\"\n+ self.finish()\n+ self.original_handler(signum, frame)\n+\n+\n class DownloadProgressMixin(object):\n \n def __init__(self, *args, **kwargs):\n@@ -109,15 +165,16 @@\n self.file.flush = lambda: self.file.wrapped.flush()\n \n \n-class DownloadProgressBar(WindowsMixin, DownloadProgressMixin, _BaseBar):\n+class DownloadProgressBar(WindowsMixin, InterruptibleMixin,\n+ DownloadProgressMixin, _BaseBar):\n \n file = sys.stdout\n message = \"%(percent)d%%\"\n suffix = \"%(downloaded)s %(download_speed)s %(pretty_eta)s\"\n \n \n-class DownloadProgressSpinner(WindowsMixin, DownloadProgressMixin,\n- WritelnMixin, Spinner):\n+class DownloadProgressSpinner(WindowsMixin, InterruptibleMixin,\n+ DownloadProgressMixin, WritelnMixin, Spinner):\n \n file = sys.stdout\n suffix = \"%(downloaded)s %(download_speed)s\"\n", "issue": "Interrupting a pip download with CTRL-C does not unhide the cursor\nVersion: pep 6.0.8\n\nPressing CTRL-C while pip is downloading a package (and displaying its progress bar) shows an \"Operation cancelled by user\" message and drops the user back to the shell prompt, but does not unhide the cursor that was hidden while displaying the progress bar.\n\nGlancing at the code, it looks like the `progress` library already offers a `SigIntMixin` helper for handling this, and that pip's progress bar isn't using it. Maybe including this mixin in the appropriate place(s) is all that's needed?\n\n", "before_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import division\n\nimport itertools\nimport sys\n\nfrom pip.compat import WINDOWS\nfrom pip.utils import format_size\nfrom pip.utils.logging import get_indentation\nfrom pip._vendor import six\nfrom pip._vendor.progress.bar import Bar, IncrementalBar\nfrom pip._vendor.progress.helpers import WritelnMixin\nfrom pip._vendor.progress.spinner import Spinner\n\ntry:\n from pip._vendor import colorama\n# Lots of different errors can come from this, including SystemError and\n# ImportError.\nexcept Exception:\n colorama = None\n\n\ndef _select_progress_class(preferred, fallback):\n encoding = getattr(preferred.file, \"encoding\", None)\n\n # If we don't know what encoding this file is in, then we'll just assume\n # that it doesn't support unicode and use the ASCII bar.\n if not encoding:\n return fallback\n\n # Collect all of the possible characters we want to use with the preferred\n # bar.\n characters = [\n getattr(preferred, \"empty_fill\", six.text_type()),\n getattr(preferred, \"fill\", six.text_type()),\n ]\n characters += list(getattr(preferred, \"phases\", []))\n\n # Try to decode the characters we're using for the bar using the encoding\n # of the given file, if this works then we'll assume that we can use the\n # fancier bar and if not we'll fall back to the plaintext bar.\n try:\n six.text_type().join(characters).encode(encoding)\n except UnicodeEncodeError:\n return fallback\n else:\n return preferred\n\n\n_BaseBar = _select_progress_class(IncrementalBar, Bar)\n\n\nclass DownloadProgressMixin(object):\n\n def __init__(self, *args, **kwargs):\n super(DownloadProgressMixin, self).__init__(*args, **kwargs)\n self.message = (\" \" * (get_indentation() + 2)) + self.message\n\n @property\n def downloaded(self):\n return format_size(self.index)\n\n @property\n def download_speed(self):\n # Avoid zero division errors...\n if self.avg == 0.0:\n return \"...\"\n return format_size(1 / self.avg) + \"/s\"\n\n @property\n def pretty_eta(self):\n if self.eta:\n return \"eta %s\" % self.eta_td\n return \"\"\n\n def iter(self, it, n=1):\n for x in it:\n yield x\n self.next(n)\n self.finish()\n\n\nclass WindowsMixin(object):\n\n def __init__(self, *args, **kwargs):\n # The Windows terminal does not support the hide/show cursor ANSI codes\n # even with colorama. So we'll ensure that hide_cursor is False on\n # Windows.\n # This call neds to go before the super() call, so that hide_cursor\n # is set in time. The base progress bar class writes the \"hide cursor\"\n # code to the terminal in its init, so if we don't set this soon\n # enough, we get a \"hide\" with no corresponding \"show\"...\n if WINDOWS and self.hide_cursor:\n self.hide_cursor = False\n\n super(WindowsMixin, self).__init__(*args, **kwargs)\n\n # Check if we are running on Windows and we have the colorama module,\n # if we do then wrap our file with it.\n if WINDOWS and colorama:\n self.file = colorama.AnsiToWin32(self.file)\n # The progress code expects to be able to call self.file.isatty()\n # but the colorama.AnsiToWin32() object doesn't have that, so we'll\n # add it.\n self.file.isatty = lambda: self.file.wrapped.isatty()\n # The progress code expects to be able to call self.file.flush()\n # but the colorama.AnsiToWin32() object doesn't have that, so we'll\n # add it.\n self.file.flush = lambda: self.file.wrapped.flush()\n\n\nclass DownloadProgressBar(WindowsMixin, DownloadProgressMixin, _BaseBar):\n\n file = sys.stdout\n message = \"%(percent)d%%\"\n suffix = \"%(downloaded)s %(download_speed)s %(pretty_eta)s\"\n\n\nclass DownloadProgressSpinner(WindowsMixin, DownloadProgressMixin,\n WritelnMixin, Spinner):\n\n file = sys.stdout\n suffix = \"%(downloaded)s %(download_speed)s\"\n\n def next_phase(self):\n if not hasattr(self, \"_phaser\"):\n self._phaser = itertools.cycle(self.phases)\n return next(self._phaser)\n\n def update(self):\n message = self.message % self\n phase = self.next_phase()\n suffix = self.suffix % self\n line = ''.join([\n message,\n \" \" if message else \"\",\n phase,\n \" \" if suffix else \"\",\n suffix,\n ])\n\n self.writeln(line)\n", "path": "pip/utils/ui.py"}], "after_files": [{"content": "from __future__ import absolute_import\nfrom __future__ import division\n\nimport itertools\nimport sys\nfrom signal import signal, SIGINT, default_int_handler\n\nfrom pip.compat import WINDOWS\nfrom pip.utils import format_size\nfrom pip.utils.logging import get_indentation\nfrom pip._vendor import six\nfrom pip._vendor.progress.bar import Bar, IncrementalBar\nfrom pip._vendor.progress.helpers import WritelnMixin\nfrom pip._vendor.progress.spinner import Spinner\n\ntry:\n from pip._vendor import colorama\n# Lots of different errors can come from this, including SystemError and\n# ImportError.\nexcept Exception:\n colorama = None\n\n\ndef _select_progress_class(preferred, fallback):\n encoding = getattr(preferred.file, \"encoding\", None)\n\n # If we don't know what encoding this file is in, then we'll just assume\n # that it doesn't support unicode and use the ASCII bar.\n if not encoding:\n return fallback\n\n # Collect all of the possible characters we want to use with the preferred\n # bar.\n characters = [\n getattr(preferred, \"empty_fill\", six.text_type()),\n getattr(preferred, \"fill\", six.text_type()),\n ]\n characters += list(getattr(preferred, \"phases\", []))\n\n # Try to decode the characters we're using for the bar using the encoding\n # of the given file, if this works then we'll assume that we can use the\n # fancier bar and if not we'll fall back to the plaintext bar.\n try:\n six.text_type().join(characters).encode(encoding)\n except UnicodeEncodeError:\n return fallback\n else:\n return preferred\n\n\n_BaseBar = _select_progress_class(IncrementalBar, Bar)\n\n\nclass InterruptibleMixin(object):\n \"\"\"\n Helper to ensure that self.finish() gets called on keyboard interrupt.\n\n This allows downloads to be interrupted without leaving temporary state\n (like hidden cursors) behind.\n\n This class is similar to the progress library's existing SigIntMixin\n helper, but as of version 1.2, that helper has the following problems:\n\n 1. It calls sys.exit().\n 2. It discards the existing SIGINT handler completely.\n 3. It leaves its own handler in place even after an uninterrupted finish,\n which will have unexpected delayed effects if the user triggers an\n unrelated keyboard interrupt some time after a progress-displaying\n download has already completed, for example.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Save the original SIGINT handler for later.\n \"\"\"\n super(InterruptibleMixin, self).__init__(*args, **kwargs)\n\n self.original_handler = signal(SIGINT, self.handle_sigint)\n\n # If signal() returns None, the previous handler was not installed from\n # Python, and we cannot restore it. This probably should not happen,\n # but if it does, we must restore something sensible instead, at least.\n # The least bad option should be Python's default SIGINT handler, which\n # just raises KeyboardInterrupt.\n if self.original_handler is None:\n self.original_handler = default_int_handler\n\n def finish(self):\n \"\"\"\n Restore the original SIGINT handler after finishing.\n\n This should happen regardless of whether the progress display finishes\n normally, or gets interrupted.\n \"\"\"\n super(InterruptibleMixin, self).finish()\n signal(SIGINT, self.original_handler)\n\n def handle_sigint(self, signum, frame):\n \"\"\"\n Call self.finish() before delegating to the original SIGINT handler.\n\n This handler should only be in place while the progress display is\n active.\n \"\"\"\n self.finish()\n self.original_handler(signum, frame)\n\n\nclass DownloadProgressMixin(object):\n\n def __init__(self, *args, **kwargs):\n super(DownloadProgressMixin, self).__init__(*args, **kwargs)\n self.message = (\" \" * (get_indentation() + 2)) + self.message\n\n @property\n def downloaded(self):\n return format_size(self.index)\n\n @property\n def download_speed(self):\n # Avoid zero division errors...\n if self.avg == 0.0:\n return \"...\"\n return format_size(1 / self.avg) + \"/s\"\n\n @property\n def pretty_eta(self):\n if self.eta:\n return \"eta %s\" % self.eta_td\n return \"\"\n\n def iter(self, it, n=1):\n for x in it:\n yield x\n self.next(n)\n self.finish()\n\n\nclass WindowsMixin(object):\n\n def __init__(self, *args, **kwargs):\n # The Windows terminal does not support the hide/show cursor ANSI codes\n # even with colorama. So we'll ensure that hide_cursor is False on\n # Windows.\n # This call neds to go before the super() call, so that hide_cursor\n # is set in time. The base progress bar class writes the \"hide cursor\"\n # code to the terminal in its init, so if we don't set this soon\n # enough, we get a \"hide\" with no corresponding \"show\"...\n if WINDOWS and self.hide_cursor:\n self.hide_cursor = False\n\n super(WindowsMixin, self).__init__(*args, **kwargs)\n\n # Check if we are running on Windows and we have the colorama module,\n # if we do then wrap our file with it.\n if WINDOWS and colorama:\n self.file = colorama.AnsiToWin32(self.file)\n # The progress code expects to be able to call self.file.isatty()\n # but the colorama.AnsiToWin32() object doesn't have that, so we'll\n # add it.\n self.file.isatty = lambda: self.file.wrapped.isatty()\n # The progress code expects to be able to call self.file.flush()\n # but the colorama.AnsiToWin32() object doesn't have that, so we'll\n # add it.\n self.file.flush = lambda: self.file.wrapped.flush()\n\n\nclass DownloadProgressBar(WindowsMixin, InterruptibleMixin,\n DownloadProgressMixin, _BaseBar):\n\n file = sys.stdout\n message = \"%(percent)d%%\"\n suffix = \"%(downloaded)s %(download_speed)s %(pretty_eta)s\"\n\n\nclass DownloadProgressSpinner(WindowsMixin, InterruptibleMixin,\n DownloadProgressMixin, WritelnMixin, Spinner):\n\n file = sys.stdout\n suffix = \"%(downloaded)s %(download_speed)s\"\n\n def next_phase(self):\n if not hasattr(self, \"_phaser\"):\n self._phaser = itertools.cycle(self.phases)\n return next(self._phaser)\n\n def update(self):\n message = self.message % self\n phase = self.next_phase()\n suffix = self.suffix % self\n line = ''.join([\n message,\n \" \" if message else \"\",\n phase,\n \" \" if suffix else \"\",\n suffix,\n ])\n\n self.writeln(line)\n", "path": "pip/utils/ui.py"}]}
1,786
763
gh_patches_debug_17530
rasdani/github-patches
git_diff
biopython__biopython-2513
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Remove use of Bio._py3k (Python 2 / 3 compatibility) As of Biopython 1.76 (released December 2019), we are dropping Python 2 support and focusing on Python 3.6 or later. This means we no longer need our (internal) Python 2 vs 3 compatibility library ``Bio._py3k`` (which is a bit like the third party library ``six``). This issue is suitable and specifically targeting first time contributors. There are lots of cases: ``` $ grep _py3k Bio*/*.py Bio/*/*.py Bio/*/*/*.py Bio/File.py:from Bio._py3k import basestring Bio/MarkovModel.py: from Bio._py3k import StringIO Bio/Seq.py:from Bio._py3k import range Bio/Seq.py:from Bio._py3k import basestring ... ``` Example One ------------ Taking the first example, ``from Bio._py3k import basestring`` we see that this is defined under Python 3 as an alias of ``str``: https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L56 ```python # Lots of our Python 2 code uses isinstance(x, basestring) # which after 2to3 becomes isinstance(x, str) basestring = str unicode = str ``` Therefore the fix for ``Bio/File.py`` is to remove the ``from Bio._py3k import basestring`` line, and update where ``basestring`` was used to instead use ``str``, which in this case means editing one line: ```python if isinstance(handleish, basestring): ``` with: ```python if isinstance(handleish, str): ``` Example Two ------------ Taking the second example, ``Bio/MarkovModel.py`` has ``from Bio._py3k import StringIO`` which we find on Python 3 can just be replaced with ``from io import StringIO`` https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L130 Contributing ----------- Could any newcomer wanting to work on this first comment on this issue saying which file(s) they are going to start with (e.g. ``Bio/File.py``, or ``BioSQL/``) to avoid duplication of effort. (*Update: The consensus was to switch to be function or constant instead, since they generally require the same technique/fix each time*) Then read https://github.com/biopython/biopython/blob/master/CONTRIBUTING.rst and setup ``flake8`` on your machine. Then make a pull request making the necessary changes so that those files no longer import from ``Bio._py3k``. Once that's done, you could pick some more to work on. Eventually there will be nothing using ``Bio._py3k`` and that code itself can be removed, and this issue closed. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `Bio/_py3k/__init__.py` Content: ``` 1 # Copyright 2010-2018 by Peter Cock. All rights reserved. 2 # 3 # This file is part of the Biopython distribution and governed by your 4 # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". 5 # Please see the LICENSE file that should have been included as part of this 6 # package. 7 """Python 3 compatibility tools (PRIVATE). 8 9 Once we drop support for Python 2, the whole of Bio._py3k will 10 go away. 11 """ 12 13 # From the point of view of pep8 and flake8, there are lots of issues with 14 # this file. This line tells flake8 to ignore it for quality assurance: 15 # flake8: noqa 16 17 import sys 18 19 import codecs 20 21 22 def _bytes_bytearray_to_str(s): 23 """If s is bytes or bytearray, convert to a unicode string (PRIVATE).""" 24 if isinstance(s, (bytes, bytearray)): 25 return s.decode() 26 return s 27 28 29 import io 30 import locale 31 32 # Python 3.4 onwards, the standard library wrappers should work: 33 def _binary_to_string_handle(handle): 34 """Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE).""" 35 try: 36 # If this is a network handle from urllib, 37 # the HTTP headers may tell us the encoding. 38 encoding = handle.headers.get_content_charset() 39 except AttributeError: 40 encoding = None 41 if encoding is None: 42 # The W3C recommendation is: 43 # When no explicit charset parameter is provided by the sender, 44 # media subtypes of the "text" type are defined to have a default 45 # charset value of "ISO-8859-1" when received via HTTP. 46 # "ISO-8859-1" is also known as 'latin-1' 47 # See the following for more detail: 48 # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 49 encoding = "latin-1" 50 wrapped = io.TextIOWrapper(io.BufferedReader(handle), encoding=encoding) 51 try: 52 # If wrapping an online handle, this is nice to have: 53 wrapped.url = handle.url 54 except AttributeError: 55 pass 56 return wrapped 57 58 59 # On Python 3 urllib, urllib2, and urlparse were merged: 60 from urllib.request import urlopen, Request, urlparse, urlcleanup 61 from urllib.parse import urlencode, quote 62 from urllib.error import URLError, HTTPError 63 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/Bio/_py3k/__init__.py b/Bio/_py3k/__init__.py --- a/Bio/_py3k/__init__.py +++ b/Bio/_py3k/__init__.py @@ -14,20 +14,7 @@ # this file. This line tells flake8 to ignore it for quality assurance: # flake8: noqa -import sys - -import codecs - - -def _bytes_bytearray_to_str(s): - """If s is bytes or bytearray, convert to a unicode string (PRIVATE).""" - if isinstance(s, (bytes, bytearray)): - return s.decode() - return s - - import io -import locale # Python 3.4 onwards, the standard library wrappers should work: def _binary_to_string_handle(handle): @@ -54,9 +41,3 @@ except AttributeError: pass return wrapped - - -# On Python 3 urllib, urllib2, and urlparse were merged: -from urllib.request import urlopen, Request, urlparse, urlcleanup -from urllib.parse import urlencode, quote -from urllib.error import URLError, HTTPError
{"golden_diff": "diff --git a/Bio/_py3k/__init__.py b/Bio/_py3k/__init__.py\n--- a/Bio/_py3k/__init__.py\n+++ b/Bio/_py3k/__init__.py\n@@ -14,20 +14,7 @@\n # this file. This line tells flake8 to ignore it for quality assurance:\n # flake8: noqa\n \n-import sys\n-\n-import codecs\n-\n-\n-def _bytes_bytearray_to_str(s):\n- \"\"\"If s is bytes or bytearray, convert to a unicode string (PRIVATE).\"\"\"\n- if isinstance(s, (bytes, bytearray)):\n- return s.decode()\n- return s\n-\n-\n import io\n-import locale\n \n # Python 3.4 onwards, the standard library wrappers should work:\n def _binary_to_string_handle(handle):\n@@ -54,9 +41,3 @@\n except AttributeError:\n pass\n return wrapped\n-\n-\n-# On Python 3 urllib, urllib2, and urlparse were merged:\n-from urllib.request import urlopen, Request, urlparse, urlcleanup\n-from urllib.parse import urlencode, quote\n-from urllib.error import URLError, HTTPError\n", "issue": "Remove use of Bio._py3k (Python 2 / 3 compatibility)\nAs of Biopython 1.76 (released December 2019), we are dropping Python 2 support and focusing on Python 3.6 or later. This means we no longer need our (internal) Python 2 vs 3 compatibility library ``Bio._py3k`` (which is a bit like the third party library ``six``).\r\n\r\nThis issue is suitable and specifically targeting first time contributors.\r\n\r\nThere are lots of cases:\r\n\r\n```\r\n$ grep _py3k Bio*/*.py Bio/*/*.py Bio/*/*/*.py\r\nBio/File.py:from Bio._py3k import basestring\r\nBio/MarkovModel.py: from Bio._py3k import StringIO\r\nBio/Seq.py:from Bio._py3k import range\r\nBio/Seq.py:from Bio._py3k import basestring\r\n...\r\n```\r\n\r\nExample One\r\n------------\r\n\r\nTaking the first example, ``from Bio._py3k import basestring`` we see that this is defined under Python 3 as an alias of ``str``:\r\n\r\nhttps://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L56\r\n\r\n```python\r\n # Lots of our Python 2 code uses isinstance(x, basestring)\r\n # which after 2to3 becomes isinstance(x, str)\r\n basestring = str\r\n unicode = str\r\n```\r\n\r\nTherefore the fix for ``Bio/File.py`` is to remove the ``from Bio._py3k import basestring`` line, and update where ``basestring`` was used to instead use ``str``, which in this case means editing one line:\r\n\r\n```python\r\nif isinstance(handleish, basestring):\r\n```\r\n\r\nwith:\r\n\r\n```python\r\nif isinstance(handleish, str):\r\n```\r\n\r\nExample Two\r\n------------\r\n\r\nTaking the second example, ``Bio/MarkovModel.py`` has ``from Bio._py3k import StringIO`` which we find on Python 3 can just be replaced with ``from io import StringIO``\r\n\r\nhttps://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L130\r\n\r\nContributing\r\n-----------\r\n\r\nCould any newcomer wanting to work on this first comment on this issue saying which file(s) they are going to start with (e.g. ``Bio/File.py``, or ``BioSQL/``) to avoid duplication of effort.\r\n\r\n(*Update: The consensus was to switch to be function or constant instead, since they generally require the same technique/fix each time*)\r\n\r\nThen read https://github.com/biopython/biopython/blob/master/CONTRIBUTING.rst and setup ``flake8`` on your machine.\r\n\r\nThen make a pull request making the necessary changes so that those files no longer import from ``Bio._py3k``. Once that's done, you could pick some more to work on.\r\n\r\nEventually there will be nothing using ``Bio._py3k`` and that code itself can be removed, and this issue closed.\n", "before_files": [{"content": "# Copyright 2010-2018 by Peter Cock. All rights reserved.\n#\n# This file is part of the Biopython distribution and governed by your\n# choice of the \"Biopython License Agreement\" or the \"BSD 3-Clause License\".\n# Please see the LICENSE file that should have been included as part of this\n# package.\n\"\"\"Python 3 compatibility tools (PRIVATE).\n\nOnce we drop support for Python 2, the whole of Bio._py3k will\ngo away.\n\"\"\"\n\n# From the point of view of pep8 and flake8, there are lots of issues with\n# this file. This line tells flake8 to ignore it for quality assurance:\n# flake8: noqa\n\nimport sys\n\nimport codecs\n\n\ndef _bytes_bytearray_to_str(s):\n \"\"\"If s is bytes or bytearray, convert to a unicode string (PRIVATE).\"\"\"\n if isinstance(s, (bytes, bytearray)):\n return s.decode()\n return s\n\n\nimport io\nimport locale\n\n# Python 3.4 onwards, the standard library wrappers should work:\ndef _binary_to_string_handle(handle):\n \"\"\"Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE).\"\"\"\n try:\n # If this is a network handle from urllib,\n # the HTTP headers may tell us the encoding.\n encoding = handle.headers.get_content_charset()\n except AttributeError:\n encoding = None\n if encoding is None:\n # The W3C recommendation is:\n # When no explicit charset parameter is provided by the sender,\n # media subtypes of the \"text\" type are defined to have a default\n # charset value of \"ISO-8859-1\" when received via HTTP.\n # \"ISO-8859-1\" is also known as 'latin-1'\n # See the following for more detail:\n # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1\n encoding = \"latin-1\"\n wrapped = io.TextIOWrapper(io.BufferedReader(handle), encoding=encoding)\n try:\n # If wrapping an online handle, this is nice to have:\n wrapped.url = handle.url\n except AttributeError:\n pass\n return wrapped\n\n\n# On Python 3 urllib, urllib2, and urlparse were merged:\nfrom urllib.request import urlopen, Request, urlparse, urlcleanup\nfrom urllib.parse import urlencode, quote\nfrom urllib.error import URLError, HTTPError\n", "path": "Bio/_py3k/__init__.py"}], "after_files": [{"content": "# Copyright 2010-2018 by Peter Cock. All rights reserved.\n#\n# This file is part of the Biopython distribution and governed by your\n# choice of the \"Biopython License Agreement\" or the \"BSD 3-Clause License\".\n# Please see the LICENSE file that should have been included as part of this\n# package.\n\"\"\"Python 3 compatibility tools (PRIVATE).\n\nOnce we drop support for Python 2, the whole of Bio._py3k will\ngo away.\n\"\"\"\n\n# From the point of view of pep8 and flake8, there are lots of issues with\n# this file. This line tells flake8 to ignore it for quality assurance:\n# flake8: noqa\n\nimport io\n\n# Python 3.4 onwards, the standard library wrappers should work:\ndef _binary_to_string_handle(handle):\n \"\"\"Treat a binary (bytes) handle like a text (unicode) handle (PRIVATE).\"\"\"\n try:\n # If this is a network handle from urllib,\n # the HTTP headers may tell us the encoding.\n encoding = handle.headers.get_content_charset()\n except AttributeError:\n encoding = None\n if encoding is None:\n # The W3C recommendation is:\n # When no explicit charset parameter is provided by the sender,\n # media subtypes of the \"text\" type are defined to have a default\n # charset value of \"ISO-8859-1\" when received via HTTP.\n # \"ISO-8859-1\" is also known as 'latin-1'\n # See the following for more detail:\n # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1\n encoding = \"latin-1\"\n wrapped = io.TextIOWrapper(io.BufferedReader(handle), encoding=encoding)\n try:\n # If wrapping an online handle, this is nice to have:\n wrapped.url = handle.url\n except AttributeError:\n pass\n return wrapped\n", "path": "Bio/_py3k/__init__.py"}]}
1,581
252
gh_patches_debug_19359
rasdani/github-patches
git_diff
fedora-infra__bodhi-4115
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add the possibility to query updates by releases in graphql We currently have a getUpdates query in graphql that let us query updates using certain attributes, we should add the possibility to give a release name and get all the updates from a release. For example ```query {getUpdates(releaseName: "F33") {alias}}``` For this we will most likely need to use a join query in the graphlq resolve function (https://github.com/fedora-infra/bodhi/blob/develop/bodhi/server/services/graphql.py#L132) to exploit the relationship between Updates and release. Some hints https://stackoverflow.com/questions/8561470/sqlalchemy-filtering-by-relationship-attribute --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `bodhi/server/services/graphql.py` Content: ``` 1 # Copyright © 2020 Red Hat Inc., and others. 2 # 3 # This file is part of Bodhi. 4 # 5 # This program is free software; you can redistribute it and/or 6 # modify it under the terms of the GNU General Public License 7 # as published by the Free Software Foundation; either version 2 8 # of the License, or (at your option) any later version. 9 # 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU General Public License for more details. 14 # 15 # You should have received a copy of the GNU General Public License 16 # along with this program; if not, write to the Free Software 17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 """Defines API endpoints related to GraphQL objects.""" 19 import graphene 20 from cornice import Service 21 from webob_graphql import serve_graphql_request 22 23 from bodhi.server.config import config 24 from bodhi.server.graphql_schemas import Release, ReleaseModel, Update, UpdateModel 25 26 graphql = Service(name='graphql', path='/graphql', description='graphql service') 27 28 29 @graphql.get() 30 @graphql.post() 31 def graphql_get(request): 32 """ 33 Perform a GET request. 34 35 Args: 36 request (pyramid.Request): The current request. 37 Returns: 38 The GraphQL response to the request. 39 """ 40 context = {'session': request.session} 41 return serve_graphql_request( 42 request, schema, graphiql_enabled=config.get('graphiql_enabled'), 43 context_value=context) 44 45 46 class Query(graphene.ObjectType): 47 """Allow querying objects.""" 48 49 allReleases = graphene.List(Release) 50 getReleases = graphene.Field( 51 lambda: graphene.List(Release), name=graphene.String(), 52 id_prefix=graphene.String(), composed_by_bodhi=graphene.Boolean(), 53 state=graphene.String()) 54 55 getUpdates = graphene.Field( 56 lambda: graphene.List(Update), stable_karma=graphene.Int(), 57 stable_days=graphene.Int(), unstable_karma=graphene.Int(), 58 status=graphene.String(), request=graphene.String(), 59 pushed=graphene.Boolean(), critpath=graphene.Boolean(), 60 date_approved=graphene.String(), alias=graphene.String(), 61 user_id=graphene.Int()) 62 63 def resolve_allReleases(self, info): 64 """Answer Queries by fetching data from the Schema.""" 65 query = Release.get_query(info) # SQLAlchemy query 66 return query.all() 67 68 def resolve_getReleases(self, info, **args): 69 """Answer Release queries with a given argument.""" 70 query = Release.get_query(info) 71 72 id_prefix = args.get("id_prefix") 73 if id_prefix is not None: 74 query = query.filter(ReleaseModel.id_prefix == id_prefix) 75 76 name = args.get("name") 77 if name is not None: 78 query = query.filter(ReleaseModel.name == name) 79 80 composed_by_bodhi = args.get("composed_by_bodhi") 81 if composed_by_bodhi is not None: 82 query = query.filter(ReleaseModel.composed_by_bodhi == composed_by_bodhi) 83 84 state = args.get("state") 85 if state is not None: 86 query = query.filter(ReleaseModel.state == state) 87 88 return query.all() 89 90 def resolve_getUpdates(self, info, **args): 91 """Answer Release queries with a given argument.""" 92 query = Update.get_query(info) 93 94 stable_karma = args.get("stable_karma") 95 if stable_karma is not None: 96 query = query.filter(UpdateModel.stable_karma == stable_karma) 97 98 stable_days = args.get("stable_days") 99 if stable_days is not None: 100 query = query.filter(UpdateModel.stable_days == stable_days) 101 102 unstable_karma = args.get("unstable_karma") 103 if unstable_karma is not None: 104 query = query.filter(UpdateModel.unstable_karma == unstable_karma) 105 106 status = args.get("status") 107 if status is not None: 108 query = query.filter(UpdateModel.status == status) 109 110 request = args.get("request") 111 if request is not None: 112 query = query.filter(UpdateModel.request == request) 113 114 pushed = args.get("pushed") 115 if pushed is not None: 116 query = query.filter(UpdateModel.pushed == pushed) 117 118 critpath = args.get("critpath") 119 if critpath is not None: 120 query = query.filter(UpdateModel.critpath == critpath) 121 122 date_approved = args.get("date_approved") 123 if date_approved is not None: 124 query = query.filter(UpdateModel.date_approved == date_approved) 125 126 alias = args.get("alias") 127 if alias is not None: 128 query = query.filter(UpdateModel.alias == alias) 129 130 user_id = args.get("user_id") 131 if user_id is not None: 132 query = query.filter(UpdateModel.user_id == user_id) 133 134 return query.all() 135 136 137 schema = graphene.Schema(query=Query) 138 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/bodhi/server/services/graphql.py b/bodhi/server/services/graphql.py --- a/bodhi/server/services/graphql.py +++ b/bodhi/server/services/graphql.py @@ -58,7 +58,7 @@ status=graphene.String(), request=graphene.String(), pushed=graphene.Boolean(), critpath=graphene.Boolean(), date_approved=graphene.String(), alias=graphene.String(), - user_id=graphene.Int()) + user_id=graphene.Int(), release_name=graphene.String()) def resolve_allReleases(self, info): """Answer Queries by fetching data from the Schema.""" @@ -131,6 +131,10 @@ if user_id is not None: query = query.filter(UpdateModel.user_id == user_id) + release_name = args.get("release_name") + if release_name is not None: + query = query.join(UpdateModel.release).filter(ReleaseModel.name == release_name) + return query.all()
{"golden_diff": "diff --git a/bodhi/server/services/graphql.py b/bodhi/server/services/graphql.py\n--- a/bodhi/server/services/graphql.py\n+++ b/bodhi/server/services/graphql.py\n@@ -58,7 +58,7 @@\n status=graphene.String(), request=graphene.String(),\n pushed=graphene.Boolean(), critpath=graphene.Boolean(),\n date_approved=graphene.String(), alias=graphene.String(),\n- user_id=graphene.Int())\n+ user_id=graphene.Int(), release_name=graphene.String())\n \n def resolve_allReleases(self, info):\n \"\"\"Answer Queries by fetching data from the Schema.\"\"\"\n@@ -131,6 +131,10 @@\n if user_id is not None:\n query = query.filter(UpdateModel.user_id == user_id)\n \n+ release_name = args.get(\"release_name\")\n+ if release_name is not None:\n+ query = query.join(UpdateModel.release).filter(ReleaseModel.name == release_name)\n+\n return query.all()\n", "issue": "Add the possibility to query updates by releases in graphql\nWe currently have a getUpdates query in graphql that let us query updates using certain attributes, we should add the possibility to give a release name and get all the updates from a release.\r\n\r\nFor example ```query {getUpdates(releaseName: \"F33\") {alias}}```\r\n\r\nFor this we will most likely need to use a join query in the graphlq resolve function (https://github.com/fedora-infra/bodhi/blob/develop/bodhi/server/services/graphql.py#L132) to exploit the relationship between Updates and release.\r\n\r\nSome hints https://stackoverflow.com/questions/8561470/sqlalchemy-filtering-by-relationship-attribute\n", "before_files": [{"content": "# Copyright \u00a9 2020 Red Hat Inc., and others.\n#\n# This file is part of Bodhi.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\"\"\"Defines API endpoints related to GraphQL objects.\"\"\"\nimport graphene\nfrom cornice import Service\nfrom webob_graphql import serve_graphql_request\n\nfrom bodhi.server.config import config\nfrom bodhi.server.graphql_schemas import Release, ReleaseModel, Update, UpdateModel\n\ngraphql = Service(name='graphql', path='/graphql', description='graphql service')\n\n\[email protected]()\[email protected]()\ndef graphql_get(request):\n \"\"\"\n Perform a GET request.\n\n Args:\n request (pyramid.Request): The current request.\n Returns:\n The GraphQL response to the request.\n \"\"\"\n context = {'session': request.session}\n return serve_graphql_request(\n request, schema, graphiql_enabled=config.get('graphiql_enabled'),\n context_value=context)\n\n\nclass Query(graphene.ObjectType):\n \"\"\"Allow querying objects.\"\"\"\n\n allReleases = graphene.List(Release)\n getReleases = graphene.Field(\n lambda: graphene.List(Release), name=graphene.String(),\n id_prefix=graphene.String(), composed_by_bodhi=graphene.Boolean(),\n state=graphene.String())\n\n getUpdates = graphene.Field(\n lambda: graphene.List(Update), stable_karma=graphene.Int(),\n stable_days=graphene.Int(), unstable_karma=graphene.Int(),\n status=graphene.String(), request=graphene.String(),\n pushed=graphene.Boolean(), critpath=graphene.Boolean(),\n date_approved=graphene.String(), alias=graphene.String(),\n user_id=graphene.Int())\n\n def resolve_allReleases(self, info):\n \"\"\"Answer Queries by fetching data from the Schema.\"\"\"\n query = Release.get_query(info) # SQLAlchemy query\n return query.all()\n\n def resolve_getReleases(self, info, **args):\n \"\"\"Answer Release queries with a given argument.\"\"\"\n query = Release.get_query(info)\n\n id_prefix = args.get(\"id_prefix\")\n if id_prefix is not None:\n query = query.filter(ReleaseModel.id_prefix == id_prefix)\n\n name = args.get(\"name\")\n if name is not None:\n query = query.filter(ReleaseModel.name == name)\n\n composed_by_bodhi = args.get(\"composed_by_bodhi\")\n if composed_by_bodhi is not None:\n query = query.filter(ReleaseModel.composed_by_bodhi == composed_by_bodhi)\n\n state = args.get(\"state\")\n if state is not None:\n query = query.filter(ReleaseModel.state == state)\n\n return query.all()\n\n def resolve_getUpdates(self, info, **args):\n \"\"\"Answer Release queries with a given argument.\"\"\"\n query = Update.get_query(info)\n\n stable_karma = args.get(\"stable_karma\")\n if stable_karma is not None:\n query = query.filter(UpdateModel.stable_karma == stable_karma)\n\n stable_days = args.get(\"stable_days\")\n if stable_days is not None:\n query = query.filter(UpdateModel.stable_days == stable_days)\n\n unstable_karma = args.get(\"unstable_karma\")\n if unstable_karma is not None:\n query = query.filter(UpdateModel.unstable_karma == unstable_karma)\n\n status = args.get(\"status\")\n if status is not None:\n query = query.filter(UpdateModel.status == status)\n\n request = args.get(\"request\")\n if request is not None:\n query = query.filter(UpdateModel.request == request)\n\n pushed = args.get(\"pushed\")\n if pushed is not None:\n query = query.filter(UpdateModel.pushed == pushed)\n\n critpath = args.get(\"critpath\")\n if critpath is not None:\n query = query.filter(UpdateModel.critpath == critpath)\n\n date_approved = args.get(\"date_approved\")\n if date_approved is not None:\n query = query.filter(UpdateModel.date_approved == date_approved)\n\n alias = args.get(\"alias\")\n if alias is not None:\n query = query.filter(UpdateModel.alias == alias)\n\n user_id = args.get(\"user_id\")\n if user_id is not None:\n query = query.filter(UpdateModel.user_id == user_id)\n\n return query.all()\n\n\nschema = graphene.Schema(query=Query)\n", "path": "bodhi/server/services/graphql.py"}], "after_files": [{"content": "# Copyright \u00a9 2020 Red Hat Inc., and others.\n#\n# This file is part of Bodhi.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\"\"\"Defines API endpoints related to GraphQL objects.\"\"\"\nimport graphene\nfrom cornice import Service\nfrom webob_graphql import serve_graphql_request\n\nfrom bodhi.server.config import config\nfrom bodhi.server.graphql_schemas import Release, ReleaseModel, Update, UpdateModel\n\ngraphql = Service(name='graphql', path='/graphql', description='graphql service')\n\n\[email protected]()\[email protected]()\ndef graphql_get(request):\n \"\"\"\n Perform a GET request.\n\n Args:\n request (pyramid.Request): The current request.\n Returns:\n The GraphQL response to the request.\n \"\"\"\n context = {'session': request.session}\n return serve_graphql_request(\n request, schema, graphiql_enabled=config.get('graphiql_enabled'),\n context_value=context)\n\n\nclass Query(graphene.ObjectType):\n \"\"\"Allow querying objects.\"\"\"\n\n allReleases = graphene.List(Release)\n getReleases = graphene.Field(\n lambda: graphene.List(Release), name=graphene.String(),\n id_prefix=graphene.String(), composed_by_bodhi=graphene.Boolean(),\n state=graphene.String())\n\n getUpdates = graphene.Field(\n lambda: graphene.List(Update), stable_karma=graphene.Int(),\n stable_days=graphene.Int(), unstable_karma=graphene.Int(),\n status=graphene.String(), request=graphene.String(),\n pushed=graphene.Boolean(), critpath=graphene.Boolean(),\n date_approved=graphene.String(), alias=graphene.String(),\n user_id=graphene.Int(), release_name=graphene.String())\n\n def resolve_allReleases(self, info):\n \"\"\"Answer Queries by fetching data from the Schema.\"\"\"\n query = Release.get_query(info) # SQLAlchemy query\n return query.all()\n\n def resolve_getReleases(self, info, **args):\n \"\"\"Answer Release queries with a given argument.\"\"\"\n query = Release.get_query(info)\n\n id_prefix = args.get(\"id_prefix\")\n if id_prefix is not None:\n query = query.filter(ReleaseModel.id_prefix == id_prefix)\n\n name = args.get(\"name\")\n if name is not None:\n query = query.filter(ReleaseModel.name == name)\n\n composed_by_bodhi = args.get(\"composed_by_bodhi\")\n if composed_by_bodhi is not None:\n query = query.filter(ReleaseModel.composed_by_bodhi == composed_by_bodhi)\n\n state = args.get(\"state\")\n if state is not None:\n query = query.filter(ReleaseModel.state == state)\n\n return query.all()\n\n def resolve_getUpdates(self, info, **args):\n \"\"\"Answer Release queries with a given argument.\"\"\"\n query = Update.get_query(info)\n\n stable_karma = args.get(\"stable_karma\")\n if stable_karma is not None:\n query = query.filter(UpdateModel.stable_karma == stable_karma)\n\n stable_days = args.get(\"stable_days\")\n if stable_days is not None:\n query = query.filter(UpdateModel.stable_days == stable_days)\n\n unstable_karma = args.get(\"unstable_karma\")\n if unstable_karma is not None:\n query = query.filter(UpdateModel.unstable_karma == unstable_karma)\n\n status = args.get(\"status\")\n if status is not None:\n query = query.filter(UpdateModel.status == status)\n\n request = args.get(\"request\")\n if request is not None:\n query = query.filter(UpdateModel.request == request)\n\n pushed = args.get(\"pushed\")\n if pushed is not None:\n query = query.filter(UpdateModel.pushed == pushed)\n\n critpath = args.get(\"critpath\")\n if critpath is not None:\n query = query.filter(UpdateModel.critpath == critpath)\n\n date_approved = args.get(\"date_approved\")\n if date_approved is not None:\n query = query.filter(UpdateModel.date_approved == date_approved)\n\n alias = args.get(\"alias\")\n if alias is not None:\n query = query.filter(UpdateModel.alias == alias)\n\n user_id = args.get(\"user_id\")\n if user_id is not None:\n query = query.filter(UpdateModel.user_id == user_id)\n\n release_name = args.get(\"release_name\")\n if release_name is not None:\n query = query.join(UpdateModel.release).filter(ReleaseModel.name == release_name)\n\n return query.all()\n\n\nschema = graphene.Schema(query=Query)\n", "path": "bodhi/server/services/graphql.py"}]}
1,827
224
gh_patches_debug_6998
rasdani/github-patches
git_diff
microsoft__hi-ml-80
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Handle the "v" in version numbering Our code in `setup.py` will trigger with new tags. `setuptools.setup` will reject tags that are not release versions but we could do more to make that explicit by checking for the leading "v". Also when we tag releases as, say, "v0.1.1" the leading "v" is carried through `setuptools.setup` so it becomes part of the pip test download > Successfully installed pip-21.2.4 > Collecting hi-ml==v0.1.0 > Downloading hi_ml-0.1.0-py3-none-any.whl (25 kB) (from [here](https://github.com/microsoft/hi-ml/runs/3362573497?check_suite_focus=true#step:6:29)) This works, but it would be cleaner to submit the version number using the public version identifier format mandated in [PEP 440](https://www.python.org/dev/peps/pep-0440/#public-version-identifiers), i.e. without the leading "v" --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 # ------------------------------------------------------------------------------------------ 2 # Copyright (c) Microsoft Corporation. All rights reserved. 3 # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. 4 # ------------------------------------------------------------------------------------------ 5 6 """A setuptools based setup module. 7 8 See: 9 https://packaging.python.org/guides/distributing-packages-using-setuptools/ 10 """ 11 12 import os 13 from math import floor 14 import pathlib 15 from random import random 16 from setuptools import setup, find_packages # type: ignore 17 18 19 here = pathlib.Path(__file__).parent.resolve() 20 21 # Get the long description from the README file 22 long_description = (here / 'README.md').read_text(encoding='utf-8') 23 24 version = '' 25 26 # If running from a GitHub Action then a standard set of environment variables will be 27 # populated (https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables). 28 # In particular, GITHUB_REF is the branch or tag ref that triggered the workflow. 29 # If this was triggered by a tagged commit then GITHUB_REF will be: 'ref/tags/new_tag'. 30 # Extract this tag and use it as a version string 31 # See also: 32 # https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/ 33 # https://github.com/pypa/gh-action-pypi-publish 34 GITHUB_REF_TAG_COMMIT = 'refs/tags/' 35 36 github_ref = os.getenv('GITHUB_REF') 37 if github_ref and github_ref.startswith(GITHUB_REF_TAG_COMMIT): 38 version = github_ref[len(GITHUB_REF_TAG_COMMIT):] 39 40 # Otherwise, if running from a GitHub Action, but not a tagged commit then GITHUB_RUN_NUMBER will be populated. 41 # Use this as a post release number. For example if GITHUB_RUN_NUMBER = 124 then the version string will be 42 # '0.1.2.post124'. Although this is discouraged, see: 43 # https://www.python.org/dev/peps/pep-0440/#post-releases 44 # it is necessary here to avoid duplicate packages in Test.PyPI. 45 if not version: 46 # TODO: Replace this with more principled package version management for the package wheels built during local test 47 # runs, one which circumvents AzureML's apparent package caching: 48 build_number = os.getenv('GITHUB_RUN_NUMBER') 49 if build_number: 50 version = '0.1.0.post' + build_number 51 else: 52 default_random_version_number = floor(random() * 10_000_000_000) 53 version = f'0.1.0.post{str(default_random_version_number)}' 54 55 (here / 'latest_version.txt').write_text(version) 56 57 # Read run_requirements.txt to get install_requires 58 install_requires = (here / 'run_requirements.txt').read_text().split("\n") 59 # Remove any whitespace and blank lines 60 install_requires = [line.strip() for line in install_requires if line.strip()] 61 62 description = 'Microsoft Health Intelligence package to elevate and monitor scripts to an AzureML workspace' 63 64 setup( 65 name='hi-ml', 66 version=version, 67 description=description, 68 long_description=long_description, 69 long_description_content_type='text/markdown', 70 url='https://github.com/microsoft/hi-ml', 71 author="Microsoft Research Cambridge InnerEye Team ", 72 author_email="[email protected]", 73 classifiers=[ 74 'Development Status :: 3 - Alpha', 75 'Intended Audience :: Science/Research', 76 "Topic :: Scientific/Engineering :: Medical Science Apps.", 77 'License :: OSI Approved :: MIT License', 78 'Programming Language :: Python :: 3.7' 79 ], 80 keywords='InnerEye, HealthIntelligence, AzureML', 81 license='MIT License', 82 packages=find_packages(where="src"), 83 package_dir={"": "src"}, 84 include_package_data=True, 85 install_requires=install_requires, 86 scripts=['src/health/azure/run_tensorboard.py'] 87 ) 88 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ # See also: # https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/ # https://github.com/pypa/gh-action-pypi-publish -GITHUB_REF_TAG_COMMIT = 'refs/tags/' +GITHUB_REF_TAG_COMMIT = 'refs/tags/v' github_ref = os.getenv('GITHUB_REF') if github_ref and github_ref.startswith(GITHUB_REF_TAG_COMMIT):
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -31,7 +31,7 @@\n # See also:\n # https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/\n # https://github.com/pypa/gh-action-pypi-publish\n-GITHUB_REF_TAG_COMMIT = 'refs/tags/'\n+GITHUB_REF_TAG_COMMIT = 'refs/tags/v'\n \n github_ref = os.getenv('GITHUB_REF')\n if github_ref and github_ref.startswith(GITHUB_REF_TAG_COMMIT):\n", "issue": "Handle the \"v\" in version numbering \nOur code in `setup.py` will trigger with new tags. `setuptools.setup` will reject tags that are not release versions but we could do more to make that explicit by checking for the leading \"v\".\r\n\r\nAlso when we tag releases as, say, \"v0.1.1\" the leading \"v\" is carried through `setuptools.setup` so it becomes part of the pip test download\r\n\r\n> Successfully installed pip-21.2.4\r\n> Collecting hi-ml==v0.1.0\r\n> Downloading hi_ml-0.1.0-py3-none-any.whl (25 kB)\r\n\r\n(from [here](https://github.com/microsoft/hi-ml/runs/3362573497?check_suite_focus=true#step:6:29))\r\n\r\nThis works, but it would be cleaner to submit the version number using the public version identifier format mandated in [PEP 440](https://www.python.org/dev/peps/pep-0440/#public-version-identifiers), i.e. without the leading \"v\"\n", "before_files": [{"content": "# ------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# ------------------------------------------------------------------------------------------\n\n\"\"\"A setuptools based setup module.\n\nSee:\nhttps://packaging.python.org/guides/distributing-packages-using-setuptools/\n\"\"\"\n\nimport os\nfrom math import floor\nimport pathlib\nfrom random import random\nfrom setuptools import setup, find_packages # type: ignore\n\n\nhere = pathlib.Path(__file__).parent.resolve()\n\n# Get the long description from the README file\nlong_description = (here / 'README.md').read_text(encoding='utf-8')\n\nversion = ''\n\n# If running from a GitHub Action then a standard set of environment variables will be\n# populated (https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables).\n# In particular, GITHUB_REF is the branch or tag ref that triggered the workflow.\n# If this was triggered by a tagged commit then GITHUB_REF will be: 'ref/tags/new_tag'.\n# Extract this tag and use it as a version string\n# See also:\n# https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/\n# https://github.com/pypa/gh-action-pypi-publish\nGITHUB_REF_TAG_COMMIT = 'refs/tags/'\n\ngithub_ref = os.getenv('GITHUB_REF')\nif github_ref and github_ref.startswith(GITHUB_REF_TAG_COMMIT):\n version = github_ref[len(GITHUB_REF_TAG_COMMIT):]\n\n# Otherwise, if running from a GitHub Action, but not a tagged commit then GITHUB_RUN_NUMBER will be populated.\n# Use this as a post release number. For example if GITHUB_RUN_NUMBER = 124 then the version string will be\n# '0.1.2.post124'. Although this is discouraged, see:\n# https://www.python.org/dev/peps/pep-0440/#post-releases\n# it is necessary here to avoid duplicate packages in Test.PyPI.\nif not version:\n # TODO: Replace this with more principled package version management for the package wheels built during local test\n # runs, one which circumvents AzureML's apparent package caching:\n build_number = os.getenv('GITHUB_RUN_NUMBER')\n if build_number:\n version = '0.1.0.post' + build_number\n else:\n default_random_version_number = floor(random() * 10_000_000_000)\n version = f'0.1.0.post{str(default_random_version_number)}'\n\n(here / 'latest_version.txt').write_text(version)\n\n# Read run_requirements.txt to get install_requires\ninstall_requires = (here / 'run_requirements.txt').read_text().split(\"\\n\")\n# Remove any whitespace and blank lines\ninstall_requires = [line.strip() for line in install_requires if line.strip()]\n\ndescription = 'Microsoft Health Intelligence package to elevate and monitor scripts to an AzureML workspace'\n\nsetup(\n name='hi-ml',\n version=version,\n description=description,\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/microsoft/hi-ml',\n author=\"Microsoft Research Cambridge InnerEye Team \",\n author_email=\"[email protected]\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n \"Topic :: Scientific/Engineering :: Medical Science Apps.\",\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.7'\n ],\n keywords='InnerEye, HealthIntelligence, AzureML',\n license='MIT License',\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n include_package_data=True,\n install_requires=install_requires,\n scripts=['src/health/azure/run_tensorboard.py']\n)\n", "path": "setup.py"}], "after_files": [{"content": "# ------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.\n# ------------------------------------------------------------------------------------------\n\n\"\"\"A setuptools based setup module.\n\nSee:\nhttps://packaging.python.org/guides/distributing-packages-using-setuptools/\n\"\"\"\n\nimport os\nfrom math import floor\nimport pathlib\nfrom random import random\nfrom setuptools import setup, find_packages # type: ignore\n\n\nhere = pathlib.Path(__file__).parent.resolve()\n\n# Get the long description from the README file\nlong_description = (here / 'README.md').read_text(encoding='utf-8')\n\nversion = ''\n\n# If running from a GitHub Action then a standard set of environment variables will be\n# populated (https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables).\n# In particular, GITHUB_REF is the branch or tag ref that triggered the workflow.\n# If this was triggered by a tagged commit then GITHUB_REF will be: 'ref/tags/new_tag'.\n# Extract this tag and use it as a version string\n# See also:\n# https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/\n# https://github.com/pypa/gh-action-pypi-publish\nGITHUB_REF_TAG_COMMIT = 'refs/tags/v'\n\ngithub_ref = os.getenv('GITHUB_REF')\nif github_ref and github_ref.startswith(GITHUB_REF_TAG_COMMIT):\n version = github_ref[len(GITHUB_REF_TAG_COMMIT):]\n\n# Otherwise, if running from a GitHub Action, but not a tagged commit then GITHUB_RUN_NUMBER will be populated.\n# Use this as a post release number. For example if GITHUB_RUN_NUMBER = 124 then the version string will be\n# '0.1.2.post124'. Although this is discouraged, see:\n# https://www.python.org/dev/peps/pep-0440/#post-releases\n# it is necessary here to avoid duplicate packages in Test.PyPI.\nif not version:\n # TODO: Replace this with more principled package version management for the package wheels built during local test\n # runs, one which circumvents AzureML's apparent package caching:\n build_number = os.getenv('GITHUB_RUN_NUMBER')\n if build_number:\n version = '0.1.0.post' + build_number\n else:\n default_random_version_number = floor(random() * 10_000_000_000)\n version = f'0.1.0.post{str(default_random_version_number)}'\n\n(here / 'latest_version.txt').write_text(version)\n\n# Read run_requirements.txt to get install_requires\ninstall_requires = (here / 'run_requirements.txt').read_text().split(\"\\n\")\n# Remove any whitespace and blank lines\ninstall_requires = [line.strip() for line in install_requires if line.strip()]\n\ndescription = 'Microsoft Health Intelligence package to elevate and monitor scripts to an AzureML workspace'\n\nsetup(\n name='hi-ml',\n version=version,\n description=description,\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/microsoft/hi-ml',\n author=\"Microsoft Research Cambridge InnerEye Team \",\n author_email=\"[email protected]\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n \"Topic :: Scientific/Engineering :: Medical Science Apps.\",\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.7'\n ],\n keywords='InnerEye, HealthIntelligence, AzureML',\n license='MIT License',\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n include_package_data=True,\n install_requires=install_requires,\n scripts=['src/health/azure/run_tensorboard.py']\n)\n", "path": "setup.py"}]}
1,509
125
gh_patches_debug_42542
rasdani/github-patches
git_diff
networkx__networkx-2532
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- maximal_independent_set does not work for DiGraph Currently [maximal_independent_set](https://github.com/networkx/networkx/blob/d7d906e1d16ef331da0bc1d149953e7532155acc/networkx/algorithms/mis.py#L70) returns the wrong results for a `DiGraph` because it uses the `G.neighbors` method which returns only the successor nodes in a `DiGraph`. I believe the [all_neighbors](https://github.com/networkx/networkx/blob/13b373bf6938c077d1e61adc60a48cb910a75755/networkx/classes/function.py#L540) function should be used instead to make `maximal_independent_set` work correctly for both graph types. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `networkx/algorithms/mis.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 # $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $ 3 """ 4 Algorithm to find a maximal (not maximum) independent set. 5 6 """ 7 # Leo Lopes <[email protected]> 8 # Aric Hagberg <[email protected]> 9 # Dan Schult <[email protected]> 10 # Pieter Swart <[email protected]> 11 # All rights reserved. 12 # BSD license. 13 14 __author__ = "\n".join(["Leo Lopes <[email protected]>", 15 "Loïc Séguin-C. <[email protected]>"]) 16 17 __all__ = ['maximal_independent_set'] 18 19 import random 20 import networkx as nx 21 22 def maximal_independent_set(G, nodes=None): 23 """Return a random maximal independent set guaranteed to contain 24 a given set of nodes. 25 26 An independent set is a set of nodes such that the subgraph 27 of G induced by these nodes contains no edges. A maximal 28 independent set is an independent set such that it is not possible 29 to add a new node and still get an independent set. 30 31 Parameters 32 ---------- 33 G : NetworkX graph 34 35 nodes : list or iterable 36 Nodes that must be part of the independent set. This set of nodes 37 must be independent. 38 39 Returns 40 ------- 41 indep_nodes : list 42 List of nodes that are part of a maximal independent set. 43 44 Raises 45 ------ 46 NetworkXUnfeasible 47 If the nodes in the provided list are not part of the graph or 48 do not form an independent set, an exception is raised. 49 50 Examples 51 -------- 52 >>> G = nx.path_graph(5) 53 >>> nx.maximal_independent_set(G) # doctest: +SKIP 54 [4, 0, 2] 55 >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP 56 [1, 3] 57 58 Notes 59 ----- 60 This algorithm does not solve the maximum independent set problem. 61 62 """ 63 if not nodes: 64 nodes = set([random.choice(list(G))]) 65 else: 66 nodes = set(nodes) 67 if not nodes.issubset(G): 68 raise nx.NetworkXUnfeasible( 69 "%s is not a subset of the nodes of G" % nodes) 70 neighbors = set.union(*[set(G.neighbors(v)) for v in nodes]) 71 if set.intersection(neighbors, nodes): 72 raise nx.NetworkXUnfeasible( 73 "%s is not an independent set of G" % nodes) 74 indep_nodes = list(nodes) 75 available_nodes = set(G.nodes()).difference(neighbors.union(nodes)) 76 while available_nodes: 77 node = random.choice(list(available_nodes)) 78 indep_nodes.append(node) 79 available_nodes.difference_update(list(G.neighbors(node)) + [node]) 80 return indep_nodes 81 82 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/networkx/algorithms/mis.py b/networkx/algorithms/mis.py --- a/networkx/algorithms/mis.py +++ b/networkx/algorithms/mis.py @@ -1,24 +1,26 @@ # -*- coding: utf-8 -*- # $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $ -""" -Algorithm to find a maximal (not maximum) independent set. - -""" # Leo Lopes <[email protected]> # Aric Hagberg <[email protected]> # Dan Schult <[email protected]> # Pieter Swart <[email protected]> # All rights reserved. # BSD license. +# +# Authors: Leo Lopes <[email protected]> +# Loïc Séguin-C. <[email protected]> +""" +Algorithm to find a maximal (not maximum) independent set. -__author__ = "\n".join(["Leo Lopes <[email protected]>", - "Loïc Séguin-C. <[email protected]>"]) +""" +import random +import networkx as nx +from networkx.utils import not_implemented_for __all__ = ['maximal_independent_set'] -import random -import networkx as nx +@not_implemented_for('directed') def maximal_independent_set(G, nodes=None): """Return a random maximal independent set guaranteed to contain a given set of nodes. @@ -27,10 +29,10 @@ of G induced by these nodes contains no edges. A maximal independent set is an independent set such that it is not possible to add a new node and still get an independent set. - + Parameters ---------- - G : NetworkX graph + G : NetworkX graph nodes : list or iterable Nodes that must be part of the independent set. This set of nodes @@ -38,7 +40,7 @@ Returns ------- - indep_nodes : list + indep_nodes : list List of nodes that are part of a maximal independent set. Raises @@ -47,6 +49,9 @@ If the nodes in the provided list are not part of the graph or do not form an independent set, an exception is raised. + NetworkXNotImplemented + If `G` is directed. + Examples -------- >>> G = nx.path_graph(5) @@ -54,7 +59,7 @@ [4, 0, 2] >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP [1, 3] - + Notes ----- This algorithm does not solve the maximum independent set problem. @@ -67,7 +72,7 @@ if not nodes.issubset(G): raise nx.NetworkXUnfeasible( "%s is not a subset of the nodes of G" % nodes) - neighbors = set.union(*[set(G.neighbors(v)) for v in nodes]) + neighbors = set.union(*[set(G.adj[v]) for v in nodes]) if set.intersection(neighbors, nodes): raise nx.NetworkXUnfeasible( "%s is not an independent set of G" % nodes) @@ -76,6 +81,5 @@ while available_nodes: node = random.choice(list(available_nodes)) indep_nodes.append(node) - available_nodes.difference_update(list(G.neighbors(node)) + [node]) + available_nodes.difference_update(list(G.adj[node]) + [node]) return indep_nodes -
{"golden_diff": "diff --git a/networkx/algorithms/mis.py b/networkx/algorithms/mis.py\n--- a/networkx/algorithms/mis.py\n+++ b/networkx/algorithms/mis.py\n@@ -1,24 +1,26 @@\n # -*- coding: utf-8 -*-\n # $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $\n-\"\"\"\n-Algorithm to find a maximal (not maximum) independent set.\n-\n-\"\"\"\n # Leo Lopes <[email protected]>\n # Aric Hagberg <[email protected]>\n # Dan Schult <[email protected]>\n # Pieter Swart <[email protected]>\n # All rights reserved.\n # BSD license.\n+#\n+# Authors: Leo Lopes <[email protected]>\n+# Lo\u00efc S\u00e9guin-C. <[email protected]>\n+\"\"\"\n+Algorithm to find a maximal (not maximum) independent set.\n \n-__author__ = \"\\n\".join([\"Leo Lopes <[email protected]>\",\n- \"Lo\u00efc S\u00e9guin-C. <[email protected]>\"])\n+\"\"\"\n+import random\n+import networkx as nx\n+from networkx.utils import not_implemented_for\n \n __all__ = ['maximal_independent_set']\n \n-import random\n-import networkx as nx\n \n+@not_implemented_for('directed')\n def maximal_independent_set(G, nodes=None):\n \"\"\"Return a random maximal independent set guaranteed to contain\n a given set of nodes.\n@@ -27,10 +29,10 @@\n of G induced by these nodes contains no edges. A maximal\n independent set is an independent set such that it is not possible\n to add a new node and still get an independent set.\n- \n+\n Parameters\n ----------\n- G : NetworkX graph \n+ G : NetworkX graph\n \n nodes : list or iterable\n Nodes that must be part of the independent set. This set of nodes\n@@ -38,7 +40,7 @@\n \n Returns\n -------\n- indep_nodes : list \n+ indep_nodes : list\n List of nodes that are part of a maximal independent set.\n \n Raises\n@@ -47,6 +49,9 @@\n If the nodes in the provided list are not part of the graph or\n do not form an independent set, an exception is raised.\n \n+ NetworkXNotImplemented\n+ If `G` is directed.\n+\n Examples\n --------\n >>> G = nx.path_graph(5)\n@@ -54,7 +59,7 @@\n [4, 0, 2]\n >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP\n [1, 3]\n- \n+\n Notes\n -----\n This algorithm does not solve the maximum independent set problem.\n@@ -67,7 +72,7 @@\n if not nodes.issubset(G):\n raise nx.NetworkXUnfeasible(\n \"%s is not a subset of the nodes of G\" % nodes)\n- neighbors = set.union(*[set(G.neighbors(v)) for v in nodes])\n+ neighbors = set.union(*[set(G.adj[v]) for v in nodes])\n if set.intersection(neighbors, nodes):\n raise nx.NetworkXUnfeasible(\n \"%s is not an independent set of G\" % nodes)\n@@ -76,6 +81,5 @@\n while available_nodes:\n node = random.choice(list(available_nodes))\n indep_nodes.append(node)\n- available_nodes.difference_update(list(G.neighbors(node)) + [node])\n+ available_nodes.difference_update(list(G.adj[node]) + [node])\n return indep_nodes\n-\n", "issue": "maximal_independent_set does not work for DiGraph\nCurrently [maximal_independent_set](https://github.com/networkx/networkx/blob/d7d906e1d16ef331da0bc1d149953e7532155acc/networkx/algorithms/mis.py#L70) returns the wrong results for a `DiGraph` because it uses the `G.neighbors` method which returns only the successor nodes in a `DiGraph`. I believe the [all_neighbors](https://github.com/networkx/networkx/blob/13b373bf6938c077d1e61adc60a48cb910a75755/networkx/classes/function.py#L540) function should be used instead to make `maximal_independent_set` work correctly for both graph types.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $\n\"\"\"\nAlgorithm to find a maximal (not maximum) independent set.\n\n\"\"\"\n# Leo Lopes <[email protected]>\n# Aric Hagberg <[email protected]>\n# Dan Schult <[email protected]>\n# Pieter Swart <[email protected]>\n# All rights reserved.\n# BSD license.\n\n__author__ = \"\\n\".join([\"Leo Lopes <[email protected]>\",\n \"Lo\u00efc S\u00e9guin-C. <[email protected]>\"])\n\n__all__ = ['maximal_independent_set']\n\nimport random\nimport networkx as nx\n\ndef maximal_independent_set(G, nodes=None):\n \"\"\"Return a random maximal independent set guaranteed to contain\n a given set of nodes.\n\n An independent set is a set of nodes such that the subgraph\n of G induced by these nodes contains no edges. A maximal\n independent set is an independent set such that it is not possible\n to add a new node and still get an independent set.\n \n Parameters\n ----------\n G : NetworkX graph \n\n nodes : list or iterable\n Nodes that must be part of the independent set. This set of nodes\n must be independent.\n\n Returns\n -------\n indep_nodes : list \n List of nodes that are part of a maximal independent set.\n\n Raises\n ------\n NetworkXUnfeasible\n If the nodes in the provided list are not part of the graph or\n do not form an independent set, an exception is raised.\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> nx.maximal_independent_set(G) # doctest: +SKIP\n [4, 0, 2]\n >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP\n [1, 3]\n \n Notes\n -----\n This algorithm does not solve the maximum independent set problem.\n\n \"\"\"\n if not nodes:\n nodes = set([random.choice(list(G))])\n else:\n nodes = set(nodes)\n if not nodes.issubset(G):\n raise nx.NetworkXUnfeasible(\n \"%s is not a subset of the nodes of G\" % nodes)\n neighbors = set.union(*[set(G.neighbors(v)) for v in nodes])\n if set.intersection(neighbors, nodes):\n raise nx.NetworkXUnfeasible(\n \"%s is not an independent set of G\" % nodes)\n indep_nodes = list(nodes)\n available_nodes = set(G.nodes()).difference(neighbors.union(nodes))\n while available_nodes:\n node = random.choice(list(available_nodes))\n indep_nodes.append(node)\n available_nodes.difference_update(list(G.neighbors(node)) + [node])\n return indep_nodes\n\n", "path": "networkx/algorithms/mis.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# $Id: maximalIndependentSet.py 576 2011-03-01 05:50:34Z lleeoo $\n# Leo Lopes <[email protected]>\n# Aric Hagberg <[email protected]>\n# Dan Schult <[email protected]>\n# Pieter Swart <[email protected]>\n# All rights reserved.\n# BSD license.\n#\n# Authors: Leo Lopes <[email protected]>\n# Lo\u00efc S\u00e9guin-C. <[email protected]>\n\"\"\"\nAlgorithm to find a maximal (not maximum) independent set.\n\n\"\"\"\nimport random\nimport networkx as nx\nfrom networkx.utils import not_implemented_for\n\n__all__ = ['maximal_independent_set']\n\n\n@not_implemented_for('directed')\ndef maximal_independent_set(G, nodes=None):\n \"\"\"Return a random maximal independent set guaranteed to contain\n a given set of nodes.\n\n An independent set is a set of nodes such that the subgraph\n of G induced by these nodes contains no edges. A maximal\n independent set is an independent set such that it is not possible\n to add a new node and still get an independent set.\n\n Parameters\n ----------\n G : NetworkX graph\n\n nodes : list or iterable\n Nodes that must be part of the independent set. This set of nodes\n must be independent.\n\n Returns\n -------\n indep_nodes : list\n List of nodes that are part of a maximal independent set.\n\n Raises\n ------\n NetworkXUnfeasible\n If the nodes in the provided list are not part of the graph or\n do not form an independent set, an exception is raised.\n\n NetworkXNotImplemented\n If `G` is directed.\n\n Examples\n --------\n >>> G = nx.path_graph(5)\n >>> nx.maximal_independent_set(G) # doctest: +SKIP\n [4, 0, 2]\n >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP\n [1, 3]\n\n Notes\n -----\n This algorithm does not solve the maximum independent set problem.\n\n \"\"\"\n if not nodes:\n nodes = set([random.choice(list(G))])\n else:\n nodes = set(nodes)\n if not nodes.issubset(G):\n raise nx.NetworkXUnfeasible(\n \"%s is not a subset of the nodes of G\" % nodes)\n neighbors = set.union(*[set(G.adj[v]) for v in nodes])\n if set.intersection(neighbors, nodes):\n raise nx.NetworkXUnfeasible(\n \"%s is not an independent set of G\" % nodes)\n indep_nodes = list(nodes)\n available_nodes = set(G.nodes()).difference(neighbors.union(nodes))\n while available_nodes:\n node = random.choice(list(available_nodes))\n indep_nodes.append(node)\n available_nodes.difference_update(list(G.adj[node]) + [node])\n return indep_nodes\n", "path": "networkx/algorithms/mis.py"}]}
1,265
846
gh_patches_debug_27752
rasdani/github-patches
git_diff
pyload__pyload-52
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- FourChanOrg don't work When i try to download a thread (e.g. http://boards.4chan.org/wg/res/5176429) nothing happens, only BasePlugin will be used, --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `module/plugins/crypter/FourChanOrg.py` Content: ``` 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import re 5 6 from module.plugins.Crypter import Crypter 7 8 class FourChanOrg(Crypter): 9 __name__ = "FourChanOrg" 10 __type__ = "container" 11 __pattern__ = r"http://(www\.)?(img\.)?(zip\.)?4chan.org/\w+/(res/|imgboard\.html)" 12 __version__ = "0.1" 13 __description__ = """4chan.org Thread Download Plugin""" 14 __author_name__ = ("Spoob") 15 __author_mail__ = ("[email protected]") 16 17 def __init__(self, parent): 18 Crypter.__init__(self, parent) 19 self.parent = parent 20 self.html = None 21 22 def file_exists(self): 23 """ returns True or False 24 """ 25 return True 26 27 def proceed(self, url, location): 28 url = self.parent.url 29 html = self.req.load(url) 30 link_pattern = "" 31 temp_links = [] 32 if "imagebord.html" in url: 33 link_pattern = '[<a href="(res/\d*\.html)">Reply</a>]' 34 temp_links = re.findall(link_pattern, html) 35 for link in re.findall(link_pattern, html): 36 temp_links.append(link) 37 else: 38 temp_links = re.findall('File : <a href="(http://(?:img\.)?(?:zip\.)?4chan\.org/\w{,3}/src/\d*\..{3})"', html) 39 self.links = temp_links 40 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/module/plugins/crypter/FourChanOrg.py b/module/plugins/crypter/FourChanOrg.py --- a/module/plugins/crypter/FourChanOrg.py +++ b/module/plugins/crypter/FourChanOrg.py @@ -6,34 +6,20 @@ from module.plugins.Crypter import Crypter class FourChanOrg(Crypter): + # Based on 4chandl by Roland Beermann + # https://gist.github.com/enkore/3492599 __name__ = "FourChanOrg" __type__ = "container" - __pattern__ = r"http://(www\.)?(img\.)?(zip\.)?4chan.org/\w+/(res/|imgboard\.html)" - __version__ = "0.1" - __description__ = """4chan.org Thread Download Plugin""" - __author_name__ = ("Spoob") - __author_mail__ = ("[email protected]") + __version__ = "0.3" + __pattern__ = r"http://boards\.4chan.org/\w+/res/(\d+)" + __description__ = "Downloader for entire 4chan threads" - def __init__(self, parent): - Crypter.__init__(self, parent) - self.parent = parent - self.html = None + def decrypt(self, pyfile): + pagehtml = self.load(pyfile.url) - def file_exists(self): - """ returns True or False - """ - return True + images = set(re.findall(r'(images\.4chan\.org/[^/]*/src/[^"<]*)', pagehtml)) + urls = [] + for image in images: + urls.append("http://" + image) - def proceed(self, url, location): - url = self.parent.url - html = self.req.load(url) - link_pattern = "" - temp_links = [] - if "imagebord.html" in url: - link_pattern = '[<a href="(res/\d*\.html)">Reply</a>]' - temp_links = re.findall(link_pattern, html) - for link in re.findall(link_pattern, html): - temp_links.append(link) - else: - temp_links = re.findall('File : <a href="(http://(?:img\.)?(?:zip\.)?4chan\.org/\w{,3}/src/\d*\..{3})"', html) - self.links = temp_links + self.core.files.addLinks(urls, self.pyfile.package().id)
{"golden_diff": "diff --git a/module/plugins/crypter/FourChanOrg.py b/module/plugins/crypter/FourChanOrg.py\n--- a/module/plugins/crypter/FourChanOrg.py\n+++ b/module/plugins/crypter/FourChanOrg.py\n@@ -6,34 +6,20 @@\n from module.plugins.Crypter import Crypter\n \n class FourChanOrg(Crypter):\n+ # Based on 4chandl by Roland Beermann\n+ # https://gist.github.com/enkore/3492599\n __name__ = \"FourChanOrg\"\n __type__ = \"container\"\n- __pattern__ = r\"http://(www\\.)?(img\\.)?(zip\\.)?4chan.org/\\w+/(res/|imgboard\\.html)\"\n- __version__ = \"0.1\"\n- __description__ = \"\"\"4chan.org Thread Download Plugin\"\"\"\n- __author_name__ = (\"Spoob\")\n- __author_mail__ = (\"[email protected]\")\n+ __version__ = \"0.3\"\n+ __pattern__ = r\"http://boards\\.4chan.org/\\w+/res/(\\d+)\"\n+ __description__ = \"Downloader for entire 4chan threads\"\n \n- def __init__(self, parent):\n- Crypter.__init__(self, parent)\n- self.parent = parent\n- self.html = None\n+ def decrypt(self, pyfile):\n+ pagehtml = self.load(pyfile.url)\n \n- def file_exists(self):\n- \"\"\" returns True or False\n- \"\"\"\n- return True\n+ images = set(re.findall(r'(images\\.4chan\\.org/[^/]*/src/[^\"<]*)', pagehtml))\n+ urls = []\n+ for image in images:\n+ urls.append(\"http://\" + image)\n \n- def proceed(self, url, location):\n- url = self.parent.url\n- html = self.req.load(url)\n- link_pattern = \"\"\n- temp_links = []\n- if \"imagebord.html\" in url:\n- link_pattern = '[<a href=\"(res/\\d*\\.html)\">Reply</a>]'\n- temp_links = re.findall(link_pattern, html)\n- for link in re.findall(link_pattern, html):\n- temp_links.append(link)\n- else:\n- temp_links = re.findall('File : <a href=\"(http://(?:img\\.)?(?:zip\\.)?4chan\\.org/\\w{,3}/src/\\d*\\..{3})\"', html)\n- self.links = temp_links\n+ self.core.files.addLinks(urls, self.pyfile.package().id)\n", "issue": "FourChanOrg don't work\nWhen i try to download a thread (e.g. http://boards.4chan.org/wg/res/5176429) nothing happens, only BasePlugin will be used,\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\n\nfrom module.plugins.Crypter import Crypter\n\nclass FourChanOrg(Crypter):\n __name__ = \"FourChanOrg\"\n __type__ = \"container\"\n __pattern__ = r\"http://(www\\.)?(img\\.)?(zip\\.)?4chan.org/\\w+/(res/|imgboard\\.html)\"\n __version__ = \"0.1\"\n __description__ = \"\"\"4chan.org Thread Download Plugin\"\"\"\n __author_name__ = (\"Spoob\")\n __author_mail__ = (\"[email protected]\")\n\n def __init__(self, parent):\n Crypter.__init__(self, parent)\n self.parent = parent\n self.html = None\n\n def file_exists(self):\n \"\"\" returns True or False\n \"\"\"\n return True\n\n def proceed(self, url, location):\n url = self.parent.url\n html = self.req.load(url)\n link_pattern = \"\"\n temp_links = []\n if \"imagebord.html\" in url:\n link_pattern = '[<a href=\"(res/\\d*\\.html)\">Reply</a>]'\n temp_links = re.findall(link_pattern, html)\n for link in re.findall(link_pattern, html):\n temp_links.append(link)\n else:\n temp_links = re.findall('File : <a href=\"(http://(?:img\\.)?(?:zip\\.)?4chan\\.org/\\w{,3}/src/\\d*\\..{3})\"', html)\n self.links = temp_links\n", "path": "module/plugins/crypter/FourChanOrg.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\n\nfrom module.plugins.Crypter import Crypter\n\nclass FourChanOrg(Crypter):\n # Based on 4chandl by Roland Beermann\n # https://gist.github.com/enkore/3492599\n __name__ = \"FourChanOrg\"\n __type__ = \"container\"\n __version__ = \"0.3\"\n __pattern__ = r\"http://boards\\.4chan.org/\\w+/res/(\\d+)\"\n __description__ = \"Downloader for entire 4chan threads\"\n\n def decrypt(self, pyfile):\n pagehtml = self.load(pyfile.url)\n\n images = set(re.findall(r'(images\\.4chan\\.org/[^/]*/src/[^\"<]*)', pagehtml))\n urls = []\n for image in images:\n urls.append(\"http://\" + image)\n\n self.core.files.addLinks(urls, self.pyfile.package().id)\n", "path": "module/plugins/crypter/FourChanOrg.py"}]}
725
582
gh_patches_debug_11575
rasdani/github-patches
git_diff
mindsdb__lightwood-968
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Improve runtime of `LightGBMArray` for long-horizon forecasting Two main approaches: - Disable optuna hyperparam search past some threshold. - Opt for a recursive strategy instead of direct (i.e. same regressor trained for all timesteps v/s one for each step). --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `lightwood/mixer/lightgbm_array.py` Content: ``` 1 from copy import deepcopy 2 from typing import Dict, List, Union 3 4 import numpy as np 5 import pandas as pd 6 7 from lightwood.helpers.log import log 8 from lightwood.mixer.helpers.ts import _apply_stl_on_training, _stl_transform, _stl_inverse_transform 9 from lightwood.encoder.base import BaseEncoder 10 from lightwood.mixer.base import BaseMixer 11 from lightwood.mixer.lightgbm import LightGBM 12 from lightwood.api.types import PredictionArguments, TimeseriesSettings 13 from lightwood.data.encoded_ds import EncodedDs, ConcatedEncodedDs 14 15 16 class LightGBMArray(BaseMixer): 17 """LightGBM-based model, intended for usage in time series tasks.""" 18 models: List[LightGBM] 19 submodel_stop_after: float 20 target: str 21 supports_proba: bool 22 ts_analysis: Dict 23 tss: TimeseriesSettings 24 25 def __init__( 26 self, 27 stop_after: float, 28 target: str, 29 dtype_dict: Dict[str, str], 30 input_cols: List[str], 31 fit_on_dev: bool, 32 target_encoder: BaseEncoder, 33 ts_analysis: Dict[str, object], 34 use_stl: bool, 35 tss: TimeseriesSettings 36 ): 37 super().__init__(stop_after) 38 self.tss = tss 39 self.horizon = tss.horizon 40 self.submodel_stop_after = stop_after / self.horizon 41 self.target = target 42 self.offset_pred_cols = [f'{self.target}_timestep_{i}' for i in range(1, self.horizon)] 43 if set(input_cols) != {self.tss.order_by}: 44 input_cols.remove(self.tss.order_by) 45 for col in self.offset_pred_cols: 46 dtype_dict[col] = dtype_dict[self.target] 47 self.models = [LightGBM(self.submodel_stop_after, 48 target_col, 49 dtype_dict, 50 input_cols, 51 False, # fit_on_dev, 52 True, # use_optuna 53 target_encoder) 54 for _, target_col in zip(range(self.horizon), [target] + self.offset_pred_cols)] 55 self.ts_analysis = ts_analysis 56 self.supports_proba = False 57 self.use_stl = False 58 self.stable = True 59 60 def _fit(self, train_data: EncodedDs, dev_data: EncodedDs, submodel_method='fit') -> None: 61 original_train = deepcopy(train_data.data_frame) 62 original_dev = deepcopy(dev_data.data_frame) 63 64 if self.use_stl and self.ts_analysis.get('stl_transforms', False): 65 _apply_stl_on_training(train_data, dev_data, self.target, self.tss, self.ts_analysis) 66 67 for timestep in range(self.horizon): 68 getattr(self.models[timestep], submodel_method)(train_data, dev_data) 69 70 # restore dfs 71 train_data.data_frame = original_train 72 dev_data.data_frame = original_dev 73 74 def fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None: 75 log.info('Started fitting LGBM models for array prediction') 76 self._fit(train_data, dev_data, submodel_method='fit') 77 78 def partial_fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None: 79 log.info('Updating array of LGBM models...') 80 self._fit(train_data, dev_data, submodel_method='partial_fit') 81 82 def __call__(self, ds: Union[EncodedDs, ConcatedEncodedDs], 83 args: PredictionArguments = PredictionArguments()) -> pd.DataFrame: 84 if args.predict_proba: 85 log.warning('This model does not output probability estimates') 86 87 original_df = deepcopy(ds.data_frame) 88 length = sum(ds.encoded_ds_lenghts) if isinstance(ds, ConcatedEncodedDs) else len(ds) 89 ydf = pd.DataFrame(0, # zero-filled 90 index=np.arange(length), 91 columns=[f'prediction_{i}' for i in range(self.horizon)]) 92 93 if self.use_stl and self.ts_analysis.get('stl_transforms', False): 94 ds.data_frame = _stl_transform(ydf, ds, self.target, self.tss, self.ts_analysis) 95 96 for timestep in range(self.horizon): 97 ydf[f'prediction_{timestep}'] = self.models[timestep](ds, args)['prediction'].values 98 99 if self.use_stl and self.ts_analysis.get('stl_transforms', False): 100 ydf = _stl_inverse_transform(ydf, ds, self.tss, self.ts_analysis) 101 102 if self.models[0].positive_domain: 103 ydf = ydf.clip(0) 104 105 ydf['prediction'] = ydf.values.tolist() 106 ds.data_frame = original_df 107 return ydf[['prediction']] 108 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/lightwood/mixer/lightgbm_array.py b/lightwood/mixer/lightgbm_array.py --- a/lightwood/mixer/lightgbm_array.py +++ b/lightwood/mixer/lightgbm_array.py @@ -49,7 +49,7 @@ dtype_dict, input_cols, False, # fit_on_dev, - True, # use_optuna + True if tss.horizon < 10 else False, # use_optuna target_encoder) for _, target_col in zip(range(self.horizon), [target] + self.offset_pred_cols)] self.ts_analysis = ts_analysis
{"golden_diff": "diff --git a/lightwood/mixer/lightgbm_array.py b/lightwood/mixer/lightgbm_array.py\n--- a/lightwood/mixer/lightgbm_array.py\n+++ b/lightwood/mixer/lightgbm_array.py\n@@ -49,7 +49,7 @@\n dtype_dict,\n input_cols,\n False, # fit_on_dev,\n- True, # use_optuna\n+ True if tss.horizon < 10 else False, # use_optuna\n target_encoder)\n for _, target_col in zip(range(self.horizon), [target] + self.offset_pred_cols)]\n self.ts_analysis = ts_analysis\n", "issue": "Improve runtime of `LightGBMArray` for long-horizon forecasting\nTwo main approaches:\r\n\r\n- Disable optuna hyperparam search past some threshold.\r\n- Opt for a recursive strategy instead of direct (i.e. same regressor trained for all timesteps v/s one for each step).\n", "before_files": [{"content": "from copy import deepcopy\nfrom typing import Dict, List, Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom lightwood.helpers.log import log\nfrom lightwood.mixer.helpers.ts import _apply_stl_on_training, _stl_transform, _stl_inverse_transform\nfrom lightwood.encoder.base import BaseEncoder\nfrom lightwood.mixer.base import BaseMixer\nfrom lightwood.mixer.lightgbm import LightGBM\nfrom lightwood.api.types import PredictionArguments, TimeseriesSettings\nfrom lightwood.data.encoded_ds import EncodedDs, ConcatedEncodedDs\n\n\nclass LightGBMArray(BaseMixer):\n \"\"\"LightGBM-based model, intended for usage in time series tasks.\"\"\"\n models: List[LightGBM]\n submodel_stop_after: float\n target: str\n supports_proba: bool\n ts_analysis: Dict\n tss: TimeseriesSettings\n\n def __init__(\n self,\n stop_after: float,\n target: str,\n dtype_dict: Dict[str, str],\n input_cols: List[str],\n fit_on_dev: bool,\n target_encoder: BaseEncoder,\n ts_analysis: Dict[str, object],\n use_stl: bool,\n tss: TimeseriesSettings\n ):\n super().__init__(stop_after)\n self.tss = tss\n self.horizon = tss.horizon\n self.submodel_stop_after = stop_after / self.horizon\n self.target = target\n self.offset_pred_cols = [f'{self.target}_timestep_{i}' for i in range(1, self.horizon)]\n if set(input_cols) != {self.tss.order_by}:\n input_cols.remove(self.tss.order_by)\n for col in self.offset_pred_cols:\n dtype_dict[col] = dtype_dict[self.target]\n self.models = [LightGBM(self.submodel_stop_after,\n target_col,\n dtype_dict,\n input_cols,\n False, # fit_on_dev,\n True, # use_optuna\n target_encoder)\n for _, target_col in zip(range(self.horizon), [target] + self.offset_pred_cols)]\n self.ts_analysis = ts_analysis\n self.supports_proba = False\n self.use_stl = False\n self.stable = True\n\n def _fit(self, train_data: EncodedDs, dev_data: EncodedDs, submodel_method='fit') -> None:\n original_train = deepcopy(train_data.data_frame)\n original_dev = deepcopy(dev_data.data_frame)\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n _apply_stl_on_training(train_data, dev_data, self.target, self.tss, self.ts_analysis)\n\n for timestep in range(self.horizon):\n getattr(self.models[timestep], submodel_method)(train_data, dev_data)\n\n # restore dfs\n train_data.data_frame = original_train\n dev_data.data_frame = original_dev\n\n def fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None:\n log.info('Started fitting LGBM models for array prediction')\n self._fit(train_data, dev_data, submodel_method='fit')\n\n def partial_fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None:\n log.info('Updating array of LGBM models...')\n self._fit(train_data, dev_data, submodel_method='partial_fit')\n\n def __call__(self, ds: Union[EncodedDs, ConcatedEncodedDs],\n args: PredictionArguments = PredictionArguments()) -> pd.DataFrame:\n if args.predict_proba:\n log.warning('This model does not output probability estimates')\n\n original_df = deepcopy(ds.data_frame)\n length = sum(ds.encoded_ds_lenghts) if isinstance(ds, ConcatedEncodedDs) else len(ds)\n ydf = pd.DataFrame(0, # zero-filled\n index=np.arange(length),\n columns=[f'prediction_{i}' for i in range(self.horizon)])\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n ds.data_frame = _stl_transform(ydf, ds, self.target, self.tss, self.ts_analysis)\n\n for timestep in range(self.horizon):\n ydf[f'prediction_{timestep}'] = self.models[timestep](ds, args)['prediction'].values\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n ydf = _stl_inverse_transform(ydf, ds, self.tss, self.ts_analysis)\n\n if self.models[0].positive_domain:\n ydf = ydf.clip(0)\n\n ydf['prediction'] = ydf.values.tolist()\n ds.data_frame = original_df\n return ydf[['prediction']]\n", "path": "lightwood/mixer/lightgbm_array.py"}], "after_files": [{"content": "from copy import deepcopy\nfrom typing import Dict, List, Union\n\nimport numpy as np\nimport pandas as pd\n\nfrom lightwood.helpers.log import log\nfrom lightwood.mixer.helpers.ts import _apply_stl_on_training, _stl_transform, _stl_inverse_transform\nfrom lightwood.encoder.base import BaseEncoder\nfrom lightwood.mixer.base import BaseMixer\nfrom lightwood.mixer.lightgbm import LightGBM\nfrom lightwood.api.types import PredictionArguments, TimeseriesSettings\nfrom lightwood.data.encoded_ds import EncodedDs, ConcatedEncodedDs\n\n\nclass LightGBMArray(BaseMixer):\n \"\"\"LightGBM-based model, intended for usage in time series tasks.\"\"\"\n models: List[LightGBM]\n submodel_stop_after: float\n target: str\n supports_proba: bool\n ts_analysis: Dict\n tss: TimeseriesSettings\n\n def __init__(\n self,\n stop_after: float,\n target: str,\n dtype_dict: Dict[str, str],\n input_cols: List[str],\n fit_on_dev: bool,\n target_encoder: BaseEncoder,\n ts_analysis: Dict[str, object],\n use_stl: bool,\n tss: TimeseriesSettings\n ):\n super().__init__(stop_after)\n self.tss = tss\n self.horizon = tss.horizon\n self.submodel_stop_after = stop_after / self.horizon\n self.target = target\n self.offset_pred_cols = [f'{self.target}_timestep_{i}' for i in range(1, self.horizon)]\n if set(input_cols) != {self.tss.order_by}:\n input_cols.remove(self.tss.order_by)\n for col in self.offset_pred_cols:\n dtype_dict[col] = dtype_dict[self.target]\n self.models = [LightGBM(self.submodel_stop_after,\n target_col,\n dtype_dict,\n input_cols,\n False, # fit_on_dev,\n True if tss.horizon < 10 else False, # use_optuna\n target_encoder)\n for _, target_col in zip(range(self.horizon), [target] + self.offset_pred_cols)]\n self.ts_analysis = ts_analysis\n self.supports_proba = False\n self.use_stl = False\n self.stable = True\n\n def _fit(self, train_data: EncodedDs, dev_data: EncodedDs, submodel_method='fit') -> None:\n original_train = deepcopy(train_data.data_frame)\n original_dev = deepcopy(dev_data.data_frame)\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n _apply_stl_on_training(train_data, dev_data, self.target, self.tss, self.ts_analysis)\n\n for timestep in range(self.horizon):\n getattr(self.models[timestep], submodel_method)(train_data, dev_data)\n\n # restore dfs\n train_data.data_frame = original_train\n dev_data.data_frame = original_dev\n\n def fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None:\n log.info('Started fitting LGBM models for array prediction')\n self._fit(train_data, dev_data, submodel_method='fit')\n\n def partial_fit(self, train_data: EncodedDs, dev_data: EncodedDs) -> None:\n log.info('Updating array of LGBM models...')\n self._fit(train_data, dev_data, submodel_method='partial_fit')\n\n def __call__(self, ds: Union[EncodedDs, ConcatedEncodedDs],\n args: PredictionArguments = PredictionArguments()) -> pd.DataFrame:\n if args.predict_proba:\n log.warning('This model does not output probability estimates')\n\n original_df = deepcopy(ds.data_frame)\n length = sum(ds.encoded_ds_lenghts) if isinstance(ds, ConcatedEncodedDs) else len(ds)\n ydf = pd.DataFrame(0, # zero-filled\n index=np.arange(length),\n columns=[f'prediction_{i}' for i in range(self.horizon)])\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n ds.data_frame = _stl_transform(ydf, ds, self.target, self.tss, self.ts_analysis)\n\n for timestep in range(self.horizon):\n ydf[f'prediction_{timestep}'] = self.models[timestep](ds, args)['prediction'].values\n\n if self.use_stl and self.ts_analysis.get('stl_transforms', False):\n ydf = _stl_inverse_transform(ydf, ds, self.tss, self.ts_analysis)\n\n if self.models[0].positive_domain:\n ydf = ydf.clip(0)\n\n ydf['prediction'] = ydf.values.tolist()\n ds.data_frame = original_df\n return ydf[['prediction']]\n", "path": "lightwood/mixer/lightgbm_array.py"}]}
1,576
143
gh_patches_debug_16279
rasdani/github-patches
git_diff
scikit-image__scikit-image-1367
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Invalid deprecation of canny, perhaps others ``` $ python -c "from skimage import filters as F; F.canny(0)" Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/stefan/src/scikit-image/skimage/_shared/utils.py", line 46, in __call__ msg = 'Call to deprecated function ``%s``.' % func.__name__ AttributeError: 'int' object has no attribute '__name__' ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `skimage/filters/__init__.py` Content: ``` 1 from .lpi_filter import inverse, wiener, LPIFilter2D 2 from ._gaussian import gaussian_filter 3 from .edges import (sobel, hsobel, vsobel, sobel_h, sobel_v, 4 scharr, hscharr, vscharr, scharr_h, scharr_v, 5 prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v, 6 roberts, roberts_positive_diagonal, 7 roberts_negative_diagonal, roberts_pos_diag, 8 roberts_neg_diag) 9 from ._rank_order import rank_order 10 from ._gabor import gabor_kernel, gabor_filter 11 from .thresholding import (threshold_adaptive, threshold_otsu, threshold_yen, 12 threshold_isodata) 13 from . import rank 14 from .rank import median 15 16 from .._shared.utils import deprecated 17 from .. import restoration 18 denoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\ 19 (restoration.denoise_bilateral) 20 denoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\ 21 (restoration.denoise_tv_bregman) 22 denoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\ 23 (restoration.denoise_tv_chambolle) 24 25 # Backward compatibility v<0.11 26 @deprecated 27 def canny(*args, **kwargs): 28 # Hack to avoid circular import 29 from ..feature._canny import canny as canny_ 30 return canny_(*args, **kwargs) 31 32 33 __all__ = ['inverse', 34 'wiener', 35 'LPIFilter2D', 36 'gaussian_filter', 37 'median', 38 'canny', 39 'sobel', 40 'hsobel', 41 'vsobel', 42 'sobel_h', 43 'sobel_v', 44 'scharr', 45 'hscharr', 46 'vscharr', 47 'scharr_h', 48 'scharr_v', 49 'prewitt', 50 'hprewitt', 51 'vprewitt', 52 'prewitt_h', 53 'prewitt_v', 54 'roberts', 55 'roberts_positive_diagonal', 56 'roberts_negative_diagonal', 57 'roberts_pos_diag', 58 'roberts_neg_diag', 59 'denoise_tv_chambolle', 60 'denoise_bilateral', 61 'denoise_tv_bregman', 62 'rank_order', 63 'gabor_kernel', 64 'gabor_filter', 65 'threshold_adaptive', 66 'threshold_otsu', 67 'threshold_yen', 68 'threshold_isodata', 69 'rank'] 70 ``` Path: `skimage/filter/__init__.py` Content: ``` 1 from .._shared.utils import skimage_deprecation 2 from warnings import warn 3 4 global _import_warned 5 6 warn(skimage_deprecation('The `skimage.filter` module has been renamed ' 7 'to `skimage.filters`. This placeholder module ' 8 'will be removed in v0.13.')) 9 _import_warned = True 10 11 del warn 12 del skimage_deprecation 13 14 from ..filters.lpi_filter import inverse, wiener, LPIFilter2D 15 from ..filters._gaussian import gaussian_filter 16 from ..filters.edges import (sobel, hsobel, vsobel, sobel_h, sobel_v, 17 scharr, hscharr, vscharr, scharr_h, scharr_v, 18 prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v, 19 roberts, roberts_positive_diagonal, 20 roberts_negative_diagonal, roberts_pos_diag, 21 roberts_neg_diag) 22 from ..filters._rank_order import rank_order 23 from ..filters._gabor import gabor_kernel, gabor_filter 24 from ..filters.thresholding import (threshold_adaptive, threshold_otsu, threshold_yen, 25 threshold_isodata) 26 from ..filters import rank 27 from ..filters.rank import median 28 29 from skimage._shared.utils import deprecated 30 from skimage import restoration 31 denoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\ 32 (restoration.denoise_bilateral) 33 denoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\ 34 (restoration.denoise_tv_bregman) 35 denoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\ 36 (restoration.denoise_tv_chambolle) 37 38 # Backward compatibility v<0.11 39 @deprecated 40 def canny(*args, **kwargs): 41 # Hack to avoid circular import 42 from skimage.feature._canny import canny as canny_ 43 return canny_(*args, **kwargs) 44 45 46 __all__ = ['inverse', 47 'wiener', 48 'LPIFilter2D', 49 'gaussian_filter', 50 'median', 51 'canny', 52 'sobel', 53 'hsobel', 54 'vsobel', 55 'sobel_h', 56 'sobel_v', 57 'scharr', 58 'hscharr', 59 'vscharr', 60 'scharr_h', 61 'scharr_v', 62 'prewitt', 63 'hprewitt', 64 'vprewitt', 65 'prewitt_h', 66 'prewitt_v', 67 'roberts', 68 'roberts_positive_diagonal', 69 'roberts_negative_diagonal', 70 'roberts_pos_diag', 71 'roberts_neg_diag', 72 'denoise_tv_chambolle', 73 'denoise_bilateral', 74 'denoise_tv_bregman', 75 'rank_order', 76 'gabor_kernel', 77 'gabor_filter', 78 'threshold_adaptive', 79 'threshold_otsu', 80 'threshold_yen', 81 'threshold_isodata', 82 'rank'] 83 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/skimage/filter/__init__.py b/skimage/filter/__init__.py --- a/skimage/filter/__init__.py +++ b/skimage/filter/__init__.py @@ -36,7 +36,7 @@ (restoration.denoise_tv_chambolle) # Backward compatibility v<0.11 -@deprecated +@deprecated('skimage.feature.canny') def canny(*args, **kwargs): # Hack to avoid circular import from skimage.feature._canny import canny as canny_ diff --git a/skimage/filters/__init__.py b/skimage/filters/__init__.py --- a/skimage/filters/__init__.py +++ b/skimage/filters/__init__.py @@ -23,7 +23,7 @@ (restoration.denoise_tv_chambolle) # Backward compatibility v<0.11 -@deprecated +@deprecated('skimage.feature.canny') def canny(*args, **kwargs): # Hack to avoid circular import from ..feature._canny import canny as canny_
{"golden_diff": "diff --git a/skimage/filter/__init__.py b/skimage/filter/__init__.py\n--- a/skimage/filter/__init__.py\n+++ b/skimage/filter/__init__.py\n@@ -36,7 +36,7 @@\n (restoration.denoise_tv_chambolle)\n \n # Backward compatibility v<0.11\n-@deprecated\n+@deprecated('skimage.feature.canny')\n def canny(*args, **kwargs):\n # Hack to avoid circular import\n from skimage.feature._canny import canny as canny_\ndiff --git a/skimage/filters/__init__.py b/skimage/filters/__init__.py\n--- a/skimage/filters/__init__.py\n+++ b/skimage/filters/__init__.py\n@@ -23,7 +23,7 @@\n (restoration.denoise_tv_chambolle)\n \n # Backward compatibility v<0.11\n-@deprecated\n+@deprecated('skimage.feature.canny')\n def canny(*args, **kwargs):\n # Hack to avoid circular import\n from ..feature._canny import canny as canny_\n", "issue": "Invalid deprecation of canny, perhaps others\n```\n$ python -c \"from skimage import filters as F; F.canny(0)\"\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\n File \"/home/stefan/src/scikit-image/skimage/_shared/utils.py\", line 46, in __call__\n msg = 'Call to deprecated function ``%s``.' % func.__name__\nAttributeError: 'int' object has no attribute '__name__'\n```\n\n", "before_files": [{"content": "from .lpi_filter import inverse, wiener, LPIFilter2D\nfrom ._gaussian import gaussian_filter\nfrom .edges import (sobel, hsobel, vsobel, sobel_h, sobel_v,\n scharr, hscharr, vscharr, scharr_h, scharr_v,\n prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v,\n roberts, roberts_positive_diagonal,\n roberts_negative_diagonal, roberts_pos_diag,\n roberts_neg_diag)\nfrom ._rank_order import rank_order\nfrom ._gabor import gabor_kernel, gabor_filter\nfrom .thresholding import (threshold_adaptive, threshold_otsu, threshold_yen,\n threshold_isodata)\nfrom . import rank\nfrom .rank import median\n\nfrom .._shared.utils import deprecated\nfrom .. import restoration\ndenoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\\\n (restoration.denoise_bilateral)\ndenoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\\\n (restoration.denoise_tv_bregman)\ndenoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\\\n (restoration.denoise_tv_chambolle)\n\n# Backward compatibility v<0.11\n@deprecated\ndef canny(*args, **kwargs):\n # Hack to avoid circular import\n from ..feature._canny import canny as canny_\n return canny_(*args, **kwargs)\n\n\n__all__ = ['inverse',\n 'wiener',\n 'LPIFilter2D',\n 'gaussian_filter',\n 'median',\n 'canny',\n 'sobel',\n 'hsobel',\n 'vsobel',\n 'sobel_h',\n 'sobel_v',\n 'scharr',\n 'hscharr',\n 'vscharr',\n 'scharr_h',\n 'scharr_v',\n 'prewitt',\n 'hprewitt',\n 'vprewitt',\n 'prewitt_h',\n 'prewitt_v',\n 'roberts',\n 'roberts_positive_diagonal',\n 'roberts_negative_diagonal',\n 'roberts_pos_diag',\n 'roberts_neg_diag',\n 'denoise_tv_chambolle',\n 'denoise_bilateral',\n 'denoise_tv_bregman',\n 'rank_order',\n 'gabor_kernel',\n 'gabor_filter',\n 'threshold_adaptive',\n 'threshold_otsu',\n 'threshold_yen',\n 'threshold_isodata',\n 'rank']\n", "path": "skimage/filters/__init__.py"}, {"content": "from .._shared.utils import skimage_deprecation\nfrom warnings import warn\n\nglobal _import_warned\n\nwarn(skimage_deprecation('The `skimage.filter` module has been renamed '\n 'to `skimage.filters`. This placeholder module '\n 'will be removed in v0.13.'))\n_import_warned = True\n\ndel warn\ndel skimage_deprecation\n\nfrom ..filters.lpi_filter import inverse, wiener, LPIFilter2D\nfrom ..filters._gaussian import gaussian_filter\nfrom ..filters.edges import (sobel, hsobel, vsobel, sobel_h, sobel_v,\n scharr, hscharr, vscharr, scharr_h, scharr_v,\n prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v,\n roberts, roberts_positive_diagonal,\n roberts_negative_diagonal, roberts_pos_diag,\n roberts_neg_diag)\nfrom ..filters._rank_order import rank_order\nfrom ..filters._gabor import gabor_kernel, gabor_filter\nfrom ..filters.thresholding import (threshold_adaptive, threshold_otsu, threshold_yen,\n threshold_isodata)\nfrom ..filters import rank\nfrom ..filters.rank import median\n\nfrom skimage._shared.utils import deprecated\nfrom skimage import restoration\ndenoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\\\n (restoration.denoise_bilateral)\ndenoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\\\n (restoration.denoise_tv_bregman)\ndenoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\\\n (restoration.denoise_tv_chambolle)\n\n# Backward compatibility v<0.11\n@deprecated\ndef canny(*args, **kwargs):\n # Hack to avoid circular import\n from skimage.feature._canny import canny as canny_\n return canny_(*args, **kwargs)\n\n\n__all__ = ['inverse',\n 'wiener',\n 'LPIFilter2D',\n 'gaussian_filter',\n 'median',\n 'canny',\n 'sobel',\n 'hsobel',\n 'vsobel',\n 'sobel_h',\n 'sobel_v',\n 'scharr',\n 'hscharr',\n 'vscharr',\n 'scharr_h',\n 'scharr_v',\n 'prewitt',\n 'hprewitt',\n 'vprewitt',\n 'prewitt_h',\n 'prewitt_v',\n 'roberts',\n 'roberts_positive_diagonal',\n 'roberts_negative_diagonal',\n 'roberts_pos_diag',\n 'roberts_neg_diag',\n 'denoise_tv_chambolle',\n 'denoise_bilateral',\n 'denoise_tv_bregman',\n 'rank_order',\n 'gabor_kernel',\n 'gabor_filter',\n 'threshold_adaptive',\n 'threshold_otsu',\n 'threshold_yen',\n 'threshold_isodata',\n 'rank']\n", "path": "skimage/filter/__init__.py"}], "after_files": [{"content": "from .lpi_filter import inverse, wiener, LPIFilter2D\nfrom ._gaussian import gaussian_filter\nfrom .edges import (sobel, hsobel, vsobel, sobel_h, sobel_v,\n scharr, hscharr, vscharr, scharr_h, scharr_v,\n prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v,\n roberts, roberts_positive_diagonal,\n roberts_negative_diagonal, roberts_pos_diag,\n roberts_neg_diag)\nfrom ._rank_order import rank_order\nfrom ._gabor import gabor_kernel, gabor_filter\nfrom .thresholding import (threshold_adaptive, threshold_otsu, threshold_yen,\n threshold_isodata)\nfrom . import rank\nfrom .rank import median\n\nfrom .._shared.utils import deprecated\nfrom .. import restoration\ndenoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\\\n (restoration.denoise_bilateral)\ndenoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\\\n (restoration.denoise_tv_bregman)\ndenoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\\\n (restoration.denoise_tv_chambolle)\n\n# Backward compatibility v<0.11\n@deprecated('skimage.feature.canny')\ndef canny(*args, **kwargs):\n # Hack to avoid circular import\n from ..feature._canny import canny as canny_\n return canny_(*args, **kwargs)\n\n\n__all__ = ['inverse',\n 'wiener',\n 'LPIFilter2D',\n 'gaussian_filter',\n 'median',\n 'canny',\n 'sobel',\n 'hsobel',\n 'vsobel',\n 'sobel_h',\n 'sobel_v',\n 'scharr',\n 'hscharr',\n 'vscharr',\n 'scharr_h',\n 'scharr_v',\n 'prewitt',\n 'hprewitt',\n 'vprewitt',\n 'prewitt_h',\n 'prewitt_v',\n 'roberts',\n 'roberts_positive_diagonal',\n 'roberts_negative_diagonal',\n 'roberts_pos_diag',\n 'roberts_neg_diag',\n 'denoise_tv_chambolle',\n 'denoise_bilateral',\n 'denoise_tv_bregman',\n 'rank_order',\n 'gabor_kernel',\n 'gabor_filter',\n 'threshold_adaptive',\n 'threshold_otsu',\n 'threshold_yen',\n 'threshold_isodata',\n 'rank']\n", "path": "skimage/filters/__init__.py"}, {"content": "from .._shared.utils import skimage_deprecation\nfrom warnings import warn\n\nglobal _import_warned\n\nwarn(skimage_deprecation('The `skimage.filter` module has been renamed '\n 'to `skimage.filters`. This placeholder module '\n 'will be removed in v0.13.'))\n_import_warned = True\n\ndel warn\ndel skimage_deprecation\n\nfrom ..filters.lpi_filter import inverse, wiener, LPIFilter2D\nfrom ..filters._gaussian import gaussian_filter\nfrom ..filters.edges import (sobel, hsobel, vsobel, sobel_h, sobel_v,\n scharr, hscharr, vscharr, scharr_h, scharr_v,\n prewitt, hprewitt, vprewitt, prewitt_h, prewitt_v,\n roberts, roberts_positive_diagonal,\n roberts_negative_diagonal, roberts_pos_diag,\n roberts_neg_diag)\nfrom ..filters._rank_order import rank_order\nfrom ..filters._gabor import gabor_kernel, gabor_filter\nfrom ..filters.thresholding import (threshold_adaptive, threshold_otsu, threshold_yen,\n threshold_isodata)\nfrom ..filters import rank\nfrom ..filters.rank import median\n\nfrom skimage._shared.utils import deprecated\nfrom skimage import restoration\ndenoise_bilateral = deprecated('skimage.restoration.denoise_bilateral')\\\n (restoration.denoise_bilateral)\ndenoise_tv_bregman = deprecated('skimage.restoration.denoise_tv_bregman')\\\n (restoration.denoise_tv_bregman)\ndenoise_tv_chambolle = deprecated('skimage.restoration.denoise_tv_chambolle')\\\n (restoration.denoise_tv_chambolle)\n\n# Backward compatibility v<0.11\n@deprecated('skimage.feature.canny')\ndef canny(*args, **kwargs):\n # Hack to avoid circular import\n from skimage.feature._canny import canny as canny_\n return canny_(*args, **kwargs)\n\n\n__all__ = ['inverse',\n 'wiener',\n 'LPIFilter2D',\n 'gaussian_filter',\n 'median',\n 'canny',\n 'sobel',\n 'hsobel',\n 'vsobel',\n 'sobel_h',\n 'sobel_v',\n 'scharr',\n 'hscharr',\n 'vscharr',\n 'scharr_h',\n 'scharr_v',\n 'prewitt',\n 'hprewitt',\n 'vprewitt',\n 'prewitt_h',\n 'prewitt_v',\n 'roberts',\n 'roberts_positive_diagonal',\n 'roberts_negative_diagonal',\n 'roberts_pos_diag',\n 'roberts_neg_diag',\n 'denoise_tv_chambolle',\n 'denoise_bilateral',\n 'denoise_tv_bregman',\n 'rank_order',\n 'gabor_kernel',\n 'gabor_filter',\n 'threshold_adaptive',\n 'threshold_otsu',\n 'threshold_yen',\n 'threshold_isodata',\n 'rank']\n", "path": "skimage/filter/__init__.py"}]}
1,937
254
gh_patches_debug_23827
rasdani/github-patches
git_diff
scoutapp__scout_apm_python-709
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Celery exceptions cause error in capture_stacktrace The latest version of celery, 5.2.1, raises some exceptions in an unexpected way. For this particular case, `tb` was a string of value: ``` 'Traceback (most recent call last):\n File "/app/.heroku/python/lib/python3.9/site-packages/billiard/pool.py", line 366, in workloop\n put((READY, (job, i, result, inqW_fd)))\n File "/app/.heroku/python/lib/python3.9/site-packages/billiard/queues.py", line 366, in put\n self.send_payload(ForkingPickler.dumps(obj))\n File "/app/.heroku/python/lib/python3.9/site-packages/billiard/reduction.py", line 56, in dumps\n cls(buf, protocol).dump(obj)\nbilliard.pool.MaybeEncodingError: Error sending res...' ``` Stacktrace of error ``` AttributeError: 'str' object has no attribute 'tb_frame' File "celery/utils/dispatch/signal.py", line 276, in send response = receiver(signal=self, sender=sender, **named) File "scout_apm/celery.py", line 114, in task_failure_callback ErrorMonitor.send( File "scout_apm/core/error.py", line 69, in send for frame in capture_stacktrace(traceback) File "scout_apm/core/backtrace.py", line 132, in capture_stacktrace return list(reversed(list(itertools.islice(walker, LIMIT)))) File "scout_apm/core/backtrace.py", line 75, in stacktrace_walker for frame, lineno in traceback.walk_tb(tb): File "traceback.py", line 312, in walk_tb yield tb.tb_frame, tb.tb_lineno ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `src/scout_apm/celery.py` Content: ``` 1 # coding=utf-8 2 from __future__ import absolute_import, division, print_function, unicode_literals 3 4 import datetime as dt 5 import logging 6 7 from celery.signals import before_task_publish, task_failure, task_postrun, task_prerun 8 9 try: 10 import django 11 12 if django.VERSION < (3, 1): 13 from django.views.debug import get_safe_settings 14 else: 15 from django.views.debug import SafeExceptionReporterFilter 16 17 def get_safe_settings(): 18 return SafeExceptionReporterFilter().get_safe_settings() 19 20 21 except ImportError: 22 # Django not installed 23 get_safe_settings = None 24 25 import scout_apm.core 26 from scout_apm.compat import datetime_to_timestamp 27 from scout_apm.core.config import scout_config 28 from scout_apm.core.error import ErrorMonitor 29 from scout_apm.core.tracked_request import TrackedRequest 30 31 logger = logging.getLogger(__name__) 32 33 34 def before_task_publish_callback(headers=None, properties=None, **kwargs): 35 if "scout_task_start" not in headers: 36 headers["scout_task_start"] = datetime_to_timestamp(dt.datetime.utcnow()) 37 38 39 def task_prerun_callback(task=None, **kwargs): 40 tracked_request = TrackedRequest.instance() 41 tracked_request.is_real_request = True 42 43 start = getattr(task.request, "scout_task_start", None) 44 if start is not None: 45 now = datetime_to_timestamp(dt.datetime.utcnow()) 46 try: 47 queue_time = now - start 48 except TypeError: 49 pass 50 else: 51 tracked_request.tag("queue_time", queue_time) 52 53 task_id = getattr(task.request, "id", None) 54 if task_id: 55 tracked_request.tag("task_id", task_id) 56 parent_task_id = getattr(task.request, "parent_id", None) 57 if parent_task_id: 58 tracked_request.tag("parent_task_id", parent_task_id) 59 60 delivery_info = task.request.delivery_info 61 tracked_request.tag("is_eager", delivery_info.get("is_eager", False)) 62 tracked_request.tag("exchange", delivery_info.get("exchange", "unknown")) 63 tracked_request.tag("priority", delivery_info.get("priority", "unknown")) 64 tracked_request.tag("routing_key", delivery_info.get("routing_key", "unknown")) 65 tracked_request.tag("queue", delivery_info.get("queue", "unknown")) 66 67 tracked_request.start_span(operation=("Job/" + task.name)) 68 69 70 def task_postrun_callback(task=None, **kwargs): 71 tracked_request = TrackedRequest.instance() 72 tracked_request.stop_span() 73 74 75 def task_failure_callback( 76 sender, 77 task_id=None, 78 exception=None, 79 args=None, 80 kwargs=None, 81 traceback=None, 82 **remaining 83 ): 84 tracked_request = TrackedRequest.instance() 85 tracked_request.tag("error", "true") 86 87 custom_controller = sender.name 88 custom_params = { 89 "celery": { 90 "task_id": task_id, 91 "args": args, 92 "kwargs": kwargs, 93 } 94 } 95 96 # Look up the django settings if populated. 97 environment = None 98 if get_safe_settings: 99 try: 100 environment = get_safe_settings() 101 except django.core.exceptions.ImproperlyConfigured as exc: 102 # Django not setup correctly 103 logger.debug( 104 "Celery integration does not have django configured properly: %r", exc 105 ) 106 pass 107 except Exception as exc: 108 logger.debug( 109 "Celery task_failure callback exception: %r", exc, exc_info=exc 110 ) 111 pass 112 113 exc_info = (exception.__class__, exception, traceback) 114 ErrorMonitor.send( 115 exc_info, 116 environment=environment, 117 custom_params=custom_params, 118 custom_controller=custom_controller, 119 ) 120 121 122 def install(app=None): 123 if app is not None: 124 copy_configuration(app) 125 126 installed = scout_apm.core.install() 127 if not installed: 128 return 129 130 before_task_publish.connect(before_task_publish_callback) 131 task_prerun.connect(task_prerun_callback) 132 task_failure.connect(task_failure_callback) 133 task_postrun.connect(task_postrun_callback) 134 135 136 def copy_configuration(app): 137 prefix = "scout_" 138 prefix_len = len(prefix) 139 140 to_set = {} 141 for key, value in app.conf.items(): 142 key_lower = key.lower() 143 if key_lower.startswith(prefix) and len(key_lower) > prefix_len: 144 scout_key = key_lower[prefix_len:] 145 to_set[scout_key] = value 146 147 scout_config.set(**to_set) 148 149 150 def uninstall(): 151 before_task_publish.disconnect(before_task_publish_callback) 152 task_prerun.disconnect(task_prerun_callback) 153 task_postrun.disconnect(task_postrun_callback) 154 task_failure.disconnect(task_failure_callback) 155 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/src/scout_apm/celery.py b/src/scout_apm/celery.py --- a/src/scout_apm/celery.py +++ b/src/scout_apm/celery.py @@ -23,7 +23,7 @@ get_safe_settings = None import scout_apm.core -from scout_apm.compat import datetime_to_timestamp +from scout_apm.compat import datetime_to_timestamp, string_type from scout_apm.core.config import scout_config from scout_apm.core.error import ErrorMonitor from scout_apm.core.tracked_request import TrackedRequest @@ -79,6 +79,7 @@ args=None, kwargs=None, traceback=None, + einfo=None, **remaining ): tracked_request = TrackedRequest.instance() @@ -110,6 +111,12 @@ ) pass + # Celery occassionally will send the traceback as a string rather + # than a Stack trace object as the docs indicate. In that case, + # fall back to the billiard ExceptionInfo instance + traceback = ( + traceback if traceback and not isinstance(traceback, string_type) else einfo.tb + ) exc_info = (exception.__class__, exception, traceback) ErrorMonitor.send( exc_info,
{"golden_diff": "diff --git a/src/scout_apm/celery.py b/src/scout_apm/celery.py\n--- a/src/scout_apm/celery.py\n+++ b/src/scout_apm/celery.py\n@@ -23,7 +23,7 @@\n get_safe_settings = None\n \n import scout_apm.core\n-from scout_apm.compat import datetime_to_timestamp\n+from scout_apm.compat import datetime_to_timestamp, string_type\n from scout_apm.core.config import scout_config\n from scout_apm.core.error import ErrorMonitor\n from scout_apm.core.tracked_request import TrackedRequest\n@@ -79,6 +79,7 @@\n args=None,\n kwargs=None,\n traceback=None,\n+ einfo=None,\n **remaining\n ):\n tracked_request = TrackedRequest.instance()\n@@ -110,6 +111,12 @@\n )\n pass\n \n+ # Celery occassionally will send the traceback as a string rather\n+ # than a Stack trace object as the docs indicate. In that case,\n+ # fall back to the billiard ExceptionInfo instance\n+ traceback = (\n+ traceback if traceback and not isinstance(traceback, string_type) else einfo.tb\n+ )\n exc_info = (exception.__class__, exception, traceback)\n ErrorMonitor.send(\n exc_info,\n", "issue": "Celery exceptions cause error in capture_stacktrace\nThe latest version of celery, 5.2.1, raises some exceptions in an unexpected way.\r\n\r\nFor this particular case, `tb` was a string of value:\r\n\r\n```\r\n'Traceback (most recent call last):\\n File \"/app/.heroku/python/lib/python3.9/site-packages/billiard/pool.py\", line 366, in workloop\\n put((READY, (job, i, result, inqW_fd)))\\n File \"/app/.heroku/python/lib/python3.9/site-packages/billiard/queues.py\", line 366, in put\\n self.send_payload(ForkingPickler.dumps(obj))\\n File \"/app/.heroku/python/lib/python3.9/site-packages/billiard/reduction.py\", line 56, in dumps\\n cls(buf, protocol).dump(obj)\\nbilliard.pool.MaybeEncodingError: Error sending res...'\r\n```\r\n\r\nStacktrace of error\r\n```\r\nAttributeError: 'str' object has no attribute 'tb_frame'\r\n File \"celery/utils/dispatch/signal.py\", line 276, in send\r\n response = receiver(signal=self, sender=sender, **named)\r\n File \"scout_apm/celery.py\", line 114, in task_failure_callback\r\n ErrorMonitor.send(\r\n File \"scout_apm/core/error.py\", line 69, in send\r\n for frame in capture_stacktrace(traceback)\r\n File \"scout_apm/core/backtrace.py\", line 132, in capture_stacktrace\r\n return list(reversed(list(itertools.islice(walker, LIMIT))))\r\n File \"scout_apm/core/backtrace.py\", line 75, in stacktrace_walker\r\n for frame, lineno in traceback.walk_tb(tb):\r\n File \"traceback.py\", line 312, in walk_tb\r\n yield tb.tb_frame, tb.tb_lineno\r\n```\n", "before_files": [{"content": "# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport datetime as dt\nimport logging\n\nfrom celery.signals import before_task_publish, task_failure, task_postrun, task_prerun\n\ntry:\n import django\n\n if django.VERSION < (3, 1):\n from django.views.debug import get_safe_settings\n else:\n from django.views.debug import SafeExceptionReporterFilter\n\n def get_safe_settings():\n return SafeExceptionReporterFilter().get_safe_settings()\n\n\nexcept ImportError:\n # Django not installed\n get_safe_settings = None\n\nimport scout_apm.core\nfrom scout_apm.compat import datetime_to_timestamp\nfrom scout_apm.core.config import scout_config\nfrom scout_apm.core.error import ErrorMonitor\nfrom scout_apm.core.tracked_request import TrackedRequest\n\nlogger = logging.getLogger(__name__)\n\n\ndef before_task_publish_callback(headers=None, properties=None, **kwargs):\n if \"scout_task_start\" not in headers:\n headers[\"scout_task_start\"] = datetime_to_timestamp(dt.datetime.utcnow())\n\n\ndef task_prerun_callback(task=None, **kwargs):\n tracked_request = TrackedRequest.instance()\n tracked_request.is_real_request = True\n\n start = getattr(task.request, \"scout_task_start\", None)\n if start is not None:\n now = datetime_to_timestamp(dt.datetime.utcnow())\n try:\n queue_time = now - start\n except TypeError:\n pass\n else:\n tracked_request.tag(\"queue_time\", queue_time)\n\n task_id = getattr(task.request, \"id\", None)\n if task_id:\n tracked_request.tag(\"task_id\", task_id)\n parent_task_id = getattr(task.request, \"parent_id\", None)\n if parent_task_id:\n tracked_request.tag(\"parent_task_id\", parent_task_id)\n\n delivery_info = task.request.delivery_info\n tracked_request.tag(\"is_eager\", delivery_info.get(\"is_eager\", False))\n tracked_request.tag(\"exchange\", delivery_info.get(\"exchange\", \"unknown\"))\n tracked_request.tag(\"priority\", delivery_info.get(\"priority\", \"unknown\"))\n tracked_request.tag(\"routing_key\", delivery_info.get(\"routing_key\", \"unknown\"))\n tracked_request.tag(\"queue\", delivery_info.get(\"queue\", \"unknown\"))\n\n tracked_request.start_span(operation=(\"Job/\" + task.name))\n\n\ndef task_postrun_callback(task=None, **kwargs):\n tracked_request = TrackedRequest.instance()\n tracked_request.stop_span()\n\n\ndef task_failure_callback(\n sender,\n task_id=None,\n exception=None,\n args=None,\n kwargs=None,\n traceback=None,\n **remaining\n):\n tracked_request = TrackedRequest.instance()\n tracked_request.tag(\"error\", \"true\")\n\n custom_controller = sender.name\n custom_params = {\n \"celery\": {\n \"task_id\": task_id,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n }\n\n # Look up the django settings if populated.\n environment = None\n if get_safe_settings:\n try:\n environment = get_safe_settings()\n except django.core.exceptions.ImproperlyConfigured as exc:\n # Django not setup correctly\n logger.debug(\n \"Celery integration does not have django configured properly: %r\", exc\n )\n pass\n except Exception as exc:\n logger.debug(\n \"Celery task_failure callback exception: %r\", exc, exc_info=exc\n )\n pass\n\n exc_info = (exception.__class__, exception, traceback)\n ErrorMonitor.send(\n exc_info,\n environment=environment,\n custom_params=custom_params,\n custom_controller=custom_controller,\n )\n\n\ndef install(app=None):\n if app is not None:\n copy_configuration(app)\n\n installed = scout_apm.core.install()\n if not installed:\n return\n\n before_task_publish.connect(before_task_publish_callback)\n task_prerun.connect(task_prerun_callback)\n task_failure.connect(task_failure_callback)\n task_postrun.connect(task_postrun_callback)\n\n\ndef copy_configuration(app):\n prefix = \"scout_\"\n prefix_len = len(prefix)\n\n to_set = {}\n for key, value in app.conf.items():\n key_lower = key.lower()\n if key_lower.startswith(prefix) and len(key_lower) > prefix_len:\n scout_key = key_lower[prefix_len:]\n to_set[scout_key] = value\n\n scout_config.set(**to_set)\n\n\ndef uninstall():\n before_task_publish.disconnect(before_task_publish_callback)\n task_prerun.disconnect(task_prerun_callback)\n task_postrun.disconnect(task_postrun_callback)\n task_failure.disconnect(task_failure_callback)\n", "path": "src/scout_apm/celery.py"}], "after_files": [{"content": "# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport datetime as dt\nimport logging\n\nfrom celery.signals import before_task_publish, task_failure, task_postrun, task_prerun\n\ntry:\n import django\n\n if django.VERSION < (3, 1):\n from django.views.debug import get_safe_settings\n else:\n from django.views.debug import SafeExceptionReporterFilter\n\n def get_safe_settings():\n return SafeExceptionReporterFilter().get_safe_settings()\n\n\nexcept ImportError:\n # Django not installed\n get_safe_settings = None\n\nimport scout_apm.core\nfrom scout_apm.compat import datetime_to_timestamp, string_type\nfrom scout_apm.core.config import scout_config\nfrom scout_apm.core.error import ErrorMonitor\nfrom scout_apm.core.tracked_request import TrackedRequest\n\nlogger = logging.getLogger(__name__)\n\n\ndef before_task_publish_callback(headers=None, properties=None, **kwargs):\n if \"scout_task_start\" not in headers:\n headers[\"scout_task_start\"] = datetime_to_timestamp(dt.datetime.utcnow())\n\n\ndef task_prerun_callback(task=None, **kwargs):\n tracked_request = TrackedRequest.instance()\n tracked_request.is_real_request = True\n\n start = getattr(task.request, \"scout_task_start\", None)\n if start is not None:\n now = datetime_to_timestamp(dt.datetime.utcnow())\n try:\n queue_time = now - start\n except TypeError:\n pass\n else:\n tracked_request.tag(\"queue_time\", queue_time)\n\n task_id = getattr(task.request, \"id\", None)\n if task_id:\n tracked_request.tag(\"task_id\", task_id)\n parent_task_id = getattr(task.request, \"parent_id\", None)\n if parent_task_id:\n tracked_request.tag(\"parent_task_id\", parent_task_id)\n\n delivery_info = task.request.delivery_info\n tracked_request.tag(\"is_eager\", delivery_info.get(\"is_eager\", False))\n tracked_request.tag(\"exchange\", delivery_info.get(\"exchange\", \"unknown\"))\n tracked_request.tag(\"priority\", delivery_info.get(\"priority\", \"unknown\"))\n tracked_request.tag(\"routing_key\", delivery_info.get(\"routing_key\", \"unknown\"))\n tracked_request.tag(\"queue\", delivery_info.get(\"queue\", \"unknown\"))\n\n tracked_request.start_span(operation=(\"Job/\" + task.name))\n\n\ndef task_postrun_callback(task=None, **kwargs):\n tracked_request = TrackedRequest.instance()\n tracked_request.stop_span()\n\n\ndef task_failure_callback(\n sender,\n task_id=None,\n exception=None,\n args=None,\n kwargs=None,\n traceback=None,\n einfo=None,\n **remaining\n):\n tracked_request = TrackedRequest.instance()\n tracked_request.tag(\"error\", \"true\")\n\n custom_controller = sender.name\n custom_params = {\n \"celery\": {\n \"task_id\": task_id,\n \"args\": args,\n \"kwargs\": kwargs,\n }\n }\n\n # Look up the django settings if populated.\n environment = None\n if get_safe_settings:\n try:\n environment = get_safe_settings()\n except django.core.exceptions.ImproperlyConfigured as exc:\n # Django not setup correctly\n logger.debug(\n \"Celery integration does not have django configured properly: %r\", exc\n )\n pass\n except Exception as exc:\n logger.debug(\n \"Celery task_failure callback exception: %r\", exc, exc_info=exc\n )\n pass\n\n # Celery occassionally will send the traceback as a string rather\n # than a Stack trace object as the docs indicate. In that case,\n # fall back to the billiard ExceptionInfo instance\n traceback = (\n traceback if traceback and not isinstance(traceback, string_type) else einfo.tb\n )\n exc_info = (exception.__class__, exception, traceback)\n ErrorMonitor.send(\n exc_info,\n environment=environment,\n custom_params=custom_params,\n custom_controller=custom_controller,\n )\n\n\ndef install(app=None):\n if app is not None:\n copy_configuration(app)\n\n installed = scout_apm.core.install()\n if not installed:\n return\n\n before_task_publish.connect(before_task_publish_callback)\n task_prerun.connect(task_prerun_callback)\n task_failure.connect(task_failure_callback)\n task_postrun.connect(task_postrun_callback)\n\n\ndef copy_configuration(app):\n prefix = \"scout_\"\n prefix_len = len(prefix)\n\n to_set = {}\n for key, value in app.conf.items():\n key_lower = key.lower()\n if key_lower.startswith(prefix) and len(key_lower) > prefix_len:\n scout_key = key_lower[prefix_len:]\n to_set[scout_key] = value\n\n scout_config.set(**to_set)\n\n\ndef uninstall():\n before_task_publish.disconnect(before_task_publish_callback)\n task_prerun.disconnect(task_prerun_callback)\n task_postrun.disconnect(task_postrun_callback)\n task_failure.disconnect(task_failure_callback)\n", "path": "src/scout_apm/celery.py"}]}
2,047
291
gh_patches_debug_56612
rasdani/github-patches
git_diff
spacetelescope__jwql-677
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Update Bokeh to latest version I remember there was some reason that we were holding off on upgrading Bokeh from 1.3.4. However, Bokeh is now up to version 2.2.1 I believe. We should look into upgrading the version used for JWQL in order to take advantage of new features and so that we minimize the number of plots created under 1.3.4 which may need to be tweaked to work under the new version. For example, one difference I ran into today was that the keyword "legend", which is used in 1.3.4 to denote the string printed in the legend for a particular element, has been changed to "legend_label" in version 2.2.1. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 import numpy as np 2 from setuptools import setup 3 from setuptools import find_packages 4 5 VERSION = '0.24.0' 6 7 AUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Mike Engesser, Mees Fix, Joe Filippazzo, Bryan Hilbert, ' 8 AUTHORS += 'Graham Kanarek, Teagan King, Catherine Martlin, Maria Pena-Guerrero, Johannes Sahlmann, Ben Sunnquist' 9 10 DESCRIPTION = 'The James Webb Space Telescope Quicklook Project' 11 12 DEPENDENCY_LINKS = ['git+https://github.com/spacetelescope/jwst_reffiles#egg=jwst_reffiles'] 13 14 REQUIRES = [ 15 'asdf>=2.3.3', 16 'astropy>=3.2.1', 17 'astroquery>=0.3.9', 18 'authlib', 19 'bokeh>=1.0,<1.4', 20 'codecov', 21 'crds', 22 'cryptography', 23 'django', 24 'flake8', 25 'inflection', 26 'ipython', 27 'jinja2', 28 'jsonschema', 29 'jwedb>=0.0.3', 30 'jwst', 31 'matplotlib', 32 'nodejs', 33 'numpy', 34 'numpydoc', 35 'pandas', 36 'psycopg2', 37 'pysiaf', 38 'pytest', 39 'pytest-cov', 40 'scipy', 41 'sphinx', 42 'sqlalchemy', 43 'stsci_rtd_theme', 44 'twine', 45 'wtforms' 46 ] 47 48 setup( 49 name='jwql', 50 version=VERSION, 51 description=DESCRIPTION, 52 url='https://github.com/spacetelescope/jwql.git', 53 author=AUTHORS, 54 author_email='[email protected]', 55 license='BSD', 56 keywords=['astronomy', 'python'], 57 classifiers=['Programming Language :: Python'], 58 packages=find_packages(), 59 install_requires=REQUIRES, 60 dependency_links=DEPENDENCY_LINKS, 61 include_package_data=True, 62 include_dirs=[np.get_include()], 63 ) 64 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ 'astropy>=3.2.1', 'astroquery>=0.3.9', 'authlib', - 'bokeh>=1.0,<1.4', + 'bokeh', 'codecov', 'crds', 'cryptography',
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -16,7 +16,7 @@\n 'astropy>=3.2.1',\n 'astroquery>=0.3.9',\n 'authlib',\n- 'bokeh>=1.0,<1.4',\n+ 'bokeh',\n 'codecov',\n 'crds',\n 'cryptography',\n", "issue": "Update Bokeh to latest version\nI remember there was some reason that we were holding off on upgrading Bokeh from 1.3.4. However, Bokeh is now up to version 2.2.1 I believe. We should look into upgrading the version used for JWQL in order to take advantage of new features and so that we minimize the number of plots created under 1.3.4 which may need to be tweaked to work under the new version.\r\n\r\nFor example, one difference I ran into today was that the keyword \"legend\", which is used in 1.3.4 to denote the string printed in the legend for a particular element, has been changed to \"legend_label\" in version 2.2.1.\n", "before_files": [{"content": "import numpy as np\nfrom setuptools import setup\nfrom setuptools import find_packages\n\nVERSION = '0.24.0'\n\nAUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Mike Engesser, Mees Fix, Joe Filippazzo, Bryan Hilbert, '\nAUTHORS += 'Graham Kanarek, Teagan King, Catherine Martlin, Maria Pena-Guerrero, Johannes Sahlmann, Ben Sunnquist'\n\nDESCRIPTION = 'The James Webb Space Telescope Quicklook Project'\n\nDEPENDENCY_LINKS = ['git+https://github.com/spacetelescope/jwst_reffiles#egg=jwst_reffiles']\n\nREQUIRES = [\n 'asdf>=2.3.3',\n 'astropy>=3.2.1',\n 'astroquery>=0.3.9',\n 'authlib',\n 'bokeh>=1.0,<1.4',\n 'codecov',\n 'crds',\n 'cryptography',\n 'django',\n 'flake8',\n 'inflection',\n 'ipython',\n 'jinja2',\n 'jsonschema',\n 'jwedb>=0.0.3',\n 'jwst',\n 'matplotlib',\n 'nodejs',\n 'numpy',\n 'numpydoc',\n 'pandas',\n 'psycopg2',\n 'pysiaf',\n 'pytest',\n 'pytest-cov',\n 'scipy',\n 'sphinx',\n 'sqlalchemy',\n 'stsci_rtd_theme',\n 'twine',\n 'wtforms'\n]\n\nsetup(\n name='jwql',\n version=VERSION,\n description=DESCRIPTION,\n url='https://github.com/spacetelescope/jwql.git',\n author=AUTHORS,\n author_email='[email protected]',\n license='BSD',\n keywords=['astronomy', 'python'],\n classifiers=['Programming Language :: Python'],\n packages=find_packages(),\n install_requires=REQUIRES,\n dependency_links=DEPENDENCY_LINKS,\n include_package_data=True,\n include_dirs=[np.get_include()],\n)\n", "path": "setup.py"}], "after_files": [{"content": "import numpy as np\nfrom setuptools import setup\nfrom setuptools import find_packages\n\nVERSION = '0.24.0'\n\nAUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Mike Engesser, Mees Fix, Joe Filippazzo, Bryan Hilbert, '\nAUTHORS += 'Graham Kanarek, Teagan King, Catherine Martlin, Maria Pena-Guerrero, Johannes Sahlmann, Ben Sunnquist'\n\nDESCRIPTION = 'The James Webb Space Telescope Quicklook Project'\n\nDEPENDENCY_LINKS = ['git+https://github.com/spacetelescope/jwst_reffiles#egg=jwst_reffiles']\n\nREQUIRES = [\n 'asdf>=2.3.3',\n 'astropy>=3.2.1',\n 'astroquery>=0.3.9',\n 'authlib',\n 'bokeh',\n 'codecov',\n 'crds',\n 'cryptography',\n 'django',\n 'flake8',\n 'inflection',\n 'ipython',\n 'jinja2',\n 'jsonschema',\n 'jwedb>=0.0.3',\n 'jwst',\n 'matplotlib',\n 'nodejs',\n 'numpy',\n 'numpydoc',\n 'pandas',\n 'psycopg2',\n 'pysiaf',\n 'pytest',\n 'pytest-cov',\n 'scipy',\n 'sphinx',\n 'sqlalchemy',\n 'stsci_rtd_theme',\n 'twine',\n 'wtforms'\n]\n\nsetup(\n name='jwql',\n version=VERSION,\n description=DESCRIPTION,\n url='https://github.com/spacetelescope/jwql.git',\n author=AUTHORS,\n author_email='[email protected]',\n license='BSD',\n keywords=['astronomy', 'python'],\n classifiers=['Programming Language :: Python'],\n packages=find_packages(),\n install_requires=REQUIRES,\n dependency_links=DEPENDENCY_LINKS,\n include_package_data=True,\n include_dirs=[np.get_include()],\n)\n", "path": "setup.py"}]}
981
94
gh_patches_debug_26224
rasdani/github-patches
git_diff
mirumee__ariadne-24
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `add_resolve_functions_to_schema` should support Scalars parse_value and parse_literal Currently Ariadne Scalar support is limited to serializing python types to JSON before returning them to client, but we also want to support using custom scalars for input. Our `add_resolve_functions_to_scalar` utility could support following use-cases: Code below results in one-way only scalar: - `type_defs = {'Scalar': {'serialize': callable}}` And this code results in two-way scalar: - `type_defs = {'Scalar': {'serialize': callable, 'parse_value': callable, 'parse_literal': callable}}` - explicit syntax for two-directional scalar. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `ariadne/resolvers.py` Content: ``` 1 from graphql import GraphQLObjectType, GraphQLScalarType, GraphQLSchema 2 from graphql.execution.base import ResolveInfo 3 4 5 def resolve_parent_field(parent, name: str): 6 if isinstance(parent, dict): 7 return parent.get(name) 8 return getattr(parent, name, None) 9 10 11 def default_resolver(parent, info: ResolveInfo): 12 return resolve_parent_field(parent, info.field_name) 13 14 15 def resolve_to(name: str): 16 def resolver(parent, *_): 17 return resolve_parent_field(parent, name) 18 19 return resolver 20 21 22 def add_resolve_functions_to_schema(schema: GraphQLSchema, resolvers: dict): 23 for type_name, type_object in schema.get_type_map().items(): 24 if isinstance(type_object, GraphQLObjectType): 25 add_resolve_functions_to_object(type_name, type_object, resolvers) 26 if isinstance(type_object, GraphQLScalarType): 27 add_resolve_function_to_scalar(type_name, type_object, resolvers) 28 29 30 def add_resolve_functions_to_object(name: str, obj: GraphQLObjectType, resolvers: dict): 31 type_resolver = resolvers.get(name, {}) 32 for field_name, field_object in obj.fields.items(): 33 field_resolver = type_resolver.get(field_name, default_resolver) 34 field_object.resolver = field_resolver 35 36 37 def add_resolve_function_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict): 38 serializer = resolvers.get(name, obj.serialize) 39 obj.serialize = serializer 40 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/ariadne/resolvers.py b/ariadne/resolvers.py --- a/ariadne/resolvers.py +++ b/ariadne/resolvers.py @@ -24,16 +24,24 @@ if isinstance(type_object, GraphQLObjectType): add_resolve_functions_to_object(type_name, type_object, resolvers) if isinstance(type_object, GraphQLScalarType): - add_resolve_function_to_scalar(type_name, type_object, resolvers) + add_resolve_functions_to_scalar(type_name, type_object, resolvers) def add_resolve_functions_to_object(name: str, obj: GraphQLObjectType, resolvers: dict): - type_resolver = resolvers.get(name, {}) + type_resolvers = resolvers.get(name, {}) for field_name, field_object in obj.fields.items(): - field_resolver = type_resolver.get(field_name, default_resolver) + field_resolver = type_resolvers.get(field_name, default_resolver) field_object.resolver = field_resolver -def add_resolve_function_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict): - serializer = resolvers.get(name, obj.serialize) - obj.serialize = serializer +def add_resolve_functions_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict): + scalar_resolvers = resolvers.get(name, {}) + + serialize = scalar_resolvers.get("serialize", obj.serialize) + obj.serialize = serialize + + parse_literal = scalar_resolvers.get("parse_literal", obj.parse_literal) + obj.parse_literal = parse_literal + + parse_value = scalar_resolvers.get("parse_value", obj.parse_value) + obj.parse_value = parse_value
{"golden_diff": "diff --git a/ariadne/resolvers.py b/ariadne/resolvers.py\n--- a/ariadne/resolvers.py\n+++ b/ariadne/resolvers.py\n@@ -24,16 +24,24 @@\n if isinstance(type_object, GraphQLObjectType):\n add_resolve_functions_to_object(type_name, type_object, resolvers)\n if isinstance(type_object, GraphQLScalarType):\n- add_resolve_function_to_scalar(type_name, type_object, resolvers)\n+ add_resolve_functions_to_scalar(type_name, type_object, resolvers)\n \n \n def add_resolve_functions_to_object(name: str, obj: GraphQLObjectType, resolvers: dict):\n- type_resolver = resolvers.get(name, {})\n+ type_resolvers = resolvers.get(name, {})\n for field_name, field_object in obj.fields.items():\n- field_resolver = type_resolver.get(field_name, default_resolver)\n+ field_resolver = type_resolvers.get(field_name, default_resolver)\n field_object.resolver = field_resolver\n \n \n-def add_resolve_function_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict):\n- serializer = resolvers.get(name, obj.serialize)\n- obj.serialize = serializer\n+def add_resolve_functions_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict):\n+ scalar_resolvers = resolvers.get(name, {})\n+\n+ serialize = scalar_resolvers.get(\"serialize\", obj.serialize)\n+ obj.serialize = serialize\n+\n+ parse_literal = scalar_resolvers.get(\"parse_literal\", obj.parse_literal)\n+ obj.parse_literal = parse_literal\n+\n+ parse_value = scalar_resolvers.get(\"parse_value\", obj.parse_value)\n+ obj.parse_value = parse_value\n", "issue": "`add_resolve_functions_to_schema` should support Scalars parse_value and parse_literal\nCurrently Ariadne Scalar support is limited to serializing python types to JSON before returning them to client, but we also want to support using custom scalars for input.\r\n\r\nOur `add_resolve_functions_to_scalar` utility could support following use-cases:\r\n\r\nCode below results in one-way only scalar:\r\n\r\n- `type_defs = {'Scalar': {'serialize': callable}}`\r\n\r\nAnd this code results in two-way scalar:\r\n\r\n- `type_defs = {'Scalar': {'serialize': callable, 'parse_value': callable, 'parse_literal': callable}}` - explicit syntax for two-directional scalar.\r\n\n", "before_files": [{"content": "from graphql import GraphQLObjectType, GraphQLScalarType, GraphQLSchema\nfrom graphql.execution.base import ResolveInfo\n\n\ndef resolve_parent_field(parent, name: str):\n if isinstance(parent, dict):\n return parent.get(name)\n return getattr(parent, name, None)\n\n\ndef default_resolver(parent, info: ResolveInfo):\n return resolve_parent_field(parent, info.field_name)\n\n\ndef resolve_to(name: str):\n def resolver(parent, *_):\n return resolve_parent_field(parent, name)\n\n return resolver\n\n\ndef add_resolve_functions_to_schema(schema: GraphQLSchema, resolvers: dict):\n for type_name, type_object in schema.get_type_map().items():\n if isinstance(type_object, GraphQLObjectType):\n add_resolve_functions_to_object(type_name, type_object, resolvers)\n if isinstance(type_object, GraphQLScalarType):\n add_resolve_function_to_scalar(type_name, type_object, resolvers)\n\n\ndef add_resolve_functions_to_object(name: str, obj: GraphQLObjectType, resolvers: dict):\n type_resolver = resolvers.get(name, {})\n for field_name, field_object in obj.fields.items():\n field_resolver = type_resolver.get(field_name, default_resolver)\n field_object.resolver = field_resolver\n\n\ndef add_resolve_function_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict):\n serializer = resolvers.get(name, obj.serialize)\n obj.serialize = serializer\n", "path": "ariadne/resolvers.py"}], "after_files": [{"content": "from graphql import GraphQLObjectType, GraphQLScalarType, GraphQLSchema\nfrom graphql.execution.base import ResolveInfo\n\n\ndef resolve_parent_field(parent, name: str):\n if isinstance(parent, dict):\n return parent.get(name)\n return getattr(parent, name, None)\n\n\ndef default_resolver(parent, info: ResolveInfo):\n return resolve_parent_field(parent, info.field_name)\n\n\ndef resolve_to(name: str):\n def resolver(parent, *_):\n return resolve_parent_field(parent, name)\n\n return resolver\n\n\ndef add_resolve_functions_to_schema(schema: GraphQLSchema, resolvers: dict):\n for type_name, type_object in schema.get_type_map().items():\n if isinstance(type_object, GraphQLObjectType):\n add_resolve_functions_to_object(type_name, type_object, resolvers)\n if isinstance(type_object, GraphQLScalarType):\n add_resolve_functions_to_scalar(type_name, type_object, resolvers)\n\n\ndef add_resolve_functions_to_object(name: str, obj: GraphQLObjectType, resolvers: dict):\n type_resolvers = resolvers.get(name, {})\n for field_name, field_object in obj.fields.items():\n field_resolver = type_resolvers.get(field_name, default_resolver)\n field_object.resolver = field_resolver\n\n\ndef add_resolve_functions_to_scalar(name: str, obj: GraphQLObjectType, resolvers: dict):\n scalar_resolvers = resolvers.get(name, {})\n\n serialize = scalar_resolvers.get(\"serialize\", obj.serialize)\n obj.serialize = serialize\n\n parse_literal = scalar_resolvers.get(\"parse_literal\", obj.parse_literal)\n obj.parse_literal = parse_literal\n\n parse_value = scalar_resolvers.get(\"parse_value\", obj.parse_value)\n obj.parse_value = parse_value\n", "path": "ariadne/resolvers.py"}]}
762
363
gh_patches_debug_36546
rasdani/github-patches
git_diff
weecology__retriever-698
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Error downloading eBird_observation data. The URL doesn't work anymore. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `try_install_all.py` Content: ``` 1 """Attempt to install all datasets into all database management systems 2 3 This module, when run, attempts to install datasets from all Retriever scripts 4 in the /scripts folder (except for those listed in IGNORE), for each engine in 5 ENGINE_LIST() from __init__.py. In other words, it runs trys to install using 6 all possible combinations of database platform and script and checks to 7 see if there are any errors. It does not check the values in the database. 8 9 """ 10 from __future__ import print_function 11 from __future__ import absolute_import 12 import os 13 import sys 14 from imp import reload 15 from retriever.lib.tools import choose_engine 16 from retriever import MODULE_LIST, ENGINE_LIST, SCRIPT_LIST 17 18 reload(sys) 19 if hasattr(sys, 'setdefaultencoding'): 20 sys.setdefaultencoding('latin-1') 21 22 MODULE_LIST = MODULE_LIST() 23 ENGINE_LIST = ENGINE_LIST() 24 if len(sys.argv) > 1: 25 ENGINE_LIST = [ 26 e for e in ENGINE_LIST 27 if e.name in sys.argv[1:] or 28 e.abbreviation in sys.argv[1:] 29 ] 30 SCRIPT_LIST = SCRIPT_LIST() 31 TEST_ENGINES = {} 32 IGNORE = ["AvianBodyMass", "FIA", "Bioclim", "PRISM", "vertnet","NPN", "mammsupertree", "eBirdOD"] 33 IGNORE = [dataset.lower() for dataset in IGNORE] 34 35 for engine in ENGINE_LIST: 36 opts = {} 37 print("** %s **" % engine.name) 38 opts["engine"] = engine.abbreviation 39 40 try: 41 TEST_ENGINES[engine.abbreviation] = choose_engine(opts) 42 TEST_ENGINES[engine.abbreviation].get_input() 43 TEST_ENGINES[engine.abbreviation].get_cursor() 44 except: 45 TEST_ENGINES[engine.abbreviation] = None 46 pass 47 48 errors = [] 49 for module in MODULE_LIST: 50 for (key, value) in list(TEST_ENGINES.items()): 51 if module.SCRIPT.shortname.lower() not in IGNORE: 52 if value != None: 53 print("==>", module.__name__, value.name, "..........", module.SCRIPT.shortname) 54 try: 55 module.SCRIPT.download(value) 56 except KeyboardInterrupt: 57 pass 58 except Exception as e: 59 print("ERROR.") 60 errors.append((key, module.__name__, e)) 61 else: 62 errors.append((key, "No connection detected......" + module.SCRIPT.shortname)) 63 64 print('') 65 if errors: 66 print("Engine, Dataset, Error") 67 for error in errors: 68 print(error) 69 else: 70 print("All tests passed") 71 ``` Path: `scripts/eBird_observation.py` Content: ``` 1 #retriever 2 """Data Retriever script for the eBird Observation Dataset""" 3 4 from retriever.lib.templates import Script 5 from retriever.lib.models import Table 6 7 8 class main(Script): 9 def __init__(self, **kwargs): 10 Script.__init__(self, **kwargs) 11 self.name = "eBird Observation Dataset" 12 self.shortname = "eBirdOD" 13 self.ref = "http://ebird.org/content/ebird/news/gbif/" 14 self.urls = {"main": "https://dataone.ornith.cornell.edu/metacat/d1/mn/v1/object/CLOEODDATA.05192014.1"} 15 self.retriever_minimum_version = '2.0.dev' 16 self.version = '1.0' 17 self.description = "A collection of observations from birders through portals managed and maintained by local partner conservation organizations" 18 19 def download(self, engine=None, debug=False): 20 data_file_name = "eBird_Observation_Dataset_2013.csv" 21 Script.download(self, engine, debug) 22 self.engine.download_files_from_archive(self.urls["main"], 23 [data_file_name], 24 filetype='gz') 25 table = (Table("main", delimiter=",")) 26 table.columns=[("BASISOFRECORD",("char", )), 27 ("INSTITUTIONCODE",("char", )), 28 ("COLLECTIONCODE",("char", )), 29 ("CATALOGNUMBER",("char", )), 30 ("OCCURRENCEID",("char", )), 31 ("RECORDEDBY",("char", )), 32 ("YEAR",("int", )), 33 ("MONTH",("int", )), 34 ("DAY",("int", )), 35 ("COUNTRY",("char", )), 36 ("STATEPROVINCE",("char", )), 37 ("COUNTY",("char", )), 38 ("DECIMALLATITUDE",("double", )), 39 ("DECIMALLONGITUDE",("double", )), 40 ("LOCALITY",("char", )), 41 ("KINGDOM",("char", )), 42 ("PHYLUM",("char", )), 43 ("CLASS",("char", )), 44 ("SPORDER",("char", )), 45 ("FAMILY",("char", )), 46 ("GENUS",("char", )), 47 ("SPECIFICEPITHET",("char", )), 48 ("SCIENTIFICNAME",("char", )), 49 ("VERNACULARNAME",("char", )), 50 ("INDIVIDUALCOUNT",("int", ))] 51 engine.table = table 52 engine.create_table() 53 engine.insert_data_from_file(engine.format_filename(data_file_name)) 54 return engine 55 56 SCRIPT = main() 57 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/scripts/eBird_observation.py b/scripts/eBird_observation.py deleted file mode 100644 --- a/scripts/eBird_observation.py +++ /dev/null @@ -1,56 +0,0 @@ -#retriever -"""Data Retriever script for the eBird Observation Dataset""" - -from retriever.lib.templates import Script -from retriever.lib.models import Table - - -class main(Script): - def __init__(self, **kwargs): - Script.__init__(self, **kwargs) - self.name = "eBird Observation Dataset" - self.shortname = "eBirdOD" - self.ref = "http://ebird.org/content/ebird/news/gbif/" - self.urls = {"main": "https://dataone.ornith.cornell.edu/metacat/d1/mn/v1/object/CLOEODDATA.05192014.1"} - self.retriever_minimum_version = '2.0.dev' - self.version = '1.0' - self.description = "A collection of observations from birders through portals managed and maintained by local partner conservation organizations" - - def download(self, engine=None, debug=False): - data_file_name = "eBird_Observation_Dataset_2013.csv" - Script.download(self, engine, debug) - self.engine.download_files_from_archive(self.urls["main"], - [data_file_name], - filetype='gz') - table = (Table("main", delimiter=",")) - table.columns=[("BASISOFRECORD",("char", )), - ("INSTITUTIONCODE",("char", )), - ("COLLECTIONCODE",("char", )), - ("CATALOGNUMBER",("char", )), - ("OCCURRENCEID",("char", )), - ("RECORDEDBY",("char", )), - ("YEAR",("int", )), - ("MONTH",("int", )), - ("DAY",("int", )), - ("COUNTRY",("char", )), - ("STATEPROVINCE",("char", )), - ("COUNTY",("char", )), - ("DECIMALLATITUDE",("double", )), - ("DECIMALLONGITUDE",("double", )), - ("LOCALITY",("char", )), - ("KINGDOM",("char", )), - ("PHYLUM",("char", )), - ("CLASS",("char", )), - ("SPORDER",("char", )), - ("FAMILY",("char", )), - ("GENUS",("char", )), - ("SPECIFICEPITHET",("char", )), - ("SCIENTIFICNAME",("char", )), - ("VERNACULARNAME",("char", )), - ("INDIVIDUALCOUNT",("int", ))] - engine.table = table - engine.create_table() - engine.insert_data_from_file(engine.format_filename(data_file_name)) - return engine - -SCRIPT = main() diff --git a/try_install_all.py b/try_install_all.py --- a/try_install_all.py +++ b/try_install_all.py @@ -29,7 +29,7 @@ ] SCRIPT_LIST = SCRIPT_LIST() TEST_ENGINES = {} -IGNORE = ["AvianBodyMass", "FIA", "Bioclim", "PRISM", "vertnet","NPN", "mammsupertree", "eBirdOD"] +IGNORE = ["AvianBodyMass", "FIA", "Bioclim", "PRISM", "vertnet","NPN", "mammsupertree"] IGNORE = [dataset.lower() for dataset in IGNORE] for engine in ENGINE_LIST:
{"golden_diff": "diff --git a/scripts/eBird_observation.py b/scripts/eBird_observation.py\ndeleted file mode 100644\n--- a/scripts/eBird_observation.py\n+++ /dev/null\n@@ -1,56 +0,0 @@\n-#retriever\n-\"\"\"Data Retriever script for the eBird Observation Dataset\"\"\"\n-\n-from retriever.lib.templates import Script\n-from retriever.lib.models import Table\n-\n-\n-class main(Script):\n- def __init__(self, **kwargs):\n- Script.__init__(self, **kwargs)\n- self.name = \"eBird Observation Dataset\"\n- self.shortname = \"eBirdOD\"\n- self.ref = \"http://ebird.org/content/ebird/news/gbif/\"\n- self.urls = {\"main\": \"https://dataone.ornith.cornell.edu/metacat/d1/mn/v1/object/CLOEODDATA.05192014.1\"}\n- self.retriever_minimum_version = '2.0.dev'\n- self.version = '1.0'\n- self.description = \"A collection of observations from birders through portals managed and maintained by local partner conservation organizations\"\n-\n- def download(self, engine=None, debug=False):\n- data_file_name = \"eBird_Observation_Dataset_2013.csv\"\n- Script.download(self, engine, debug)\n- self.engine.download_files_from_archive(self.urls[\"main\"],\n- [data_file_name],\n- filetype='gz')\n- table = (Table(\"main\", delimiter=\",\"))\n- table.columns=[(\"BASISOFRECORD\",(\"char\", )),\n- (\"INSTITUTIONCODE\",(\"char\", )),\n- (\"COLLECTIONCODE\",(\"char\", )),\n- (\"CATALOGNUMBER\",(\"char\", )),\n- (\"OCCURRENCEID\",(\"char\", )),\n- (\"RECORDEDBY\",(\"char\", )),\n- (\"YEAR\",(\"int\", )),\n- (\"MONTH\",(\"int\", )),\n- (\"DAY\",(\"int\", )),\n- (\"COUNTRY\",(\"char\", )),\n- (\"STATEPROVINCE\",(\"char\", )),\n- (\"COUNTY\",(\"char\", )),\n- (\"DECIMALLATITUDE\",(\"double\", )),\n- (\"DECIMALLONGITUDE\",(\"double\", )),\n- (\"LOCALITY\",(\"char\", )),\n- (\"KINGDOM\",(\"char\", )),\n- (\"PHYLUM\",(\"char\", )),\n- (\"CLASS\",(\"char\", )),\n- (\"SPORDER\",(\"char\", )),\n- (\"FAMILY\",(\"char\", )),\n- (\"GENUS\",(\"char\", )),\n- (\"SPECIFICEPITHET\",(\"char\", )),\n- (\"SCIENTIFICNAME\",(\"char\", )),\n- (\"VERNACULARNAME\",(\"char\", )),\n- (\"INDIVIDUALCOUNT\",(\"int\", ))]\n- engine.table = table\n- engine.create_table()\n- engine.insert_data_from_file(engine.format_filename(data_file_name))\n- return engine\n-\n-SCRIPT = main()\ndiff --git a/try_install_all.py b/try_install_all.py\n--- a/try_install_all.py\n+++ b/try_install_all.py\n@@ -29,7 +29,7 @@\n ]\n SCRIPT_LIST = SCRIPT_LIST()\n TEST_ENGINES = {}\n-IGNORE = [\"AvianBodyMass\", \"FIA\", \"Bioclim\", \"PRISM\", \"vertnet\",\"NPN\", \"mammsupertree\", \"eBirdOD\"]\n+IGNORE = [\"AvianBodyMass\", \"FIA\", \"Bioclim\", \"PRISM\", \"vertnet\",\"NPN\", \"mammsupertree\"]\n IGNORE = [dataset.lower() for dataset in IGNORE]\n \n for engine in ENGINE_LIST:\n", "issue": "Error downloading eBird_observation data.\nThe URL doesn't work anymore.\n\n", "before_files": [{"content": "\"\"\"Attempt to install all datasets into all database management systems\n\nThis module, when run, attempts to install datasets from all Retriever scripts\nin the /scripts folder (except for those listed in IGNORE), for each engine in\nENGINE_LIST() from __init__.py. In other words, it runs trys to install using\nall possible combinations of database platform and script and checks to\nsee if there are any errors. It does not check the values in the database.\n\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport os\nimport sys\nfrom imp import reload\nfrom retriever.lib.tools import choose_engine\nfrom retriever import MODULE_LIST, ENGINE_LIST, SCRIPT_LIST\n\nreload(sys)\nif hasattr(sys, 'setdefaultencoding'):\n sys.setdefaultencoding('latin-1')\n\nMODULE_LIST = MODULE_LIST()\nENGINE_LIST = ENGINE_LIST()\nif len(sys.argv) > 1:\n ENGINE_LIST = [\n e for e in ENGINE_LIST\n if e.name in sys.argv[1:] or\n e.abbreviation in sys.argv[1:]\n ]\nSCRIPT_LIST = SCRIPT_LIST()\nTEST_ENGINES = {}\nIGNORE = [\"AvianBodyMass\", \"FIA\", \"Bioclim\", \"PRISM\", \"vertnet\",\"NPN\", \"mammsupertree\", \"eBirdOD\"]\nIGNORE = [dataset.lower() for dataset in IGNORE]\n\nfor engine in ENGINE_LIST:\n opts = {}\n print(\"** %s **\" % engine.name)\n opts[\"engine\"] = engine.abbreviation\n\n try:\n TEST_ENGINES[engine.abbreviation] = choose_engine(opts)\n TEST_ENGINES[engine.abbreviation].get_input()\n TEST_ENGINES[engine.abbreviation].get_cursor()\n except:\n TEST_ENGINES[engine.abbreviation] = None\n pass\n\nerrors = []\nfor module in MODULE_LIST:\n for (key, value) in list(TEST_ENGINES.items()):\n if module.SCRIPT.shortname.lower() not in IGNORE:\n if value != None:\n print(\"==>\", module.__name__, value.name, \"..........\", module.SCRIPT.shortname)\n try:\n module.SCRIPT.download(value)\n except KeyboardInterrupt:\n pass\n except Exception as e:\n print(\"ERROR.\")\n errors.append((key, module.__name__, e))\n else:\n errors.append((key, \"No connection detected......\" + module.SCRIPT.shortname))\n\nprint('')\nif errors:\n print(\"Engine, Dataset, Error\")\n for error in errors:\n print(error)\nelse:\n print(\"All tests passed\")\n", "path": "try_install_all.py"}, {"content": "#retriever\n\"\"\"Data Retriever script for the eBird Observation Dataset\"\"\"\n\nfrom retriever.lib.templates import Script\nfrom retriever.lib.models import Table\n\n\nclass main(Script):\n def __init__(self, **kwargs):\n Script.__init__(self, **kwargs)\n self.name = \"eBird Observation Dataset\"\n self.shortname = \"eBirdOD\"\n self.ref = \"http://ebird.org/content/ebird/news/gbif/\"\n self.urls = {\"main\": \"https://dataone.ornith.cornell.edu/metacat/d1/mn/v1/object/CLOEODDATA.05192014.1\"}\n self.retriever_minimum_version = '2.0.dev'\n self.version = '1.0'\n self.description = \"A collection of observations from birders through portals managed and maintained by local partner conservation organizations\"\n\n def download(self, engine=None, debug=False):\n data_file_name = \"eBird_Observation_Dataset_2013.csv\"\n Script.download(self, engine, debug)\n self.engine.download_files_from_archive(self.urls[\"main\"],\n [data_file_name],\n filetype='gz')\n table = (Table(\"main\", delimiter=\",\"))\n table.columns=[(\"BASISOFRECORD\",(\"char\", )),\n (\"INSTITUTIONCODE\",(\"char\", )),\n (\"COLLECTIONCODE\",(\"char\", )),\n (\"CATALOGNUMBER\",(\"char\", )),\n (\"OCCURRENCEID\",(\"char\", )),\n (\"RECORDEDBY\",(\"char\", )),\n (\"YEAR\",(\"int\", )),\n (\"MONTH\",(\"int\", )),\n (\"DAY\",(\"int\", )),\n (\"COUNTRY\",(\"char\", )),\n (\"STATEPROVINCE\",(\"char\", )),\n (\"COUNTY\",(\"char\", )),\n (\"DECIMALLATITUDE\",(\"double\", )),\n (\"DECIMALLONGITUDE\",(\"double\", )),\n (\"LOCALITY\",(\"char\", )),\n (\"KINGDOM\",(\"char\", )),\n (\"PHYLUM\",(\"char\", )),\n (\"CLASS\",(\"char\", )),\n (\"SPORDER\",(\"char\", )),\n (\"FAMILY\",(\"char\", )),\n (\"GENUS\",(\"char\", )),\n (\"SPECIFICEPITHET\",(\"char\", )),\n (\"SCIENTIFICNAME\",(\"char\", )),\n (\"VERNACULARNAME\",(\"char\", )),\n (\"INDIVIDUALCOUNT\",(\"int\", ))]\n engine.table = table\n engine.create_table()\n engine.insert_data_from_file(engine.format_filename(data_file_name))\n return engine\n\nSCRIPT = main()\n", "path": "scripts/eBird_observation.py"}], "after_files": [{"content": "\"\"\"Attempt to install all datasets into all database management systems\n\nThis module, when run, attempts to install datasets from all Retriever scripts\nin the /scripts folder (except for those listed in IGNORE), for each engine in\nENGINE_LIST() from __init__.py. In other words, it runs trys to install using\nall possible combinations of database platform and script and checks to\nsee if there are any errors. It does not check the values in the database.\n\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport os\nimport sys\nfrom imp import reload\nfrom retriever.lib.tools import choose_engine\nfrom retriever import MODULE_LIST, ENGINE_LIST, SCRIPT_LIST\n\nreload(sys)\nif hasattr(sys, 'setdefaultencoding'):\n sys.setdefaultencoding('latin-1')\n\nMODULE_LIST = MODULE_LIST()\nENGINE_LIST = ENGINE_LIST()\nif len(sys.argv) > 1:\n ENGINE_LIST = [\n e for e in ENGINE_LIST\n if e.name in sys.argv[1:] or\n e.abbreviation in sys.argv[1:]\n ]\nSCRIPT_LIST = SCRIPT_LIST()\nTEST_ENGINES = {}\nIGNORE = [\"AvianBodyMass\", \"FIA\", \"Bioclim\", \"PRISM\", \"vertnet\",\"NPN\", \"mammsupertree\"]\nIGNORE = [dataset.lower() for dataset in IGNORE]\n\nfor engine in ENGINE_LIST:\n opts = {}\n print(\"** %s **\" % engine.name)\n opts[\"engine\"] = engine.abbreviation\n\n try:\n TEST_ENGINES[engine.abbreviation] = choose_engine(opts)\n TEST_ENGINES[engine.abbreviation].get_input()\n TEST_ENGINES[engine.abbreviation].get_cursor()\n except:\n TEST_ENGINES[engine.abbreviation] = None\n pass\n\nerrors = []\nfor module in MODULE_LIST:\n for (key, value) in list(TEST_ENGINES.items()):\n if module.SCRIPT.shortname.lower() not in IGNORE:\n if value != None:\n print(\"==>\", module.__name__, value.name, \"..........\", module.SCRIPT.shortname)\n try:\n module.SCRIPT.download(value)\n except KeyboardInterrupt:\n pass\n except Exception as e:\n print(\"ERROR.\")\n errors.append((key, module.__name__, e))\n else:\n errors.append((key, \"No connection detected......\" + module.SCRIPT.shortname))\n\nprint('')\nif errors:\n print(\"Engine, Dataset, Error\")\n for error in errors:\n print(error)\nelse:\n print(\"All tests passed\")\n", "path": "try_install_all.py"}, {"content": null, "path": "scripts/eBird_observation.py"}]}
1,642
820
gh_patches_debug_29119
rasdani/github-patches
git_diff
googleapis__google-cloud-python-3786
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- BigQuery: expose public helper method to convert a list of schema fields to/from a list of schema dictionaries (JSON) I've received some feedback asking how to take a schema from the client library and save it to a JSON file. One reason to do this is the [`bq` command-line tool](https://cloud.google.com/bigquery/bq-command-line-tool#creatingtablefromfile) accepts a schema file, formatted like ``` [ {"name": "name", "type": "string", "mode": "required"}, {"name": "gender", "type": "string", "mode": "nullable"}, {"name": "count", "type": "integer", "mode": "required"} ] ``` Note: this format is the same as the API representation. It would be great if our client libraries could read/write in this format. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `bigquery/google/cloud/bigquery/schema.py` Content: ``` 1 # Copyright 2015 Google Inc. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """Schemas for BigQuery tables / queries.""" 16 17 18 class SchemaField(object): 19 """Describe a single field within a table schema. 20 21 :type name: str 22 :param name: the name of the field. 23 24 :type field_type: str 25 :param field_type: the type of the field (one of 'STRING', 'INTEGER', 26 'FLOAT', 'BOOLEAN', 'TIMESTAMP' or 'RECORD'). 27 28 :type mode: str 29 :param mode: the mode of the field (one of 'NULLABLE', 'REQUIRED', 30 or 'REPEATED'). 31 32 :type description: str 33 :param description: optional description for the field. 34 35 :type fields: tuple of :class:`SchemaField` 36 :param fields: subfields (requires ``field_type`` of 'RECORD'). 37 """ 38 def __init__(self, name, field_type, mode='NULLABLE', 39 description=None, fields=()): 40 self._name = name 41 self._field_type = field_type 42 self._mode = mode 43 self._description = description 44 self._fields = tuple(fields) 45 46 @property 47 def name(self): 48 """str: The name of the field.""" 49 return self._name 50 51 @property 52 def field_type(self): 53 """str: The type of the field. 54 55 Will be one of 'STRING', 'INTEGER', 'FLOAT', 'BOOLEAN', 56 'TIMESTAMP' or 'RECORD'. 57 """ 58 return self._field_type 59 60 @property 61 def mode(self): 62 """str: The mode of the field. 63 64 Will be one of 'NULLABLE', 'REQUIRED', or 'REPEATED'. 65 """ 66 return self._mode 67 68 @property 69 def is_nullable(self): 70 """Check whether 'mode' is 'nullable'.""" 71 return self._mode == 'NULLABLE' 72 73 @property 74 def description(self): 75 """Optional[str]: Description for the field.""" 76 return self._description 77 78 @property 79 def fields(self): 80 """tuple: Subfields contained in this field. 81 82 If ``field_type`` is not 'RECORD', this property must be 83 empty / unset. 84 """ 85 return self._fields 86 87 def _key(self): 88 """A tuple key that unique-ly describes this field. 89 90 Used to compute this instance's hashcode and evaluate equality. 91 92 Returns: 93 tuple: The contents of this :class:`SchemaField`. 94 """ 95 return ( 96 self._name, 97 self._field_type.lower(), 98 self._mode, 99 self._description, 100 self._fields, 101 ) 102 103 def __eq__(self, other): 104 if not isinstance(other, SchemaField): 105 return NotImplemented 106 return self._key() == other._key() 107 108 def __ne__(self, other): 109 return not self == other 110 111 def __hash__(self): 112 return hash(self._key()) 113 114 def __repr__(self): 115 return 'SchemaField{}'.format(self._key()) 116 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/bigquery/google/cloud/bigquery/schema.py b/bigquery/google/cloud/bigquery/schema.py --- a/bigquery/google/cloud/bigquery/schema.py +++ b/bigquery/google/cloud/bigquery/schema.py @@ -43,6 +43,25 @@ self._description = description self._fields = tuple(fields) + @classmethod + def from_api_repr(cls, api_repr): + """Return a ``SchemaField`` object deserialized from a dictionary. + + Args: + api_repr (Mapping[str, str]): The serialized representation + of the SchemaField, such as what is output by + :meth:`to_api_repr`. + + Returns: + SchemaField: The ``SchemaField`` object. + """ + return cls( + field_type=api_repr['type'].upper(), + fields=[cls.from_api_repr(f) for f in api_repr.get('fields', ())], + mode=api_repr['mode'].upper(), + name=api_repr['name'], + ) + @property def name(self): """str: The name of the field.""" @@ -84,6 +103,28 @@ """ return self._fields + def to_api_repr(self): + """Return a dictionary representing this schema field. + + Returns: + dict: A dictionary representing the SchemaField in a serialized + form. + """ + # Put together the basic representation. See http://bit.ly/2hOAT5u. + answer = { + 'mode': self.mode.lower(), + 'name': self.name, + 'type': self.field_type.lower(), + } + + # If this is a RECORD type, then sub-fields are also included, + # add this to the serialized representation. + if self.field_type.upper() == 'RECORD': + answer['fields'] = [f.to_api_repr() for f in self.fields] + + # Done; return the serialized dictionary. + return answer + def _key(self): """A tuple key that unique-ly describes this field.
{"golden_diff": "diff --git a/bigquery/google/cloud/bigquery/schema.py b/bigquery/google/cloud/bigquery/schema.py\n--- a/bigquery/google/cloud/bigquery/schema.py\n+++ b/bigquery/google/cloud/bigquery/schema.py\n@@ -43,6 +43,25 @@\n self._description = description\n self._fields = tuple(fields)\n \n+ @classmethod\n+ def from_api_repr(cls, api_repr):\n+ \"\"\"Return a ``SchemaField`` object deserialized from a dictionary.\n+\n+ Args:\n+ api_repr (Mapping[str, str]): The serialized representation\n+ of the SchemaField, such as what is output by\n+ :meth:`to_api_repr`.\n+\n+ Returns:\n+ SchemaField: The ``SchemaField`` object.\n+ \"\"\"\n+ return cls(\n+ field_type=api_repr['type'].upper(),\n+ fields=[cls.from_api_repr(f) for f in api_repr.get('fields', ())],\n+ mode=api_repr['mode'].upper(),\n+ name=api_repr['name'],\n+ )\n+\n @property\n def name(self):\n \"\"\"str: The name of the field.\"\"\"\n@@ -84,6 +103,28 @@\n \"\"\"\n return self._fields\n \n+ def to_api_repr(self):\n+ \"\"\"Return a dictionary representing this schema field.\n+\n+ Returns:\n+ dict: A dictionary representing the SchemaField in a serialized\n+ form.\n+ \"\"\"\n+ # Put together the basic representation. See http://bit.ly/2hOAT5u.\n+ answer = {\n+ 'mode': self.mode.lower(),\n+ 'name': self.name,\n+ 'type': self.field_type.lower(),\n+ }\n+\n+ # If this is a RECORD type, then sub-fields are also included,\n+ # add this to the serialized representation.\n+ if self.field_type.upper() == 'RECORD':\n+ answer['fields'] = [f.to_api_repr() for f in self.fields]\n+\n+ # Done; return the serialized dictionary.\n+ return answer\n+\n def _key(self):\n \"\"\"A tuple key that unique-ly describes this field.\n", "issue": "BigQuery: expose public helper method to convert a list of schema fields to/from a list of schema dictionaries (JSON)\nI've received some feedback asking how to take a schema from the client library and save it to a JSON file. One reason to do this is the [`bq` command-line tool](https://cloud.google.com/bigquery/bq-command-line-tool#creatingtablefromfile) accepts a schema file, formatted like\r\n\r\n```\r\n[\r\n {\"name\": \"name\", \"type\": \"string\", \"mode\": \"required\"},\r\n {\"name\": \"gender\", \"type\": \"string\", \"mode\": \"nullable\"},\r\n {\"name\": \"count\", \"type\": \"integer\", \"mode\": \"required\"}\r\n]\r\n```\r\n\r\nNote: this format is the same as the API representation.\r\n\r\nIt would be great if our client libraries could read/write in this format.\r\n\r\n\n", "before_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Schemas for BigQuery tables / queries.\"\"\"\n\n\nclass SchemaField(object):\n \"\"\"Describe a single field within a table schema.\n\n :type name: str\n :param name: the name of the field.\n\n :type field_type: str\n :param field_type: the type of the field (one of 'STRING', 'INTEGER',\n 'FLOAT', 'BOOLEAN', 'TIMESTAMP' or 'RECORD').\n\n :type mode: str\n :param mode: the mode of the field (one of 'NULLABLE', 'REQUIRED',\n or 'REPEATED').\n\n :type description: str\n :param description: optional description for the field.\n\n :type fields: tuple of :class:`SchemaField`\n :param fields: subfields (requires ``field_type`` of 'RECORD').\n \"\"\"\n def __init__(self, name, field_type, mode='NULLABLE',\n description=None, fields=()):\n self._name = name\n self._field_type = field_type\n self._mode = mode\n self._description = description\n self._fields = tuple(fields)\n\n @property\n def name(self):\n \"\"\"str: The name of the field.\"\"\"\n return self._name\n\n @property\n def field_type(self):\n \"\"\"str: The type of the field.\n\n Will be one of 'STRING', 'INTEGER', 'FLOAT', 'BOOLEAN',\n 'TIMESTAMP' or 'RECORD'.\n \"\"\"\n return self._field_type\n\n @property\n def mode(self):\n \"\"\"str: The mode of the field.\n\n Will be one of 'NULLABLE', 'REQUIRED', or 'REPEATED'.\n \"\"\"\n return self._mode\n\n @property\n def is_nullable(self):\n \"\"\"Check whether 'mode' is 'nullable'.\"\"\"\n return self._mode == 'NULLABLE'\n\n @property\n def description(self):\n \"\"\"Optional[str]: Description for the field.\"\"\"\n return self._description\n\n @property\n def fields(self):\n \"\"\"tuple: Subfields contained in this field.\n\n If ``field_type`` is not 'RECORD', this property must be\n empty / unset.\n \"\"\"\n return self._fields\n\n def _key(self):\n \"\"\"A tuple key that unique-ly describes this field.\n\n Used to compute this instance's hashcode and evaluate equality.\n\n Returns:\n tuple: The contents of this :class:`SchemaField`.\n \"\"\"\n return (\n self._name,\n self._field_type.lower(),\n self._mode,\n self._description,\n self._fields,\n )\n\n def __eq__(self, other):\n if not isinstance(other, SchemaField):\n return NotImplemented\n return self._key() == other._key()\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash(self._key())\n\n def __repr__(self):\n return 'SchemaField{}'.format(self._key())\n", "path": "bigquery/google/cloud/bigquery/schema.py"}], "after_files": [{"content": "# Copyright 2015 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Schemas for BigQuery tables / queries.\"\"\"\n\n\nclass SchemaField(object):\n \"\"\"Describe a single field within a table schema.\n\n :type name: str\n :param name: the name of the field.\n\n :type field_type: str\n :param field_type: the type of the field (one of 'STRING', 'INTEGER',\n 'FLOAT', 'BOOLEAN', 'TIMESTAMP' or 'RECORD').\n\n :type mode: str\n :param mode: the mode of the field (one of 'NULLABLE', 'REQUIRED',\n or 'REPEATED').\n\n :type description: str\n :param description: optional description for the field.\n\n :type fields: tuple of :class:`SchemaField`\n :param fields: subfields (requires ``field_type`` of 'RECORD').\n \"\"\"\n def __init__(self, name, field_type, mode='NULLABLE',\n description=None, fields=()):\n self._name = name\n self._field_type = field_type\n self._mode = mode\n self._description = description\n self._fields = tuple(fields)\n\n @classmethod\n def from_api_repr(cls, api_repr):\n \"\"\"Return a ``SchemaField`` object deserialized from a dictionary.\n\n Args:\n api_repr (Mapping[str, str]): The serialized representation\n of the SchemaField, such as what is output by\n :meth:`to_api_repr`.\n\n Returns:\n SchemaField: The ``SchemaField`` object.\n \"\"\"\n return cls(\n field_type=api_repr['type'].upper(),\n fields=[cls.from_api_repr(f) for f in api_repr.get('fields', ())],\n mode=api_repr['mode'].upper(),\n name=api_repr['name'],\n )\n\n @property\n def name(self):\n \"\"\"str: The name of the field.\"\"\"\n return self._name\n\n @property\n def field_type(self):\n \"\"\"str: The type of the field.\n\n Will be one of 'STRING', 'INTEGER', 'FLOAT', 'BOOLEAN',\n 'TIMESTAMP' or 'RECORD'.\n \"\"\"\n return self._field_type\n\n @property\n def mode(self):\n \"\"\"str: The mode of the field.\n\n Will be one of 'NULLABLE', 'REQUIRED', or 'REPEATED'.\n \"\"\"\n return self._mode\n\n @property\n def is_nullable(self):\n \"\"\"Check whether 'mode' is 'nullable'.\"\"\"\n return self._mode == 'NULLABLE'\n\n @property\n def description(self):\n \"\"\"Optional[str]: Description for the field.\"\"\"\n return self._description\n\n @property\n def fields(self):\n \"\"\"tuple: Subfields contained in this field.\n\n If ``field_type`` is not 'RECORD', this property must be\n empty / unset.\n \"\"\"\n return self._fields\n\n def to_api_repr(self):\n \"\"\"Return a dictionary representing this schema field.\n\n Returns:\n dict: A dictionary representing the SchemaField in a serialized\n form.\n \"\"\"\n # Put together the basic representation. See http://bit.ly/2hOAT5u.\n answer = {\n 'mode': self.mode.lower(),\n 'name': self.name,\n 'type': self.field_type.lower(),\n }\n\n # If this is a RECORD type, then sub-fields are also included,\n # add this to the serialized representation.\n if self.field_type.upper() == 'RECORD':\n answer['fields'] = [f.to_api_repr() for f in self.fields]\n\n # Done; return the serialized dictionary.\n return answer\n\n def _key(self):\n \"\"\"A tuple key that unique-ly describes this field.\n\n Used to compute this instance's hashcode and evaluate equality.\n\n Returns:\n tuple: The contents of this :class:`SchemaField`.\n \"\"\"\n return (\n self._name,\n self._field_type.lower(),\n self._mode,\n self._description,\n self._fields,\n )\n\n def __eq__(self, other):\n if not isinstance(other, SchemaField):\n return NotImplemented\n return self._key() == other._key()\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash(self._key())\n\n def __repr__(self):\n return 'SchemaField{}'.format(self._key())\n", "path": "bigquery/google/cloud/bigquery/schema.py"}]}
1,469
468
gh_patches_debug_13145
rasdani/github-patches
git_diff
mabel-dev__opteryx-1159
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- 🧹 resync SQLoxide AST to SQL and AST visitor appear to have been added --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `opteryx/third_party/sqloxide/__init__.py` Content: ``` 1 try: 2 from .sqloxide import parse_sql 3 except ImportError as e: # pragma: no cover 4 print(e) 5 if str(e) != "PyO3 modules may only be initialized once per interpreter process": 6 raise e 7 8 __all__ = ["parse_sql"] 9 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/opteryx/third_party/sqloxide/__init__.py b/opteryx/third_party/sqloxide/__init__.py --- a/opteryx/third_party/sqloxide/__init__.py +++ b/opteryx/third_party/sqloxide/__init__.py @@ -1,8 +1,16 @@ -try: - from .sqloxide import parse_sql -except ImportError as e: # pragma: no cover - print(e) - if str(e) != "PyO3 modules may only be initialized once per interpreter process": - raise e - -__all__ = ["parse_sql"] +""" +This module provides an interface to the sqloxide library, which is responsible for parsing SQL, +restoring the Abstract Syntax Tree (AST), and performing various mutations on expressions and relations. + +For more information about sqloxide: https://github.com/wseaton/sqloxide + +This module is not from sqloxide, it is written for Opteryx. +""" + +from .sqloxide import mutate_expressions +from .sqloxide import mutate_relations +from .sqloxide import parse_sql +from .sqloxide import restore_ast + +# Explicitly define the API of this module for external consumers +__all__ = ["parse_sql", "restore_ast", "mutate_expressions", "mutate_relations"]
{"golden_diff": "diff --git a/opteryx/third_party/sqloxide/__init__.py b/opteryx/third_party/sqloxide/__init__.py\n--- a/opteryx/third_party/sqloxide/__init__.py\n+++ b/opteryx/third_party/sqloxide/__init__.py\n@@ -1,8 +1,16 @@\n-try:\n- from .sqloxide import parse_sql\n-except ImportError as e: # pragma: no cover\n- print(e)\n- if str(e) != \"PyO3 modules may only be initialized once per interpreter process\":\n- raise e\n-\n-__all__ = [\"parse_sql\"]\n+\"\"\"\n+This module provides an interface to the sqloxide library, which is responsible for parsing SQL,\n+restoring the Abstract Syntax Tree (AST), and performing various mutations on expressions and relations.\n+\n+For more information about sqloxide: https://github.com/wseaton/sqloxide\n+\n+This module is not from sqloxide, it is written for Opteryx.\n+\"\"\"\n+\n+from .sqloxide import mutate_expressions\n+from .sqloxide import mutate_relations\n+from .sqloxide import parse_sql\n+from .sqloxide import restore_ast\n+\n+# Explicitly define the API of this module for external consumers\n+__all__ = [\"parse_sql\", \"restore_ast\", \"mutate_expressions\", \"mutate_relations\"]\n", "issue": "\ud83e\uddf9 resync SQLoxide\nAST to SQL and AST visitor appear to have been added \n", "before_files": [{"content": "try:\n from .sqloxide import parse_sql\nexcept ImportError as e: # pragma: no cover\n print(e)\n if str(e) != \"PyO3 modules may only be initialized once per interpreter process\":\n raise e\n\n__all__ = [\"parse_sql\"]\n", "path": "opteryx/third_party/sqloxide/__init__.py"}], "after_files": [{"content": "\"\"\"\nThis module provides an interface to the sqloxide library, which is responsible for parsing SQL,\nrestoring the Abstract Syntax Tree (AST), and performing various mutations on expressions and relations.\n\nFor more information about sqloxide: https://github.com/wseaton/sqloxide\n\nThis module is not from sqloxide, it is written for Opteryx.\n\"\"\"\n\nfrom .sqloxide import mutate_expressions\nfrom .sqloxide import mutate_relations\nfrom .sqloxide import parse_sql\nfrom .sqloxide import restore_ast\n\n# Explicitly define the API of this module for external consumers\n__all__ = [\"parse_sql\", \"restore_ast\", \"mutate_expressions\", \"mutate_relations\"]\n", "path": "opteryx/third_party/sqloxide/__init__.py"}]}
356
311
gh_patches_debug_15830
rasdani/github-patches
git_diff
Parsl__parsl-666
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add "all" install option We have several subpackages now. I think it would be good if we had an option to install all subpackages. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setup.py` Content: ``` 1 from setuptools import setup, find_packages 2 3 with open('parsl/version.py') as f: 4 exec(f.read()) 5 6 with open('requirements.txt') as f: 7 install_requires = f.readlines() 8 9 setup( 10 name='parsl', 11 version=VERSION, 12 description='Simple data dependent workflows in Python', 13 long_description='Simple parallel workflows system for Python', 14 url='https://github.com/Parsl/parsl', 15 author='The Parsl Team', 16 author_email='[email protected]', 17 license='Apache 2.0', 18 download_url='https://github.com/Parsl/parsl/archive/{}.tar.gz'.format(VERSION), 19 package_data={'': ['LICENSE']}, 20 packages=find_packages(), 21 install_requires=install_requires, 22 scripts = ['parsl/executors/high_throughput/process_worker_pool.py', 23 'parsl/executors/extreme_scale/mpi_worker_pool.py'], 24 extras_require = { 25 'db_logging' : ['CMRESHandler', 'psutil', 'sqlalchemy'], 26 'aws' : ['boto3'], 27 'jetstream' : ['python-novaclient'], 28 'extreme_scale' : ['mpi4py'], 29 'docs' : ['nbsphinx', 'sphinx_rtd_theme'], 30 'google_cloud' : ['google-auth', 'google-api-python-client'] 31 }, 32 classifiers = [ 33 # Maturity 34 'Development Status :: 3 - Alpha', 35 # Intended audience 36 'Intended Audience :: Developers', 37 # Licence, must match with licence above 38 'License :: OSI Approved :: Apache Software License', 39 # Python versions supported 40 'Programming Language :: Python :: 3.5', 41 'Programming Language :: Python :: 3.6', 42 ], 43 keywords=['Workflows', 'Scientific computing'], 44 ) 45 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -24,10 +24,17 @@ extras_require = { 'db_logging' : ['CMRESHandler', 'psutil', 'sqlalchemy'], 'aws' : ['boto3'], - 'jetstream' : ['python-novaclient'], + # Jetstream is deprecated since the interface has not been maintained. + # 'jetstream' : ['python-novaclient'], 'extreme_scale' : ['mpi4py'], 'docs' : ['nbsphinx', 'sphinx_rtd_theme'], - 'google_cloud' : ['google-auth', 'google-api-python-client'] + 'google_cloud' : ['google-auth', 'google-api-python-client'], + 'all' : ['CMRESHandler', 'psutil', 'sqlalchemy', + 'boto3', + 'mpi4py', + 'nbsphinx', 'sphinx_rtd_theme', + 'google-auth', 'google-api-python-client'] + }, classifiers = [ # Maturity
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -24,10 +24,17 @@\n extras_require = {\n 'db_logging' : ['CMRESHandler', 'psutil', 'sqlalchemy'],\n 'aws' : ['boto3'],\n- 'jetstream' : ['python-novaclient'],\n+ # Jetstream is deprecated since the interface has not been maintained.\n+ # 'jetstream' : ['python-novaclient'],\n 'extreme_scale' : ['mpi4py'],\n 'docs' : ['nbsphinx', 'sphinx_rtd_theme'],\n- 'google_cloud' : ['google-auth', 'google-api-python-client']\n+ 'google_cloud' : ['google-auth', 'google-api-python-client'],\n+ 'all' : ['CMRESHandler', 'psutil', 'sqlalchemy',\n+ 'boto3',\n+ 'mpi4py',\n+ 'nbsphinx', 'sphinx_rtd_theme',\n+ 'google-auth', 'google-api-python-client']\n+\n },\n classifiers = [\n # Maturity\n", "issue": "Add \"all\" install option\nWe have several subpackages now. I think it would be good if we had an option to install all subpackages. \n", "before_files": [{"content": "from setuptools import setup, find_packages\n\nwith open('parsl/version.py') as f:\n exec(f.read())\n\nwith open('requirements.txt') as f:\n install_requires = f.readlines()\n\nsetup(\n name='parsl',\n version=VERSION,\n description='Simple data dependent workflows in Python',\n long_description='Simple parallel workflows system for Python',\n url='https://github.com/Parsl/parsl',\n author='The Parsl Team',\n author_email='[email protected]',\n license='Apache 2.0',\n download_url='https://github.com/Parsl/parsl/archive/{}.tar.gz'.format(VERSION),\n package_data={'': ['LICENSE']},\n packages=find_packages(),\n install_requires=install_requires,\n scripts = ['parsl/executors/high_throughput/process_worker_pool.py',\n 'parsl/executors/extreme_scale/mpi_worker_pool.py'],\n extras_require = {\n 'db_logging' : ['CMRESHandler', 'psutil', 'sqlalchemy'],\n 'aws' : ['boto3'],\n 'jetstream' : ['python-novaclient'],\n 'extreme_scale' : ['mpi4py'],\n 'docs' : ['nbsphinx', 'sphinx_rtd_theme'],\n 'google_cloud' : ['google-auth', 'google-api-python-client']\n },\n classifiers = [\n # Maturity\n 'Development Status :: 3 - Alpha',\n # Intended audience\n 'Intended Audience :: Developers',\n # Licence, must match with licence above\n 'License :: OSI Approved :: Apache Software License',\n # Python versions supported\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords=['Workflows', 'Scientific computing'],\n)\n", "path": "setup.py"}], "after_files": [{"content": "from setuptools import setup, find_packages\n\nwith open('parsl/version.py') as f:\n exec(f.read())\n\nwith open('requirements.txt') as f:\n install_requires = f.readlines()\n\nsetup(\n name='parsl',\n version=VERSION,\n description='Simple data dependent workflows in Python',\n long_description='Simple parallel workflows system for Python',\n url='https://github.com/Parsl/parsl',\n author='The Parsl Team',\n author_email='[email protected]',\n license='Apache 2.0',\n download_url='https://github.com/Parsl/parsl/archive/{}.tar.gz'.format(VERSION),\n package_data={'': ['LICENSE']},\n packages=find_packages(),\n install_requires=install_requires,\n scripts = ['parsl/executors/high_throughput/process_worker_pool.py',\n 'parsl/executors/extreme_scale/mpi_worker_pool.py'],\n extras_require = {\n 'db_logging' : ['CMRESHandler', 'psutil', 'sqlalchemy'],\n 'aws' : ['boto3'],\n # Jetstream is deprecated since the interface has not been maintained.\n # 'jetstream' : ['python-novaclient'],\n 'extreme_scale' : ['mpi4py'],\n 'docs' : ['nbsphinx', 'sphinx_rtd_theme'],\n 'google_cloud' : ['google-auth', 'google-api-python-client'],\n 'all' : ['CMRESHandler', 'psutil', 'sqlalchemy',\n 'boto3',\n 'mpi4py',\n 'nbsphinx', 'sphinx_rtd_theme',\n 'google-auth', 'google-api-python-client']\n\n },\n classifiers = [\n # Maturity\n 'Development Status :: 3 - Alpha',\n # Intended audience\n 'Intended Audience :: Developers',\n # Licence, must match with licence above\n 'License :: OSI Approved :: Apache Software License',\n # Python versions supported\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords=['Workflows', 'Scientific computing'],\n)\n", "path": "setup.py"}]}
755
244
gh_patches_debug_15111
rasdani/github-patches
git_diff
wagtail__wagtail-2621
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add default icon for TableBlock As per https://github.com/torchbox/wagtail/pull/1705#issuecomment-216053655. Best to do this after #2417 is merged, to avoid conflicts. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `wagtail/contrib/table_block/fields.py` Content: ``` 1 from __future__ import absolute_import, unicode_literals 2 3 import json 4 5 from django import forms 6 from django.template.loader import render_to_string 7 from django.utils import translation 8 from django.utils.functional import cached_property 9 10 from wagtail.utils.widgets import WidgetWithScript 11 from wagtail.wagtailcore.blocks import FieldBlock 12 13 14 class TableInput(WidgetWithScript, forms.HiddenInput): 15 16 def __init__(self, table_options=None, attrs=None): 17 self.table_options = table_options 18 super(TableInput, self).__init__(attrs=attrs) 19 20 def render(self, name, value, attrs=None): 21 original_field_html = super(TableInput, self).render(name, value, attrs) 22 return render_to_string("table_block/widgets/table.html", { 23 'original_field_html': original_field_html, 24 'attrs': attrs, 25 'value': value, 26 }) 27 28 def render_js_init(self, id_, name, value): 29 return "initTable({0}, {1});".format(json.dumps(id_), json.dumps(self.table_options)) 30 31 32 33 class TableBlock(FieldBlock): 34 def __init__(self, required=True, help_text=None, table_options=None, **kwargs): 35 # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality 36 # natively (via 'label' and 'default') 37 # CharField's 'max_length' and 'min_length' parameters are not exposed as table data needs to 38 # have arbitrary length 39 # table_options can contain any valid handsontable options: http://docs.handsontable.com/0.18.0/Options.html 40 self.field_options = {'required': required, 'help_text': help_text} 41 42 language = translation.get_language() 43 if language is not None and len(language) > 2: 44 language = language[:2] 45 46 default_table_options = { 47 'minSpareRows': 0, 48 'startRows': 3, 49 'startCols': 3, 50 'colHeaders': False, 51 'rowHeaders': False, 52 'contextMenu': True, 53 'editor': 'text', 54 'stretchH': 'all', 55 'height': 108, 56 'language': language, 57 'renderer': 'text', 58 'autoColumnSize': False, 59 } 60 if table_options is not None: 61 default_table_options.update(table_options) 62 self.table_options = default_table_options 63 super(TableBlock, self).__init__(**kwargs) 64 65 @cached_property 66 def field(self): 67 return forms.CharField(widget=TableInput(table_options=self.table_options), **self.field_options) 68 69 def value_from_form(self, value): 70 return json.loads(value) 71 72 def value_for_form(self, value): 73 return json.dumps(value) 74 75 def is_html_renderer(self): 76 return self.table_options['renderer'] == 'html' 77 78 def render(self, value): 79 template = getattr(self.meta, 'template', None) 80 if template and value: 81 table_header = value['data'][0] if value.get('data', None) and len(value['data']) > 0 and value.get('first_row_is_table_header', False) else None 82 first_col_is_header = value.get('first_col_is_header', False) 83 context = { 84 'self': value, 85 self.TEMPLATE_VAR: value, 86 'table_header': table_header, 87 'first_col_is_header': first_col_is_header, 88 'html_renderer': self.is_html_renderer(), 89 'data': value['data'][1:] if table_header else value.get('data', []) 90 } 91 return render_to_string(template, context) 92 else: 93 return self.render_basic(value) 94 95 @property 96 def media(self): 97 return forms.Media( 98 css={'all': ['table_block/css/vendor/handsontable-0.24.2.full.min.css']}, 99 js=['table_block/js/vendor/handsontable-0.24.2.full.min.js', 'table_block/js/table.js'] 100 ) 101 102 class Meta: 103 default = None 104 template = 'table_block/blocks/table.html' 105 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/wagtail/contrib/table_block/fields.py b/wagtail/contrib/table_block/fields.py --- a/wagtail/contrib/table_block/fields.py +++ b/wagtail/contrib/table_block/fields.py @@ -29,7 +29,6 @@ return "initTable({0}, {1});".format(json.dumps(id_), json.dumps(self.table_options)) - class TableBlock(FieldBlock): def __init__(self, required=True, help_text=None, table_options=None, **kwargs): # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality @@ -102,3 +101,4 @@ class Meta: default = None template = 'table_block/blocks/table.html' + icon = "table"
{"golden_diff": "diff --git a/wagtail/contrib/table_block/fields.py b/wagtail/contrib/table_block/fields.py\n--- a/wagtail/contrib/table_block/fields.py\n+++ b/wagtail/contrib/table_block/fields.py\n@@ -29,7 +29,6 @@\n return \"initTable({0}, {1});\".format(json.dumps(id_), json.dumps(self.table_options))\n \n \n-\n class TableBlock(FieldBlock):\n def __init__(self, required=True, help_text=None, table_options=None, **kwargs):\n # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality\n@@ -102,3 +101,4 @@\n class Meta:\n default = None\n template = 'table_block/blocks/table.html'\n+ icon = \"table\"\n", "issue": "Add default icon for TableBlock\nAs per https://github.com/torchbox/wagtail/pull/1705#issuecomment-216053655. Best to do this after #2417 is merged, to avoid conflicts.\n\n", "before_files": [{"content": "from __future__ import absolute_import, unicode_literals\n\nimport json\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.utils import translation\nfrom django.utils.functional import cached_property\n\nfrom wagtail.utils.widgets import WidgetWithScript\nfrom wagtail.wagtailcore.blocks import FieldBlock\n\n\nclass TableInput(WidgetWithScript, forms.HiddenInput):\n\n def __init__(self, table_options=None, attrs=None):\n self.table_options = table_options\n super(TableInput, self).__init__(attrs=attrs)\n\n def render(self, name, value, attrs=None):\n original_field_html = super(TableInput, self).render(name, value, attrs)\n return render_to_string(\"table_block/widgets/table.html\", {\n 'original_field_html': original_field_html,\n 'attrs': attrs,\n 'value': value,\n })\n\n def render_js_init(self, id_, name, value):\n return \"initTable({0}, {1});\".format(json.dumps(id_), json.dumps(self.table_options))\n\n\n\nclass TableBlock(FieldBlock):\n def __init__(self, required=True, help_text=None, table_options=None, **kwargs):\n # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality\n # natively (via 'label' and 'default')\n # CharField's 'max_length' and 'min_length' parameters are not exposed as table data needs to\n # have arbitrary length\n # table_options can contain any valid handsontable options: http://docs.handsontable.com/0.18.0/Options.html\n self.field_options = {'required': required, 'help_text': help_text}\n\n language = translation.get_language()\n if language is not None and len(language) > 2:\n language = language[:2]\n\n default_table_options = {\n 'minSpareRows': 0,\n 'startRows': 3,\n 'startCols': 3,\n 'colHeaders': False,\n 'rowHeaders': False,\n 'contextMenu': True,\n 'editor': 'text',\n 'stretchH': 'all',\n 'height': 108,\n 'language': language,\n 'renderer': 'text',\n 'autoColumnSize': False,\n }\n if table_options is not None:\n default_table_options.update(table_options)\n self.table_options = default_table_options\n super(TableBlock, self).__init__(**kwargs)\n\n @cached_property\n def field(self):\n return forms.CharField(widget=TableInput(table_options=self.table_options), **self.field_options)\n\n def value_from_form(self, value):\n return json.loads(value)\n\n def value_for_form(self, value):\n return json.dumps(value)\n\n def is_html_renderer(self):\n return self.table_options['renderer'] == 'html'\n\n def render(self, value):\n template = getattr(self.meta, 'template', None)\n if template and value:\n table_header = value['data'][0] if value.get('data', None) and len(value['data']) > 0 and value.get('first_row_is_table_header', False) else None\n first_col_is_header = value.get('first_col_is_header', False)\n context = {\n 'self': value,\n self.TEMPLATE_VAR: value,\n 'table_header': table_header,\n 'first_col_is_header': first_col_is_header,\n 'html_renderer': self.is_html_renderer(),\n 'data': value['data'][1:] if table_header else value.get('data', [])\n }\n return render_to_string(template, context)\n else:\n return self.render_basic(value)\n\n @property\n def media(self):\n return forms.Media(\n css={'all': ['table_block/css/vendor/handsontable-0.24.2.full.min.css']},\n js=['table_block/js/vendor/handsontable-0.24.2.full.min.js', 'table_block/js/table.js']\n )\n\n class Meta:\n default = None\n template = 'table_block/blocks/table.html'\n", "path": "wagtail/contrib/table_block/fields.py"}], "after_files": [{"content": "from __future__ import absolute_import, unicode_literals\n\nimport json\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.utils import translation\nfrom django.utils.functional import cached_property\n\nfrom wagtail.utils.widgets import WidgetWithScript\nfrom wagtail.wagtailcore.blocks import FieldBlock\n\n\nclass TableInput(WidgetWithScript, forms.HiddenInput):\n\n def __init__(self, table_options=None, attrs=None):\n self.table_options = table_options\n super(TableInput, self).__init__(attrs=attrs)\n\n def render(self, name, value, attrs=None):\n original_field_html = super(TableInput, self).render(name, value, attrs)\n return render_to_string(\"table_block/widgets/table.html\", {\n 'original_field_html': original_field_html,\n 'attrs': attrs,\n 'value': value,\n })\n\n def render_js_init(self, id_, name, value):\n return \"initTable({0}, {1});\".format(json.dumps(id_), json.dumps(self.table_options))\n\n\nclass TableBlock(FieldBlock):\n def __init__(self, required=True, help_text=None, table_options=None, **kwargs):\n # CharField's 'label' and 'initial' parameters are not exposed, as Block handles that functionality\n # natively (via 'label' and 'default')\n # CharField's 'max_length' and 'min_length' parameters are not exposed as table data needs to\n # have arbitrary length\n # table_options can contain any valid handsontable options: http://docs.handsontable.com/0.18.0/Options.html\n self.field_options = {'required': required, 'help_text': help_text}\n\n language = translation.get_language()\n if language is not None and len(language) > 2:\n language = language[:2]\n\n default_table_options = {\n 'minSpareRows': 0,\n 'startRows': 3,\n 'startCols': 3,\n 'colHeaders': False,\n 'rowHeaders': False,\n 'contextMenu': True,\n 'editor': 'text',\n 'stretchH': 'all',\n 'height': 108,\n 'language': language,\n 'renderer': 'text',\n 'autoColumnSize': False,\n }\n if table_options is not None:\n default_table_options.update(table_options)\n self.table_options = default_table_options\n super(TableBlock, self).__init__(**kwargs)\n\n @cached_property\n def field(self):\n return forms.CharField(widget=TableInput(table_options=self.table_options), **self.field_options)\n\n def value_from_form(self, value):\n return json.loads(value)\n\n def value_for_form(self, value):\n return json.dumps(value)\n\n def is_html_renderer(self):\n return self.table_options['renderer'] == 'html'\n\n def render(self, value):\n template = getattr(self.meta, 'template', None)\n if template and value:\n table_header = value['data'][0] if value.get('data', None) and len(value['data']) > 0 and value.get('first_row_is_table_header', False) else None\n first_col_is_header = value.get('first_col_is_header', False)\n context = {\n 'self': value,\n self.TEMPLATE_VAR: value,\n 'table_header': table_header,\n 'first_col_is_header': first_col_is_header,\n 'html_renderer': self.is_html_renderer(),\n 'data': value['data'][1:] if table_header else value.get('data', [])\n }\n return render_to_string(template, context)\n else:\n return self.render_basic(value)\n\n @property\n def media(self):\n return forms.Media(\n css={'all': ['table_block/css/vendor/handsontable-0.24.2.full.min.css']},\n js=['table_block/js/vendor/handsontable-0.24.2.full.min.js', 'table_block/js/table.js']\n )\n\n class Meta:\n default = None\n template = 'table_block/blocks/table.html'\n icon = \"table\"\n", "path": "wagtail/contrib/table_block/fields.py"}]}
1,409
180
gh_patches_debug_23780
rasdani/github-patches
git_diff
pypa__setuptools-2256
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Unexpected behavior when distutils is invoked before Setuptools TL;DR We are forced to use distutils because setuptools has broken symlink processing and this causes `distutils.errors.DistutilsClassError: command class <class '__main__.SDistCommand'> must subclass Command`. It works with `setuptools<48` and the changelog doesn't document any breaking behaviors for this version. Repro: ```console $ git clone https://github.com/ansible/ansible.git $ cd ansible $ pip install -U 'setuptools>=48' $ python setup.py sdist ``` (tried under Python 3.8) Ref: https://github.com/ansible/ansible/issues/70456 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `setuptools/distutils_patch.py` Content: ``` 1 """ 2 Ensure that the local copy of distutils is preferred over stdlib. 3 4 See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 5 for more motivation. 6 """ 7 8 import sys 9 import re 10 import os 11 import importlib 12 import warnings 13 14 15 def clear_distutils(): 16 if 'distutils' not in sys.modules: 17 return 18 warnings.warn("Setuptools is replacing distutils") 19 mods = [name for name in sys.modules if re.match(r'distutils\b', name)] 20 for name in mods: 21 del sys.modules[name] 22 23 24 def enabled(): 25 """ 26 Allow selection of distutils by environment variable. 27 """ 28 which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') 29 return which == 'local' 30 31 32 def ensure_local_distutils(): 33 clear_distutils() 34 distutils = importlib.import_module('setuptools._distutils') 35 distutils.__name__ = 'distutils' 36 sys.modules['distutils'] = distutils 37 38 # sanity check that submodules load as expected 39 core = importlib.import_module('distutils.core') 40 assert '_distutils' in core.__file__, core.__file__ 41 42 43 if enabled(): 44 ensure_local_distutils() 45 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/setuptools/distutils_patch.py b/setuptools/distutils_patch.py --- a/setuptools/distutils_patch.py +++ b/setuptools/distutils_patch.py @@ -12,10 +12,26 @@ import warnings +is_pypy = '__pypy__' in sys.builtin_module_names + + +def warn_distutils_present(): + if 'distutils' not in sys.modules: + return + if is_pypy and sys.version_info < (3, 7): + # PyPy for 3.6 unconditionally imports distutils, so bypass the warning + # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250 + return + warnings.warn( + "Distutils was imported before Setuptools. This usage is discouraged " + "and may exhibit undesirable behaviors or errors. Please use " + "Setuptools' objects directly or at least import Setuptools first.") + + def clear_distutils(): if 'distutils' not in sys.modules: return - warnings.warn("Setuptools is replacing distutils") + warnings.warn("Setuptools is replacing distutils.") mods = [name for name in sys.modules if re.match(r'distutils\b', name)] for name in mods: del sys.modules[name] @@ -40,5 +56,6 @@ assert '_distutils' in core.__file__, core.__file__ +warn_distutils_present() if enabled(): ensure_local_distutils()
{"golden_diff": "diff --git a/setuptools/distutils_patch.py b/setuptools/distutils_patch.py\n--- a/setuptools/distutils_patch.py\n+++ b/setuptools/distutils_patch.py\n@@ -12,10 +12,26 @@\n import warnings\n \n \n+is_pypy = '__pypy__' in sys.builtin_module_names\n+\n+\n+def warn_distutils_present():\n+ if 'distutils' not in sys.modules:\n+ return\n+ if is_pypy and sys.version_info < (3, 7):\n+ # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n+ # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n+ return\n+ warnings.warn(\n+ \"Distutils was imported before Setuptools. This usage is discouraged \"\n+ \"and may exhibit undesirable behaviors or errors. Please use \"\n+ \"Setuptools' objects directly or at least import Setuptools first.\")\n+\n+\n def clear_distutils():\n if 'distutils' not in sys.modules:\n return\n- warnings.warn(\"Setuptools is replacing distutils\")\n+ warnings.warn(\"Setuptools is replacing distutils.\")\n mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\n for name in mods:\n del sys.modules[name]\n@@ -40,5 +56,6 @@\n assert '_distutils' in core.__file__, core.__file__\n \n \n+warn_distutils_present()\n if enabled():\n ensure_local_distutils()\n", "issue": "Unexpected behavior when distutils is invoked before Setuptools\nTL;DR We are forced to use distutils because setuptools has broken symlink processing and this causes `distutils.errors.DistutilsClassError: command class <class '__main__.SDistCommand'> must subclass Command`.\r\n\r\nIt works with `setuptools<48` and the changelog doesn't document any breaking behaviors for this version.\r\n\r\nRepro:\r\n```console\r\n$ git clone https://github.com/ansible/ansible.git\r\n$ cd ansible\r\n$ pip install -U 'setuptools>=48'\r\n$ python setup.py sdist\r\n```\r\n(tried under Python 3.8)\r\n\r\nRef: https://github.com/ansible/ansible/issues/70456\n", "before_files": [{"content": "\"\"\"\nEnsure that the local copy of distutils is preferred over stdlib.\n\nSee https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\nfor more motivation.\n\"\"\"\n\nimport sys\nimport re\nimport os\nimport importlib\nimport warnings\n\n\ndef clear_distutils():\n if 'distutils' not in sys.modules:\n return\n warnings.warn(\"Setuptools is replacing distutils\")\n mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\n for name in mods:\n del sys.modules[name]\n\n\ndef enabled():\n \"\"\"\n Allow selection of distutils by environment variable.\n \"\"\"\n which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')\n return which == 'local'\n\n\ndef ensure_local_distutils():\n clear_distutils()\n distutils = importlib.import_module('setuptools._distutils')\n distutils.__name__ = 'distutils'\n sys.modules['distutils'] = distutils\n\n # sanity check that submodules load as expected\n core = importlib.import_module('distutils.core')\n assert '_distutils' in core.__file__, core.__file__\n\n\nif enabled():\n ensure_local_distutils()\n", "path": "setuptools/distutils_patch.py"}], "after_files": [{"content": "\"\"\"\nEnsure that the local copy of distutils is preferred over stdlib.\n\nSee https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\nfor more motivation.\n\"\"\"\n\nimport sys\nimport re\nimport os\nimport importlib\nimport warnings\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n if 'distutils' not in sys.modules:\n return\n if is_pypy and sys.version_info < (3, 7):\n # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n return\n warnings.warn(\n \"Distutils was imported before Setuptools. This usage is discouraged \"\n \"and may exhibit undesirable behaviors or errors. Please use \"\n \"Setuptools' objects directly or at least import Setuptools first.\")\n\n\ndef clear_distutils():\n if 'distutils' not in sys.modules:\n return\n warnings.warn(\"Setuptools is replacing distutils.\")\n mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\n for name in mods:\n del sys.modules[name]\n\n\ndef enabled():\n \"\"\"\n Allow selection of distutils by environment variable.\n \"\"\"\n which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')\n return which == 'local'\n\n\ndef ensure_local_distutils():\n clear_distutils()\n distutils = importlib.import_module('setuptools._distutils')\n distutils.__name__ = 'distutils'\n sys.modules['distutils'] = distutils\n\n # sanity check that submodules load as expected\n core = importlib.import_module('distutils.core')\n assert '_distutils' in core.__file__, core.__file__\n\n\nwarn_distutils_present()\nif enabled():\n ensure_local_distutils()\n", "path": "setuptools/distutils_patch.py"}]}
770
378
gh_patches_debug_3506
rasdani/github-patches
git_diff
vega__altair-692
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Two renderers with same name Working with a fresh Anaconda installation of Jupyter 3.6. Followed Altair Notebook installation instructions. Basic example (flower petals scatter plot) rendered but with JSON underneath graph (issue #634). I thought this might be due to having selected the wrong renderer., so I went to list the available renderers. `alt.renderers.names()` returns `['default', 'json', 'notebook', 'notebook']` Secretly hoping the second `notebook` renderer solves #634. In any case, I think you shouldn't be able to have two renderers with the same name. (hs teacher, maybe I'm missing something) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `altair/utils/plugin_registry.py` Content: ``` 1 from typing import Callable, Generic, List, TypeVar, Union, cast 2 3 import entrypoints 4 5 6 PluginType = TypeVar('PluginType') 7 8 9 class PluginRegistry(Generic[PluginType]): 10 """A registry for plugins. 11 12 This is a plugin registry that allows plugins to be loaded/registered 13 in two ways: 14 15 1. Through an explicit call to ``.register(name, value)``. 16 2. By looking for other Python packages that are installed and provide 17 a setuptools entry point group. 18 19 When you create an instance of this class, provide the name of the 20 entry point group to use:: 21 22 reg = PluginRegister('my_entrypoint_group') 23 24 """ 25 # this is a mapping of name to error message to allow custom error messages 26 # in case an entrypoint is not found 27 entrypoint_err_messages = {} 28 29 def __init__(self, entry_point_group: str = '', plugin_type=object) -> None: 30 """Create a PluginRegistry for a named entry point group. 31 32 Parameters 33 ========== 34 entry_point_group: str 35 The name of the entry point group. 36 plugin_type: object 37 A type that will optionally be used for runtime type checking of 38 loaded plugins using isinstance. 39 """ 40 self.entry_point_group = entry_point_group 41 self.plugin_type = plugin_type 42 self._active = None # type: None 43 self._active_name = '' # type: str 44 self._plugins = {} # type: dict 45 self._options = {} # type: dict 46 47 def register(self, name: str, value: Union[PluginType,None]) -> PluginType: 48 """Register a plugin by name and value. 49 50 This method is used for explicit registration of a plugin and shouldn't be 51 used to manage entry point managed plugins, which are auto-loaded. 52 53 Parameters 54 ========== 55 name: str 56 The name of the plugin. 57 value: PluginType or None 58 The actual plugin object to register or None to unregister that plugin. 59 60 Returns 61 ======= 62 plugin: PluginType 63 The plugin that was registered or unregistered. 64 """ 65 if value is None and name in self._plugins: 66 return self._plugins.pop(name) 67 else: 68 assert isinstance(value, self.plugin_type) 69 self._plugins[name] = value 70 return value 71 72 73 def names(self) -> List[str]: 74 """List the names of the registered and entry points plugins.""" 75 exts = list(self._plugins.keys()) 76 more_exts = [ep.name for ep in entrypoints.get_group_all(self.entry_point_group)] 77 exts.extend(more_exts) 78 return exts 79 80 81 def enable(self, name: str) -> None: 82 """Enable a plugin by name.""" 83 if name not in self._plugins: 84 try: 85 ep = entrypoints.get_single(self.entry_point_group, name) 86 except entrypoints.NoSuchEntryPoint as err: 87 if name in self.entrypoint_err_messages: 88 raise ValueError(self.entrypoint_err_messages[name]) 89 else: 90 raise 91 value = cast(PluginType, ep.load()) 92 assert isinstance(value, self.plugin_type) 93 self.register(name, value) 94 self._active_name = name 95 self._active = self._plugins[name] 96 97 @property 98 def active(self) -> str: 99 """Return the name of the currently active plugin""" 100 return self._active_name 101 102 def get(self) -> PluginType: 103 """Return the currently active plugin.""" 104 return self._active 105 106 def __repr__(self) -> str: 107 return ("{0}(active={1!r}, registered={2!r})" 108 "".format(self.__class__.__name__, 109 self._active_name, 110 list(self.names()))) 111 ``` --- END FILES --- Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks. Here is an example: ```diff diff --git a/examples/server_async.py b/examples/server_async.py --- a/examples/server_async.py +++ b/examples/server_async.py @@ -313,4 +313,4 @@ if __name__ == "__main__": - asyncio.run(run_async_server("."), debug=True) + asyncio.run(run_async_server(), debug=True) diff --git a/examples/server_sync.py b/examples/server_sync.py --- a/examples/server_sync.py +++ b/examples/server_sync.py @@ -313,5 +313,5 @@ if __name__ == "__main__": - server = run_sync_server(".") + server = run_sync_server() server.shutdown() ```
diff --git a/altair/utils/plugin_registry.py b/altair/utils/plugin_registry.py --- a/altair/utils/plugin_registry.py +++ b/altair/utils/plugin_registry.py @@ -75,7 +75,7 @@ exts = list(self._plugins.keys()) more_exts = [ep.name for ep in entrypoints.get_group_all(self.entry_point_group)] exts.extend(more_exts) - return exts + return sorted(set(exts)) def enable(self, name: str) -> None:
{"golden_diff": "diff --git a/altair/utils/plugin_registry.py b/altair/utils/plugin_registry.py\n--- a/altair/utils/plugin_registry.py\n+++ b/altair/utils/plugin_registry.py\n@@ -75,7 +75,7 @@\n exts = list(self._plugins.keys())\n more_exts = [ep.name for ep in entrypoints.get_group_all(self.entry_point_group)]\n exts.extend(more_exts)\n- return exts\n+ return sorted(set(exts))\n \n \n def enable(self, name: str) -> None:\n", "issue": "Two renderers with same name\nWorking with a fresh Anaconda installation of Jupyter 3.6. Followed Altair Notebook installation instructions. Basic example (flower petals scatter plot) rendered but with JSON underneath graph (issue #634). I thought this might be due to having selected the wrong renderer., so I went to list the available renderers. \r\n\r\n`alt.renderers.names()`\r\nreturns\r\n`['default', 'json', 'notebook', 'notebook']`\r\n\r\nSecretly hoping the second `notebook` renderer solves #634. In any case, I think you shouldn't be able to have two renderers with the same name. \r\n\r\n(hs teacher, maybe I'm missing something)\n", "before_files": [{"content": "from typing import Callable, Generic, List, TypeVar, Union, cast\n\nimport entrypoints\n\n\nPluginType = TypeVar('PluginType')\n\n\nclass PluginRegistry(Generic[PluginType]):\n \"\"\"A registry for plugins.\n\n This is a plugin registry that allows plugins to be loaded/registered\n in two ways:\n\n 1. Through an explicit call to ``.register(name, value)``.\n 2. By looking for other Python packages that are installed and provide\n a setuptools entry point group.\n\n When you create an instance of this class, provide the name of the\n entry point group to use::\n\n reg = PluginRegister('my_entrypoint_group')\n\n \"\"\"\n # this is a mapping of name to error message to allow custom error messages\n # in case an entrypoint is not found\n entrypoint_err_messages = {}\n\n def __init__(self, entry_point_group: str = '', plugin_type=object) -> None:\n \"\"\"Create a PluginRegistry for a named entry point group.\n\n Parameters\n ==========\n entry_point_group: str\n The name of the entry point group.\n plugin_type: object\n A type that will optionally be used for runtime type checking of\n loaded plugins using isinstance.\n \"\"\"\n self.entry_point_group = entry_point_group\n self.plugin_type = plugin_type\n self._active = None # type: None\n self._active_name = '' # type: str\n self._plugins = {} # type: dict\n self._options = {} # type: dict\n\n def register(self, name: str, value: Union[PluginType,None]) -> PluginType:\n \"\"\"Register a plugin by name and value.\n\n This method is used for explicit registration of a plugin and shouldn't be\n used to manage entry point managed plugins, which are auto-loaded.\n\n Parameters\n ==========\n name: str\n The name of the plugin.\n value: PluginType or None\n The actual plugin object to register or None to unregister that plugin.\n\n Returns\n =======\n plugin: PluginType\n The plugin that was registered or unregistered.\n \"\"\"\n if value is None and name in self._plugins:\n return self._plugins.pop(name)\n else:\n assert isinstance(value, self.plugin_type)\n self._plugins[name] = value\n return value\n\n\n def names(self) -> List[str]:\n \"\"\"List the names of the registered and entry points plugins.\"\"\"\n exts = list(self._plugins.keys())\n more_exts = [ep.name for ep in entrypoints.get_group_all(self.entry_point_group)]\n exts.extend(more_exts)\n return exts\n\n\n def enable(self, name: str) -> None:\n \"\"\"Enable a plugin by name.\"\"\"\n if name not in self._plugins:\n try:\n ep = entrypoints.get_single(self.entry_point_group, name)\n except entrypoints.NoSuchEntryPoint as err:\n if name in self.entrypoint_err_messages:\n raise ValueError(self.entrypoint_err_messages[name])\n else:\n raise\n value = cast(PluginType, ep.load())\n assert isinstance(value, self.plugin_type)\n self.register(name, value)\n self._active_name = name\n self._active = self._plugins[name]\n\n @property\n def active(self) -> str:\n \"\"\"Return the name of the currently active plugin\"\"\"\n return self._active_name\n\n def get(self) -> PluginType:\n \"\"\"Return the currently active plugin.\"\"\"\n return self._active\n\n def __repr__(self) -> str:\n return (\"{0}(active={1!r}, registered={2!r})\"\n \"\".format(self.__class__.__name__,\n self._active_name,\n list(self.names())))\n", "path": "altair/utils/plugin_registry.py"}], "after_files": [{"content": "from typing import Callable, Generic, List, TypeVar, Union, cast\n\nimport entrypoints\n\n\nPluginType = TypeVar('PluginType')\n\n\nclass PluginRegistry(Generic[PluginType]):\n \"\"\"A registry for plugins.\n\n This is a plugin registry that allows plugins to be loaded/registered\n in two ways:\n\n 1. Through an explicit call to ``.register(name, value)``.\n 2. By looking for other Python packages that are installed and provide\n a setuptools entry point group.\n\n When you create an instance of this class, provide the name of the\n entry point group to use::\n\n reg = PluginRegister('my_entrypoint_group')\n\n \"\"\"\n # this is a mapping of name to error message to allow custom error messages\n # in case an entrypoint is not found\n entrypoint_err_messages = {}\n\n def __init__(self, entry_point_group: str = '', plugin_type=object) -> None:\n \"\"\"Create a PluginRegistry for a named entry point group.\n\n Parameters\n ==========\n entry_point_group: str\n The name of the entry point group.\n plugin_type: object\n A type that will optionally be used for runtime type checking of\n loaded plugins using isinstance.\n \"\"\"\n self.entry_point_group = entry_point_group\n self.plugin_type = plugin_type\n self._active = None # type: None\n self._active_name = '' # type: str\n self._plugins = {} # type: dict\n self._options = {} # type: dict\n\n def register(self, name: str, value: Union[PluginType,None]) -> PluginType:\n \"\"\"Register a plugin by name and value.\n\n This method is used for explicit registration of a plugin and shouldn't be\n used to manage entry point managed plugins, which are auto-loaded.\n\n Parameters\n ==========\n name: str\n The name of the plugin.\n value: PluginType or None\n The actual plugin object to register or None to unregister that plugin.\n\n Returns\n =======\n plugin: PluginType\n The plugin that was registered or unregistered.\n \"\"\"\n if value is None and name in self._plugins:\n return self._plugins.pop(name)\n else:\n assert isinstance(value, self.plugin_type)\n self._plugins[name] = value\n return value\n\n\n def names(self) -> List[str]:\n \"\"\"List the names of the registered and entry points plugins.\"\"\"\n exts = list(self._plugins.keys())\n more_exts = [ep.name for ep in entrypoints.get_group_all(self.entry_point_group)]\n exts.extend(more_exts)\n return sorted(set(exts))\n\n\n def enable(self, name: str) -> None:\n \"\"\"Enable a plugin by name.\"\"\"\n if name not in self._plugins:\n try:\n ep = entrypoints.get_single(self.entry_point_group, name)\n except entrypoints.NoSuchEntryPoint as err:\n if name in self.entrypoint_err_messages:\n raise ValueError(self.entrypoint_err_messages[name])\n else:\n raise\n value = cast(PluginType, ep.load())\n assert isinstance(value, self.plugin_type)\n self.register(name, value)\n self._active_name = name\n self._active = self._plugins[name]\n\n @property\n def active(self) -> str:\n \"\"\"Return the name of the currently active plugin\"\"\"\n return self._active_name\n\n def get(self) -> PluginType:\n \"\"\"Return the currently active plugin.\"\"\"\n return self._active\n\n def __repr__(self) -> str:\n return (\"{0}(active={1!r}, registered={2!r})\"\n \"\".format(self.__class__.__name__,\n self._active_name,\n list(self.names())))\n", "path": "altair/utils/plugin_registry.py"}]}
1,455
119