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_11776
rasdani/github-patches
git_diff
bookwyrm-social__bookwyrm-273
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- It's possible to create a FollowRequest for a Follow that already exists Send a follow request. User accepts. Send a second follow request (eg. using an old tab) Because requests and follows are stored in separate tables it's not possible to enforce this with a constraint. Pre-checking would leave a race condition, so I guess we either need to mess with table locks or create the follow request, and then delete it if its unneeded. Can we enforce this in the pre save of the model, perhaps? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `bookwyrm/models/relationship.py` Content: ``` 1 ''' defines relationships between users ''' 2 from django.db import models 3 4 from bookwyrm import activitypub 5 from .base_model import ActivitypubMixin, ActivityMapping, BookWyrmModel 6 7 8 class UserRelationship(ActivitypubMixin, BookWyrmModel): 9 ''' many-to-many through table for followers ''' 10 user_subject = models.ForeignKey( 11 'User', 12 on_delete=models.PROTECT, 13 related_name='%(class)s_user_subject' 14 ) 15 user_object = models.ForeignKey( 16 'User', 17 on_delete=models.PROTECT, 18 related_name='%(class)s_user_object' 19 ) 20 21 class Meta: 22 ''' relationships should be unique ''' 23 abstract = True 24 constraints = [ 25 models.UniqueConstraint( 26 fields=['user_subject', 'user_object'], 27 name='%(class)s_unique' 28 ), 29 models.CheckConstraint( 30 check=~models.Q(user_subject=models.F('user_object')), 31 name='%(class)s_no_self' 32 ) 33 ] 34 35 activity_mappings = [ 36 ActivityMapping('id', 'remote_id'), 37 ActivityMapping('actor', 'user_subject'), 38 ActivityMapping('object', 'user_object'), 39 ] 40 activity_serializer = activitypub.Follow 41 42 def get_remote_id(self, status=None): 43 ''' use shelf identifier in remote_id ''' 44 status = status or 'follows' 45 base_path = self.user_subject.remote_id 46 return '%s#%s/%d' % (base_path, status, self.id) 47 48 49 def to_accept_activity(self): 50 ''' generate an Accept for this follow request ''' 51 return activitypub.Accept( 52 id=self.get_remote_id(status='accepts'), 53 actor=self.user_object.remote_id, 54 object=self.to_activity() 55 ).serialize() 56 57 58 def to_reject_activity(self): 59 ''' generate an Accept for this follow request ''' 60 return activitypub.Reject( 61 id=self.get_remote_id(status='rejects'), 62 actor=self.user_object.remote_id, 63 object=self.to_activity() 64 ).serialize() 65 66 67 class UserFollows(UserRelationship): 68 ''' Following a user ''' 69 status = 'follows' 70 71 @classmethod 72 def from_request(cls, follow_request): 73 ''' converts a follow request into a follow relationship ''' 74 return cls( 75 user_subject=follow_request.user_subject, 76 user_object=follow_request.user_object, 77 remote_id=follow_request.remote_id, 78 ) 79 80 81 class UserFollowRequest(UserRelationship): 82 ''' following a user requires manual or automatic confirmation ''' 83 status = 'follow_request' 84 85 86 class UserBlocks(UserRelationship): 87 ''' prevent another user from following you and seeing your posts ''' 88 # TODO: not implemented 89 status = 'blocks' 90 ``` --- 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/bookwyrm/models/relationship.py b/bookwyrm/models/relationship.py --- a/bookwyrm/models/relationship.py +++ b/bookwyrm/models/relationship.py @@ -82,6 +82,17 @@ ''' following a user requires manual or automatic confirmation ''' status = 'follow_request' + def save(self, *args, **kwargs): + ''' make sure the follow relationship doesn't already exist ''' + try: + UserFollows.objects.get( + user_subject=self.user_subject, + user_object=self.user_object + ) + return None + except UserFollows.DoesNotExist: + return super().save(*args, **kwargs) + class UserBlocks(UserRelationship): ''' prevent another user from following you and seeing your posts '''
{"golden_diff": "diff --git a/bookwyrm/models/relationship.py b/bookwyrm/models/relationship.py\n--- a/bookwyrm/models/relationship.py\n+++ b/bookwyrm/models/relationship.py\n@@ -82,6 +82,17 @@\n ''' following a user requires manual or automatic confirmation '''\n status = 'follow_request'\n \n+ def save(self, *args, **kwargs):\n+ ''' make sure the follow relationship doesn't already exist '''\n+ try:\n+ UserFollows.objects.get(\n+ user_subject=self.user_subject,\n+ user_object=self.user_object\n+ )\n+ return None\n+ except UserFollows.DoesNotExist:\n+ return super().save(*args, **kwargs)\n+\n \n class UserBlocks(UserRelationship):\n ''' prevent another user from following you and seeing your posts '''\n", "issue": "It's possible to create a FollowRequest for a Follow that already exists\nSend a follow request.\r\nUser accepts.\r\nSend a second follow request (eg. using an old tab)\r\n\r\nBecause requests and follows are stored in separate tables it's not possible to enforce this with a constraint. Pre-checking would leave a race condition, so I guess we either need to mess with table locks or create the follow request, and then delete it if its unneeded. Can we enforce this in the pre save of the model, perhaps?\n", "before_files": [{"content": "''' defines relationships between users '''\nfrom django.db import models\n\nfrom bookwyrm import activitypub\nfrom .base_model import ActivitypubMixin, ActivityMapping, BookWyrmModel\n\n\nclass UserRelationship(ActivitypubMixin, BookWyrmModel):\n ''' many-to-many through table for followers '''\n user_subject = models.ForeignKey(\n 'User',\n on_delete=models.PROTECT,\n related_name='%(class)s_user_subject'\n )\n user_object = models.ForeignKey(\n 'User',\n on_delete=models.PROTECT,\n related_name='%(class)s_user_object'\n )\n\n class Meta:\n ''' relationships should be unique '''\n abstract = True\n constraints = [\n models.UniqueConstraint(\n fields=['user_subject', 'user_object'],\n name='%(class)s_unique'\n ),\n models.CheckConstraint(\n check=~models.Q(user_subject=models.F('user_object')),\n name='%(class)s_no_self'\n )\n ]\n\n activity_mappings = [\n ActivityMapping('id', 'remote_id'),\n ActivityMapping('actor', 'user_subject'),\n ActivityMapping('object', 'user_object'),\n ]\n activity_serializer = activitypub.Follow\n\n def get_remote_id(self, status=None):\n ''' use shelf identifier in remote_id '''\n status = status or 'follows'\n base_path = self.user_subject.remote_id\n return '%s#%s/%d' % (base_path, status, self.id)\n\n\n def to_accept_activity(self):\n ''' generate an Accept for this follow request '''\n return activitypub.Accept(\n id=self.get_remote_id(status='accepts'),\n actor=self.user_object.remote_id,\n object=self.to_activity()\n ).serialize()\n\n\n def to_reject_activity(self):\n ''' generate an Accept for this follow request '''\n return activitypub.Reject(\n id=self.get_remote_id(status='rejects'),\n actor=self.user_object.remote_id,\n object=self.to_activity()\n ).serialize()\n\n\nclass UserFollows(UserRelationship):\n ''' Following a user '''\n status = 'follows'\n\n @classmethod\n def from_request(cls, follow_request):\n ''' converts a follow request into a follow relationship '''\n return cls(\n user_subject=follow_request.user_subject,\n user_object=follow_request.user_object,\n remote_id=follow_request.remote_id,\n )\n\n\nclass UserFollowRequest(UserRelationship):\n ''' following a user requires manual or automatic confirmation '''\n status = 'follow_request'\n\n\nclass UserBlocks(UserRelationship):\n ''' prevent another user from following you and seeing your posts '''\n # TODO: not implemented\n status = 'blocks'\n", "path": "bookwyrm/models/relationship.py"}], "after_files": [{"content": "''' defines relationships between users '''\nfrom django.db import models\n\nfrom bookwyrm import activitypub\nfrom .base_model import ActivitypubMixin, ActivityMapping, BookWyrmModel\n\n\nclass UserRelationship(ActivitypubMixin, BookWyrmModel):\n ''' many-to-many through table for followers '''\n user_subject = models.ForeignKey(\n 'User',\n on_delete=models.PROTECT,\n related_name='%(class)s_user_subject'\n )\n user_object = models.ForeignKey(\n 'User',\n on_delete=models.PROTECT,\n related_name='%(class)s_user_object'\n )\n\n class Meta:\n ''' relationships should be unique '''\n abstract = True\n constraints = [\n models.UniqueConstraint(\n fields=['user_subject', 'user_object'],\n name='%(class)s_unique'\n ),\n models.CheckConstraint(\n check=~models.Q(user_subject=models.F('user_object')),\n name='%(class)s_no_self'\n )\n ]\n\n activity_mappings = [\n ActivityMapping('id', 'remote_id'),\n ActivityMapping('actor', 'user_subject'),\n ActivityMapping('object', 'user_object'),\n ]\n activity_serializer = activitypub.Follow\n\n def get_remote_id(self, status=None):\n ''' use shelf identifier in remote_id '''\n status = status or 'follows'\n base_path = self.user_subject.remote_id\n return '%s#%s/%d' % (base_path, status, self.id)\n\n\n def to_accept_activity(self):\n ''' generate an Accept for this follow request '''\n return activitypub.Accept(\n id=self.get_remote_id(status='accepts'),\n actor=self.user_object.remote_id,\n object=self.to_activity()\n ).serialize()\n\n\n def to_reject_activity(self):\n ''' generate an Accept for this follow request '''\n return activitypub.Reject(\n id=self.get_remote_id(status='rejects'),\n actor=self.user_object.remote_id,\n object=self.to_activity()\n ).serialize()\n\n\nclass UserFollows(UserRelationship):\n ''' Following a user '''\n status = 'follows'\n\n @classmethod\n def from_request(cls, follow_request):\n ''' converts a follow request into a follow relationship '''\n return cls(\n user_subject=follow_request.user_subject,\n user_object=follow_request.user_object,\n remote_id=follow_request.remote_id,\n )\n\n\nclass UserFollowRequest(UserRelationship):\n ''' following a user requires manual or automatic confirmation '''\n status = 'follow_request'\n\n def save(self, *args, **kwargs):\n ''' make sure the follow relationship doesn't already exist '''\n try:\n UserFollows.objects.get(\n user_subject=self.user_subject,\n user_object=self.user_object\n )\n return None\n except UserFollows.DoesNotExist:\n return super().save(*args, **kwargs)\n\n\nclass UserBlocks(UserRelationship):\n ''' prevent another user from following you and seeing your posts '''\n # TODO: not implemented\n status = 'blocks'\n", "path": "bookwyrm/models/relationship.py"}]}
1,093
174
gh_patches_debug_31832
rasdani/github-patches
git_diff
pypa__virtualenv-1521
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- 20b1: problems with editable installs I've decided to try running `tox` on [all the Python projects I maintain](https://projects.gedmin.as/) with virtualenv 20.0.0b1, to check for regressions in the new beta. Three of the projects failed, all on Python 2.7: - gtimelog (python: No module named gtimelog) - irclog2html (ImportError: No module named zope.testrunner) - zodbbrowser (ImportError: No module named zope.testrunner) Here's how to reproduce the gtimelog issue: - git clone https://github.com/gtimelog/gtimelog - virtualenv -p python2.7 /tmp/venv - /tmp/venv/bin/pip install -e gtimelog --no-deps - /tmp/venv/bin/python -c 'import gtimelog' I expect: no output, the import should succeed. I get ``` Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named gtimelog ``` The `--no-deps` to pip install is there to make the test simpler and faster; I get the same failure if I do a full `pip install -e gtimelog`. I'll create a separate bug for the irclog2html/zodbbrowser issue (they're the same issue): #1518. I'm on Ubuntu 19.10. I installed virtualenv 20.0.0b1 with `pipx install --pip-args=--pre` using my system Python 3.7. `pipx runpip virtualenv list` produces ``` Package Version ------------------ -------- appdirs 1.4.3 filelock 3.0.12 importlib-metadata 1.5.0 pip 20.0.2 pkg-resources 0.0.0 setuptools 45.1.0 six 1.14.0 virtualenv 20.0.0b1 wheel 0.34.1 zipp 2.1.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: `src/virtualenv/create/via_global_ref/builtin/python2/site.py` Content: ``` 1 """ 2 A simple shim module to fix up things on Python 2 only. 3 4 Note: until we setup correctly the paths we can only import built-ins. 5 """ 6 import sys 7 8 9 def main(): 10 """Patch what needed, and invoke the original site.py""" 11 config = read_pyvenv() 12 sys.real_prefix = sys.base_prefix = config["base-prefix"] 13 sys.base_exec_prefix = config["base-exec-prefix"] 14 sys.base_executable = config["base-executable"] 15 global_site_package_enabled = config.get("include-system-site-packages", False) == "true" 16 rewrite_standard_library_sys_path() 17 disable_user_site_package() 18 load_host_site() 19 if global_site_package_enabled: 20 add_global_site_package() 21 22 23 def load_host_site(): 24 """trigger reload of site.py - now it will use the standard library instance that will take care of init""" 25 # the standard library will be the first element starting with the real prefix, not zip, must be present 26 custom_site_package_path = __file__ 27 reload(sys.modules["site"]) # noqa 28 29 # ensure that our expected site packages is on the sys.path 30 import os 31 32 site_packages = r""" 33 ___EXPECTED_SITE_PACKAGES___ 34 """ 35 import json 36 37 for path in json.loads(site_packages): 38 full_path = os.path.abspath(os.path.join(custom_site_package_path, path.encode("utf-8"))) 39 if full_path not in sys.path: 40 sys.path.append(full_path) 41 42 43 def read_pyvenv(): 44 """read pyvenv.cfg""" 45 os_sep = "\\" if sys.platform == "win32" else "/" # no os module here yet - poor mans version 46 config_file = "{}{}pyvenv.cfg".format(sys.prefix, os_sep) 47 with open(config_file) as file_handler: 48 lines = file_handler.readlines() 49 config = {} 50 for line in lines: 51 try: 52 split_at = line.index("=") 53 except ValueError: 54 continue # ignore bad/empty lines 55 else: 56 config[line[:split_at].strip()] = line[split_at + 1 :].strip() 57 return config 58 59 60 def rewrite_standard_library_sys_path(): 61 """Once this site file is loaded the standard library paths have already been set, fix them up""" 62 sep = "\\" if sys.platform == "win32" else "/" 63 exe_dir = sys.executable[: sys.executable.rfind(sep)] 64 for at, value in enumerate(sys.path): 65 # replace old sys prefix path starts with new 66 if value == exe_dir: 67 pass # don't fix the current executable location, notably on Windows this gets added 68 elif value.startswith(exe_dir): 69 # content inside the exe folder needs to remap to original executables folder 70 orig_exe_folder = sys.base_executable[: sys.base_executable.rfind(sep)] 71 value = "{}{}".format(orig_exe_folder, value[len(exe_dir) :]) 72 elif value.startswith(sys.prefix): 73 value = "{}{}".format(sys.base_prefix, value[len(sys.prefix) :]) 74 elif value.startswith(sys.exec_prefix): 75 value = "{}{}".format(sys.base_exec_prefix, value[len(sys.exec_prefix) :]) 76 sys.path[at] = value 77 78 79 def disable_user_site_package(): 80 """Flip the switch on enable user site package""" 81 # sys.flags is a c-extension type, so we cannot monkey patch it, replace it with a python class to flip it 82 sys.original_flags = sys.flags 83 84 class Flags(object): 85 def __init__(self): 86 self.__dict__ = {key: getattr(sys.flags, key) for key in dir(sys.flags) if not key.startswith("_")} 87 88 sys.flags = Flags() 89 sys.flags.no_user_site = 1 90 91 92 def add_global_site_package(): 93 """add the global site package""" 94 import site 95 96 # add user site package 97 sys.flags = sys.original_flags # restore original 98 site.ENABLE_USER_SITE = None # reset user site check 99 # add the global site package to the path - use new prefix and delegate to site.py 100 orig_prefixes = None 101 try: 102 orig_prefixes = site.PREFIXES 103 site.PREFIXES = [sys.base_prefix, sys.base_exec_prefix] 104 site.main() 105 finally: 106 site.PREFIXES = orig_prefixes 107 108 109 main() 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/src/virtualenv/create/via_global_ref/builtin/python2/site.py b/src/virtualenv/create/via_global_ref/builtin/python2/site.py --- a/src/virtualenv/create/via_global_ref/builtin/python2/site.py +++ b/src/virtualenv/create/via_global_ref/builtin/python2/site.py @@ -22,11 +22,24 @@ def load_host_site(): """trigger reload of site.py - now it will use the standard library instance that will take care of init""" - # the standard library will be the first element starting with the real prefix, not zip, must be present - custom_site_package_path = __file__ + # we have a duality here, we generate the platform and pure library path based on what distutils.install specifies + # because this is what pip will be using; the host site.py though may contain it's own pattern for where the + # platform and pure library paths should exist + + # notably on Ubuntu there's a patch for getsitepackages to point to + # - prefix + local/lib/pythonx.y/dist-packages + # - prefix + lib/pythonx.y/dist-packages + # while distutils.install.cmd still points both of these to + # - prefix + lib/python2.7/site-packages + + # to facilitate when the two match, or not we first reload the site.py, now triggering the import of host site.py, + # as this will ensure that initialization code within host site.py runs + + here = __file__ # the distutils.install patterns will be injected relative to this site.py, save it here reload(sys.modules["site"]) # noqa - # ensure that our expected site packages is on the sys.path + # and then if the distutils site packages are not on the sys.path we add them via add_site_dir; note we must add + # them by invoking add_site_dir to trigger the processing of pth files import os site_packages = r""" @@ -34,10 +47,11 @@ """ import json + add_site_dir = sys.modules["site"].addsitedir for path in json.loads(site_packages): - full_path = os.path.abspath(os.path.join(custom_site_package_path, path.encode("utf-8"))) + full_path = os.path.abspath(os.path.join(here, path.encode("utf-8"))) if full_path not in sys.path: - sys.path.append(full_path) + add_site_dir(full_path) def read_pyvenv():
{"golden_diff": "diff --git a/src/virtualenv/create/via_global_ref/builtin/python2/site.py b/src/virtualenv/create/via_global_ref/builtin/python2/site.py\n--- a/src/virtualenv/create/via_global_ref/builtin/python2/site.py\n+++ b/src/virtualenv/create/via_global_ref/builtin/python2/site.py\n@@ -22,11 +22,24 @@\n \n def load_host_site():\n \"\"\"trigger reload of site.py - now it will use the standard library instance that will take care of init\"\"\"\n- # the standard library will be the first element starting with the real prefix, not zip, must be present\n- custom_site_package_path = __file__\n+ # we have a duality here, we generate the platform and pure library path based on what distutils.install specifies\n+ # because this is what pip will be using; the host site.py though may contain it's own pattern for where the\n+ # platform and pure library paths should exist\n+\n+ # notably on Ubuntu there's a patch for getsitepackages to point to\n+ # - prefix + local/lib/pythonx.y/dist-packages\n+ # - prefix + lib/pythonx.y/dist-packages\n+ # while distutils.install.cmd still points both of these to\n+ # - prefix + lib/python2.7/site-packages\n+\n+ # to facilitate when the two match, or not we first reload the site.py, now triggering the import of host site.py,\n+ # as this will ensure that initialization code within host site.py runs\n+\n+ here = __file__ # the distutils.install patterns will be injected relative to this site.py, save it here\n reload(sys.modules[\"site\"]) # noqa\n \n- # ensure that our expected site packages is on the sys.path\n+ # and then if the distutils site packages are not on the sys.path we add them via add_site_dir; note we must add\n+ # them by invoking add_site_dir to trigger the processing of pth files\n import os\n \n site_packages = r\"\"\"\n@@ -34,10 +47,11 @@\n \"\"\"\n import json\n \n+ add_site_dir = sys.modules[\"site\"].addsitedir\n for path in json.loads(site_packages):\n- full_path = os.path.abspath(os.path.join(custom_site_package_path, path.encode(\"utf-8\")))\n+ full_path = os.path.abspath(os.path.join(here, path.encode(\"utf-8\")))\n if full_path not in sys.path:\n- sys.path.append(full_path)\n+ add_site_dir(full_path)\n \n \n def read_pyvenv():\n", "issue": "20b1: problems with editable installs\nI've decided to try running `tox` on [all the Python projects I maintain](https://projects.gedmin.as/) with virtualenv 20.0.0b1, to check for regressions in the new beta. Three of the projects failed, all on Python 2.7:\r\n\r\n- gtimelog (python: No module named gtimelog)\r\n- irclog2html (ImportError: No module named zope.testrunner)\r\n- zodbbrowser (ImportError: No module named zope.testrunner)\r\n\r\nHere's how to reproduce the gtimelog issue:\r\n\r\n- git clone https://github.com/gtimelog/gtimelog\r\n- virtualenv -p python2.7 /tmp/venv\r\n- /tmp/venv/bin/pip install -e gtimelog --no-deps\r\n- /tmp/venv/bin/python -c 'import gtimelog'\r\n\r\nI expect: no output, the import should succeed.\r\n\r\nI get\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"<string>\", line 1, in <module>\r\nImportError: No module named gtimelog\r\n```\r\n\r\nThe `--no-deps` to pip install is there to make the test simpler and faster; I get the same failure if I do a full `pip install -e gtimelog`.\r\n\r\nI'll create a separate bug for the irclog2html/zodbbrowser issue (they're the same issue): #1518.\r\n\r\n\r\nI'm on Ubuntu 19.10. I installed virtualenv 20.0.0b1 with `pipx install --pip-args=--pre` using my system Python 3.7. `pipx runpip virtualenv list` produces\r\n\r\n```\r\nPackage Version \r\n------------------ --------\r\nappdirs 1.4.3 \r\nfilelock 3.0.12 \r\nimportlib-metadata 1.5.0 \r\npip 20.0.2 \r\npkg-resources 0.0.0 \r\nsetuptools 45.1.0 \r\nsix 1.14.0 \r\nvirtualenv 20.0.0b1\r\nwheel 0.34.1 \r\nzipp 2.1.0 \r\n```\n", "before_files": [{"content": "\"\"\"\nA simple shim module to fix up things on Python 2 only.\n\nNote: until we setup correctly the paths we can only import built-ins.\n\"\"\"\nimport sys\n\n\ndef main():\n \"\"\"Patch what needed, and invoke the original site.py\"\"\"\n config = read_pyvenv()\n sys.real_prefix = sys.base_prefix = config[\"base-prefix\"]\n sys.base_exec_prefix = config[\"base-exec-prefix\"]\n sys.base_executable = config[\"base-executable\"]\n global_site_package_enabled = config.get(\"include-system-site-packages\", False) == \"true\"\n rewrite_standard_library_sys_path()\n disable_user_site_package()\n load_host_site()\n if global_site_package_enabled:\n add_global_site_package()\n\n\ndef load_host_site():\n \"\"\"trigger reload of site.py - now it will use the standard library instance that will take care of init\"\"\"\n # the standard library will be the first element starting with the real prefix, not zip, must be present\n custom_site_package_path = __file__\n reload(sys.modules[\"site\"]) # noqa\n\n # ensure that our expected site packages is on the sys.path\n import os\n\n site_packages = r\"\"\"\n ___EXPECTED_SITE_PACKAGES___\n \"\"\"\n import json\n\n for path in json.loads(site_packages):\n full_path = os.path.abspath(os.path.join(custom_site_package_path, path.encode(\"utf-8\")))\n if full_path not in sys.path:\n sys.path.append(full_path)\n\n\ndef read_pyvenv():\n \"\"\"read pyvenv.cfg\"\"\"\n os_sep = \"\\\\\" if sys.platform == \"win32\" else \"/\" # no os module here yet - poor mans version\n config_file = \"{}{}pyvenv.cfg\".format(sys.prefix, os_sep)\n with open(config_file) as file_handler:\n lines = file_handler.readlines()\n config = {}\n for line in lines:\n try:\n split_at = line.index(\"=\")\n except ValueError:\n continue # ignore bad/empty lines\n else:\n config[line[:split_at].strip()] = line[split_at + 1 :].strip()\n return config\n\n\ndef rewrite_standard_library_sys_path():\n \"\"\"Once this site file is loaded the standard library paths have already been set, fix them up\"\"\"\n sep = \"\\\\\" if sys.platform == \"win32\" else \"/\"\n exe_dir = sys.executable[: sys.executable.rfind(sep)]\n for at, value in enumerate(sys.path):\n # replace old sys prefix path starts with new\n if value == exe_dir:\n pass # don't fix the current executable location, notably on Windows this gets added\n elif value.startswith(exe_dir):\n # content inside the exe folder needs to remap to original executables folder\n orig_exe_folder = sys.base_executable[: sys.base_executable.rfind(sep)]\n value = \"{}{}\".format(orig_exe_folder, value[len(exe_dir) :])\n elif value.startswith(sys.prefix):\n value = \"{}{}\".format(sys.base_prefix, value[len(sys.prefix) :])\n elif value.startswith(sys.exec_prefix):\n value = \"{}{}\".format(sys.base_exec_prefix, value[len(sys.exec_prefix) :])\n sys.path[at] = value\n\n\ndef disable_user_site_package():\n \"\"\"Flip the switch on enable user site package\"\"\"\n # sys.flags is a c-extension type, so we cannot monkey patch it, replace it with a python class to flip it\n sys.original_flags = sys.flags\n\n class Flags(object):\n def __init__(self):\n self.__dict__ = {key: getattr(sys.flags, key) for key in dir(sys.flags) if not key.startswith(\"_\")}\n\n sys.flags = Flags()\n sys.flags.no_user_site = 1\n\n\ndef add_global_site_package():\n \"\"\"add the global site package\"\"\"\n import site\n\n # add user site package\n sys.flags = sys.original_flags # restore original\n site.ENABLE_USER_SITE = None # reset user site check\n # add the global site package to the path - use new prefix and delegate to site.py\n orig_prefixes = None\n try:\n orig_prefixes = site.PREFIXES\n site.PREFIXES = [sys.base_prefix, sys.base_exec_prefix]\n site.main()\n finally:\n site.PREFIXES = orig_prefixes\n\n\nmain()\n", "path": "src/virtualenv/create/via_global_ref/builtin/python2/site.py"}], "after_files": [{"content": "\"\"\"\nA simple shim module to fix up things on Python 2 only.\n\nNote: until we setup correctly the paths we can only import built-ins.\n\"\"\"\nimport sys\n\n\ndef main():\n \"\"\"Patch what needed, and invoke the original site.py\"\"\"\n config = read_pyvenv()\n sys.real_prefix = sys.base_prefix = config[\"base-prefix\"]\n sys.base_exec_prefix = config[\"base-exec-prefix\"]\n sys.base_executable = config[\"base-executable\"]\n global_site_package_enabled = config.get(\"include-system-site-packages\", False) == \"true\"\n rewrite_standard_library_sys_path()\n disable_user_site_package()\n load_host_site()\n if global_site_package_enabled:\n add_global_site_package()\n\n\ndef load_host_site():\n \"\"\"trigger reload of site.py - now it will use the standard library instance that will take care of init\"\"\"\n # we have a duality here, we generate the platform and pure library path based on what distutils.install specifies\n # because this is what pip will be using; the host site.py though may contain it's own pattern for where the\n # platform and pure library paths should exist\n\n # notably on Ubuntu there's a patch for getsitepackages to point to\n # - prefix + local/lib/pythonx.y/dist-packages\n # - prefix + lib/pythonx.y/dist-packages\n # while distutils.install.cmd still points both of these to\n # - prefix + lib/python2.7/site-packages\n\n # to facilitate when the two match, or not we first reload the site.py, now triggering the import of host site.py,\n # as this will ensure that initialization code within host site.py runs\n\n here = __file__ # the distutils.install patterns will be injected relative to this site.py, save it here\n reload(sys.modules[\"site\"]) # noqa\n\n # and then if the distutils site packages are not on the sys.path we add them via add_site_dir; note we must add\n # them by invoking add_site_dir to trigger the processing of pth files\n import os\n\n site_packages = r\"\"\"\n ___EXPECTED_SITE_PACKAGES___\n \"\"\"\n import json\n\n add_site_dir = sys.modules[\"site\"].addsitedir\n for path in json.loads(site_packages):\n full_path = os.path.abspath(os.path.join(here, path.encode(\"utf-8\")))\n if full_path not in sys.path:\n add_site_dir(full_path)\n\n\ndef read_pyvenv():\n \"\"\"read pyvenv.cfg\"\"\"\n os_sep = \"\\\\\" if sys.platform == \"win32\" else \"/\" # no os module here yet - poor mans version\n config_file = \"{}{}pyvenv.cfg\".format(sys.prefix, os_sep)\n with open(config_file) as file_handler:\n lines = file_handler.readlines()\n config = {}\n for line in lines:\n try:\n split_at = line.index(\"=\")\n except ValueError:\n continue # ignore bad/empty lines\n else:\n config[line[:split_at].strip()] = line[split_at + 1 :].strip()\n return config\n\n\ndef rewrite_standard_library_sys_path():\n \"\"\"Once this site file is loaded the standard library paths have already been set, fix them up\"\"\"\n sep = \"\\\\\" if sys.platform == \"win32\" else \"/\"\n exe_dir = sys.executable[: sys.executable.rfind(sep)]\n for at, value in enumerate(sys.path):\n # replace old sys prefix path starts with new\n if value == exe_dir:\n pass # don't fix the current executable location, notably on Windows this gets added\n elif value.startswith(exe_dir):\n # content inside the exe folder needs to remap to original executables folder\n orig_exe_folder = sys.base_executable[: sys.base_executable.rfind(sep)]\n value = \"{}{}\".format(orig_exe_folder, value[len(exe_dir) :])\n elif value.startswith(sys.prefix):\n value = \"{}{}\".format(sys.base_prefix, value[len(sys.prefix) :])\n elif value.startswith(sys.exec_prefix):\n value = \"{}{}\".format(sys.base_exec_prefix, value[len(sys.exec_prefix) :])\n sys.path[at] = value\n\n\ndef disable_user_site_package():\n \"\"\"Flip the switch on enable user site package\"\"\"\n # sys.flags is a c-extension type, so we cannot monkey patch it, replace it with a python class to flip it\n sys.original_flags = sys.flags\n\n class Flags(object):\n def __init__(self):\n self.__dict__ = {key: getattr(sys.flags, key) for key in dir(sys.flags) if not key.startswith(\"_\")}\n\n sys.flags = Flags()\n sys.flags.no_user_site = 1\n\n\ndef add_global_site_package():\n \"\"\"add the global site package\"\"\"\n import site\n\n # add user site package\n sys.flags = sys.original_flags # restore original\n site.ENABLE_USER_SITE = None # reset user site check\n # add the global site package to the path - use new prefix and delegate to site.py\n orig_prefixes = None\n try:\n orig_prefixes = site.PREFIXES\n site.PREFIXES = [sys.base_prefix, sys.base_exec_prefix]\n site.main()\n finally:\n site.PREFIXES = orig_prefixes\n\n\nmain()\n", "path": "src/virtualenv/create/via_global_ref/builtin/python2/site.py"}]}
1,912
565
gh_patches_debug_56973
rasdani/github-patches
git_diff
bookwyrm-social__bookwyrm-3126
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Saved lists pagination is broken **Describe the bug** Trying to move through pages of saved lists is broken. Instead, one moves back to all lists. **To Reproduce** Steps to reproduce the behavior: 1. Save enough lists to have at least two pages 2. Go to [`Lists -> Saved Lists`](https://bookwyrm.social/list/saved) 3. Click on `Next` 4. Wonder why the lists shown are not the ones you saved 5. Realize you're back on `All Lists` **Expected behavior** One should be able to paginate through saved lists **Instance** [bookwyrm.social](https://bookwyrm.social/) **Additional comments** I'm trying to dig through the code a bit, but I don't have time to setup dev environment and populate local dbs and whatever needs to be done. It might just be that `path` needs to be changed to `/list/saved` [here](https://github.com/bookwyrm-social/bookwyrm/blob/6667178703b93d0d1874f1fd547e97c12a2ec144/bookwyrm/views/list/lists.py#L62)? But idk, this isn't a stack I'm very intimate with 🤷 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `bookwyrm/views/list/lists.py` Content: ``` 1 """ book list views""" 2 from django.contrib.auth.decorators import login_required 3 from django.core.paginator import Paginator 4 from django.shortcuts import redirect 5 from django.template.response import TemplateResponse 6 from django.utils.decorators import method_decorator 7 from django.views import View 8 9 from bookwyrm import forms, models 10 from bookwyrm.lists_stream import ListsStream 11 from bookwyrm.views.helpers import get_user_from_username 12 13 14 # pylint: disable=no-self-use 15 class Lists(View): 16 """book list page""" 17 18 def get(self, request): 19 """display a book list""" 20 if request.user.is_authenticated: 21 lists = ListsStream().get_list_stream(request.user) 22 else: 23 lists = models.List.objects.filter(privacy="public") 24 paginated = Paginator(lists, 12) 25 data = { 26 "lists": paginated.get_page(request.GET.get("page")), 27 "list_form": forms.ListForm(), 28 "path": "/list", 29 } 30 return TemplateResponse(request, "lists/lists.html", data) 31 32 @method_decorator(login_required, name="dispatch") 33 # pylint: disable=unused-argument 34 def post(self, request): 35 """create a book_list""" 36 form = forms.ListForm(request.POST) 37 if not form.is_valid(): 38 return redirect("lists") 39 book_list = form.save(request, commit=False) 40 41 # list should not have a group if it is not group curated 42 if not book_list.curation == "group": 43 book_list.group = None 44 book_list.save() 45 46 return redirect(book_list.local_path) 47 48 49 @method_decorator(login_required, name="dispatch") 50 class SavedLists(View): 51 """saved book list page""" 52 53 def get(self, request): 54 """display book lists""" 55 # hide lists with no approved books 56 lists = request.user.saved_lists.order_by("-updated_date") 57 58 paginated = Paginator(lists, 12) 59 data = { 60 "lists": paginated.get_page(request.GET.get("page")), 61 "list_form": forms.ListForm(), 62 "path": "/list", 63 } 64 return TemplateResponse(request, "lists/lists.html", data) 65 66 67 @method_decorator(login_required, name="dispatch") 68 class UserLists(View): 69 """a user's book list page""" 70 71 def get(self, request, username): 72 """display a book list""" 73 user = get_user_from_username(request.user, username) 74 lists = models.List.privacy_filter(request.user).filter(user=user) 75 paginated = Paginator(lists, 12) 76 77 data = { 78 "user": user, 79 "is_self": request.user.id == user.id, 80 "lists": paginated.get_page(request.GET.get("page")), 81 "list_form": forms.ListForm(), 82 "path": user.local_path + "/lists", 83 } 84 return TemplateResponse(request, "user/lists.html", data) 85 ``` --- 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/bookwyrm/views/list/lists.py b/bookwyrm/views/list/lists.py --- a/bookwyrm/views/list/lists.py +++ b/bookwyrm/views/list/lists.py @@ -59,7 +59,7 @@ data = { "lists": paginated.get_page(request.GET.get("page")), "list_form": forms.ListForm(), - "path": "/list", + "path": "/list/saved", } return TemplateResponse(request, "lists/lists.html", data)
{"golden_diff": "diff --git a/bookwyrm/views/list/lists.py b/bookwyrm/views/list/lists.py\n--- a/bookwyrm/views/list/lists.py\n+++ b/bookwyrm/views/list/lists.py\n@@ -59,7 +59,7 @@\n data = {\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n- \"path\": \"/list\",\n+ \"path\": \"/list/saved\",\n }\n return TemplateResponse(request, \"lists/lists.html\", data)\n", "issue": "Saved lists pagination is broken\n**Describe the bug**\r\nTrying to move through pages of saved lists is broken. Instead, one moves back to all lists.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Save enough lists to have at least two pages\r\n2. Go to [`Lists -> Saved Lists`](https://bookwyrm.social/list/saved)\r\n3. Click on `Next`\r\n4. Wonder why the lists shown are not the ones you saved\r\n5. Realize you're back on `All Lists`\r\n\r\n**Expected behavior**\r\nOne should be able to paginate through saved lists\r\n\r\n**Instance**\r\n[bookwyrm.social](https://bookwyrm.social/)\r\n\r\n**Additional comments**\r\nI'm trying to dig through the code a bit, but I don't have time to setup dev environment and populate local dbs and whatever needs to be done. It might just be that `path` needs to be changed to `/list/saved` [here](https://github.com/bookwyrm-social/bookwyrm/blob/6667178703b93d0d1874f1fd547e97c12a2ec144/bookwyrm/views/list/lists.py#L62)? But idk, this isn't a stack I'm very intimate with \ud83e\udd37\r\n\n", "before_files": [{"content": "\"\"\" book list views\"\"\"\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom bookwyrm import forms, models\nfrom bookwyrm.lists_stream import ListsStream\nfrom bookwyrm.views.helpers import get_user_from_username\n\n\n# pylint: disable=no-self-use\nclass Lists(View):\n \"\"\"book list page\"\"\"\n\n def get(self, request):\n \"\"\"display a book list\"\"\"\n if request.user.is_authenticated:\n lists = ListsStream().get_list_stream(request.user)\n else:\n lists = models.List.objects.filter(privacy=\"public\")\n paginated = Paginator(lists, 12)\n data = {\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": \"/list\",\n }\n return TemplateResponse(request, \"lists/lists.html\", data)\n\n @method_decorator(login_required, name=\"dispatch\")\n # pylint: disable=unused-argument\n def post(self, request):\n \"\"\"create a book_list\"\"\"\n form = forms.ListForm(request.POST)\n if not form.is_valid():\n return redirect(\"lists\")\n book_list = form.save(request, commit=False)\n\n # list should not have a group if it is not group curated\n if not book_list.curation == \"group\":\n book_list.group = None\n book_list.save()\n\n return redirect(book_list.local_path)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass SavedLists(View):\n \"\"\"saved book list page\"\"\"\n\n def get(self, request):\n \"\"\"display book lists\"\"\"\n # hide lists with no approved books\n lists = request.user.saved_lists.order_by(\"-updated_date\")\n\n paginated = Paginator(lists, 12)\n data = {\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": \"/list\",\n }\n return TemplateResponse(request, \"lists/lists.html\", data)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UserLists(View):\n \"\"\"a user's book list page\"\"\"\n\n def get(self, request, username):\n \"\"\"display a book list\"\"\"\n user = get_user_from_username(request.user, username)\n lists = models.List.privacy_filter(request.user).filter(user=user)\n paginated = Paginator(lists, 12)\n\n data = {\n \"user\": user,\n \"is_self\": request.user.id == user.id,\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": user.local_path + \"/lists\",\n }\n return TemplateResponse(request, \"user/lists.html\", data)\n", "path": "bookwyrm/views/list/lists.py"}], "after_files": [{"content": "\"\"\" book list views\"\"\"\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom bookwyrm import forms, models\nfrom bookwyrm.lists_stream import ListsStream\nfrom bookwyrm.views.helpers import get_user_from_username\n\n\n# pylint: disable=no-self-use\nclass Lists(View):\n \"\"\"book list page\"\"\"\n\n def get(self, request):\n \"\"\"display a book list\"\"\"\n if request.user.is_authenticated:\n lists = ListsStream().get_list_stream(request.user)\n else:\n lists = models.List.objects.filter(privacy=\"public\")\n paginated = Paginator(lists, 12)\n data = {\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": \"/list\",\n }\n return TemplateResponse(request, \"lists/lists.html\", data)\n\n @method_decorator(login_required, name=\"dispatch\")\n # pylint: disable=unused-argument\n def post(self, request):\n \"\"\"create a book_list\"\"\"\n form = forms.ListForm(request.POST)\n if not form.is_valid():\n return redirect(\"lists\")\n book_list = form.save(request, commit=False)\n\n # list should not have a group if it is not group curated\n if not book_list.curation == \"group\":\n book_list.group = None\n book_list.save()\n\n return redirect(book_list.local_path)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass SavedLists(View):\n \"\"\"saved book list page\"\"\"\n\n def get(self, request):\n \"\"\"display book lists\"\"\"\n # hide lists with no approved books\n lists = request.user.saved_lists.order_by(\"-updated_date\")\n\n paginated = Paginator(lists, 12)\n data = {\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": \"/list/saved\",\n }\n return TemplateResponse(request, \"lists/lists.html\", data)\n\n\n@method_decorator(login_required, name=\"dispatch\")\nclass UserLists(View):\n \"\"\"a user's book list page\"\"\"\n\n def get(self, request, username):\n \"\"\"display a book list\"\"\"\n user = get_user_from_username(request.user, username)\n lists = models.List.privacy_filter(request.user).filter(user=user)\n paginated = Paginator(lists, 12)\n\n data = {\n \"user\": user,\n \"is_self\": request.user.id == user.id,\n \"lists\": paginated.get_page(request.GET.get(\"page\")),\n \"list_form\": forms.ListForm(),\n \"path\": user.local_path + \"/lists\",\n }\n return TemplateResponse(request, \"user/lists.html\", data)\n", "path": "bookwyrm/views/list/lists.py"}]}
1,304
112
gh_patches_debug_1469
rasdani/github-patches
git_diff
microsoft__DeepSpeed-5577
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [BUG] fp_quantizer is not correctly built when non-jit installation **Describe the bug** fp_quantizer is not correctly built when non-jit installation. **To Reproduce** Steps to reproduce the behavior: ``` DS_BUILD_FP_QUANTIZER=1 pip install deepspeed ``` install will succeed but ``` from deepspeed.ops.fp_quantizer import FP_Quantize FP_Quantize() ``` will raise `ImportError: dynamic module does not define module export function (PyInit_fp_quantizer_op)` **Expected behavior** Renaming csrc/fp_quantizer/quantize.cu may solve the issue. This restriction seems to be cause of the bug. > Note that setuptools cannot handle files with the same name but different extensions https://pytorch.org/tutorials/advanced/cpp_extension.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: `op_builder/fp_quantizer.py` Content: ``` 1 # Copyright (c) Microsoft Corporation. 2 # SPDX-License-Identifier: Apache-2.0 3 4 # DeepSpeed Team 5 6 from .builder import CUDAOpBuilder, installed_cuda_version 7 8 9 class FPQuantizerBuilder(CUDAOpBuilder): 10 BUILD_VAR = "DS_BUILD_FP_QUANTIZER" 11 NAME = "fp_quantizer" 12 13 def __init__(self, name=None): 14 name = self.NAME if name is None else name 15 super().__init__(name=name) 16 17 def absolute_name(self): 18 return f'deepspeed.ops.fp_quantizer.{self.NAME}_op' 19 20 def is_compatible(self, verbose=True): 21 try: 22 import torch 23 except ImportError: 24 self.warning("Please install torch if trying to pre-compile inference kernels") 25 return False 26 27 cuda_okay = True 28 if not self.is_rocm_pytorch() and torch.cuda.is_available(): #ignore-cuda 29 sys_cuda_major, _ = installed_cuda_version() 30 torch_cuda_major = int(torch.version.cuda.split('.')[0]) 31 cuda_capability = torch.cuda.get_device_properties(0).major #ignore-cuda 32 if cuda_capability < 8: 33 self.warning("NVIDIA Inference is only supported on Ampere and newer architectures") 34 cuda_okay = False 35 if cuda_capability >= 8: 36 if torch_cuda_major < 11 or sys_cuda_major < 11: 37 self.warning("On Ampere and higher architectures please use CUDA 11+") 38 cuda_okay = False 39 return super().is_compatible(verbose) and cuda_okay 40 41 def filter_ccs(self, ccs): 42 ccs_retained = [] 43 ccs_pruned = [] 44 for cc in ccs: 45 if int(cc[0]) >= 8: 46 ccs_retained.append(cc) 47 else: 48 ccs_pruned.append(cc) 49 if len(ccs_pruned) > 0: 50 self.warning(f"Filtered compute capabilities {ccs_pruned}") 51 return ccs_retained 52 53 def sources(self): 54 return [ 55 "csrc/fp_quantizer/quantize.cu", 56 "csrc/fp_quantizer/quantize.cpp", 57 ] 58 59 def extra_ldflags(self): 60 return ['-lcurand'] 61 62 def include_paths(self): 63 return ['csrc/fp_quantizer/includes', 'csrc/includes'] 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/op_builder/fp_quantizer.py b/op_builder/fp_quantizer.py --- a/op_builder/fp_quantizer.py +++ b/op_builder/fp_quantizer.py @@ -52,8 +52,8 @@ def sources(self): return [ - "csrc/fp_quantizer/quantize.cu", - "csrc/fp_quantizer/quantize.cpp", + "csrc/fp_quantizer/fp_quantize.cu", + "csrc/fp_quantizer/fp_quantize.cpp", ] def extra_ldflags(self):
{"golden_diff": "diff --git a/op_builder/fp_quantizer.py b/op_builder/fp_quantizer.py\n--- a/op_builder/fp_quantizer.py\n+++ b/op_builder/fp_quantizer.py\n@@ -52,8 +52,8 @@\n \n def sources(self):\n return [\n- \"csrc/fp_quantizer/quantize.cu\",\n- \"csrc/fp_quantizer/quantize.cpp\",\n+ \"csrc/fp_quantizer/fp_quantize.cu\",\n+ \"csrc/fp_quantizer/fp_quantize.cpp\",\n ]\n \n def extra_ldflags(self):\n", "issue": "[BUG] fp_quantizer is not correctly built when non-jit installation\n**Describe the bug**\r\nfp_quantizer is not correctly built when non-jit installation.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n```\r\nDS_BUILD_FP_QUANTIZER=1 pip install deepspeed\r\n```\r\ninstall will succeed but\r\n```\r\nfrom deepspeed.ops.fp_quantizer import FP_Quantize\r\nFP_Quantize()\r\n```\r\nwill raise `ImportError: dynamic module does not define module export function (PyInit_fp_quantizer_op)`\r\n\r\n**Expected behavior**\r\n\r\nRenaming csrc/fp_quantizer/quantize.cu may solve the issue.\r\nThis restriction seems to be cause of the bug.\r\n> Note that setuptools cannot handle files with the same name but different extensions\r\nhttps://pytorch.org/tutorials/advanced/cpp_extension.html\r\n\n", "before_files": [{"content": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nfrom .builder import CUDAOpBuilder, installed_cuda_version\n\n\nclass FPQuantizerBuilder(CUDAOpBuilder):\n BUILD_VAR = \"DS_BUILD_FP_QUANTIZER\"\n NAME = \"fp_quantizer\"\n\n def __init__(self, name=None):\n name = self.NAME if name is None else name\n super().__init__(name=name)\n\n def absolute_name(self):\n return f'deepspeed.ops.fp_quantizer.{self.NAME}_op'\n\n def is_compatible(self, verbose=True):\n try:\n import torch\n except ImportError:\n self.warning(\"Please install torch if trying to pre-compile inference kernels\")\n return False\n\n cuda_okay = True\n if not self.is_rocm_pytorch() and torch.cuda.is_available(): #ignore-cuda\n sys_cuda_major, _ = installed_cuda_version()\n torch_cuda_major = int(torch.version.cuda.split('.')[0])\n cuda_capability = torch.cuda.get_device_properties(0).major #ignore-cuda\n if cuda_capability < 8:\n self.warning(\"NVIDIA Inference is only supported on Ampere and newer architectures\")\n cuda_okay = False\n if cuda_capability >= 8:\n if torch_cuda_major < 11 or sys_cuda_major < 11:\n self.warning(\"On Ampere and higher architectures please use CUDA 11+\")\n cuda_okay = False\n return super().is_compatible(verbose) and cuda_okay\n\n def filter_ccs(self, ccs):\n ccs_retained = []\n ccs_pruned = []\n for cc in ccs:\n if int(cc[0]) >= 8:\n ccs_retained.append(cc)\n else:\n ccs_pruned.append(cc)\n if len(ccs_pruned) > 0:\n self.warning(f\"Filtered compute capabilities {ccs_pruned}\")\n return ccs_retained\n\n def sources(self):\n return [\n \"csrc/fp_quantizer/quantize.cu\",\n \"csrc/fp_quantizer/quantize.cpp\",\n ]\n\n def extra_ldflags(self):\n return ['-lcurand']\n\n def include_paths(self):\n return ['csrc/fp_quantizer/includes', 'csrc/includes']\n", "path": "op_builder/fp_quantizer.py"}], "after_files": [{"content": "# Copyright (c) Microsoft Corporation.\n# SPDX-License-Identifier: Apache-2.0\n\n# DeepSpeed Team\n\nfrom .builder import CUDAOpBuilder, installed_cuda_version\n\n\nclass FPQuantizerBuilder(CUDAOpBuilder):\n BUILD_VAR = \"DS_BUILD_FP_QUANTIZER\"\n NAME = \"fp_quantizer\"\n\n def __init__(self, name=None):\n name = self.NAME if name is None else name\n super().__init__(name=name)\n\n def absolute_name(self):\n return f'deepspeed.ops.fp_quantizer.{self.NAME}_op'\n\n def is_compatible(self, verbose=True):\n try:\n import torch\n except ImportError:\n self.warning(\"Please install torch if trying to pre-compile inference kernels\")\n return False\n\n cuda_okay = True\n if not self.is_rocm_pytorch() and torch.cuda.is_available(): #ignore-cuda\n sys_cuda_major, _ = installed_cuda_version()\n torch_cuda_major = int(torch.version.cuda.split('.')[0])\n cuda_capability = torch.cuda.get_device_properties(0).major #ignore-cuda\n if cuda_capability < 8:\n self.warning(\"NVIDIA Inference is only supported on Ampere and newer architectures\")\n cuda_okay = False\n if cuda_capability >= 8:\n if torch_cuda_major < 11 or sys_cuda_major < 11:\n self.warning(\"On Ampere and higher architectures please use CUDA 11+\")\n cuda_okay = False\n return super().is_compatible(verbose) and cuda_okay\n\n def filter_ccs(self, ccs):\n ccs_retained = []\n ccs_pruned = []\n for cc in ccs:\n if int(cc[0]) >= 8:\n ccs_retained.append(cc)\n else:\n ccs_pruned.append(cc)\n if len(ccs_pruned) > 0:\n self.warning(f\"Filtered compute capabilities {ccs_pruned}\")\n return ccs_retained\n\n def sources(self):\n return [\n \"csrc/fp_quantizer/fp_quantize.cu\",\n \"csrc/fp_quantizer/fp_quantize.cpp\",\n ]\n\n def extra_ldflags(self):\n return ['-lcurand']\n\n def include_paths(self):\n return ['csrc/fp_quantizer/includes', 'csrc/includes']\n", "path": "op_builder/fp_quantizer.py"}]}
1,063
131
gh_patches_debug_16543
rasdani/github-patches
git_diff
web2py__web2py-1496
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- IS_EMPTY_OR validator returns incorrect "empty" value When setting default validators, the https://github.com/web2py/web2py/commit/bdbc053285b67fd3ee02f2ea862b30ca495f33e2 commit mistakenly sets the `null` attribute of the `IS_EMPTY_OR` validator to `''` for _all_ field types rather than just the string based field types. [This line](https://github.com/web2py/web2py/blob/1877f497309e71918aa78e1a1288cbe3cb5392ec/gluon/dal.py#L81): ``` requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None) ``` should instead be: ``` requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None) ``` Notice, `field.type` rather than `field`. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `gluon/dal.py` Content: ``` 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 """ 5 | This file is part of the web2py Web Framework 6 | Copyrighted by Massimo Di Pierro <[email protected]> 7 | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) 8 9 Takes care of adapting pyDAL to web2py's needs 10 ----------------------------------------------- 11 """ 12 13 from pydal import DAL as DAL 14 from pydal import Field 15 from pydal.objects import Row, Rows, Table, Query, Set, Expression 16 from pydal import SQLCustomType, geoPoint, geoLine, geoPolygon 17 18 def _default_validators(db, field): 19 """ 20 Field type validation, using web2py's validators mechanism. 21 22 makes sure the content of a field is in line with the declared 23 fieldtype 24 """ 25 from gluon import validators 26 field_type, field_length = field.type, field.length 27 requires = [] 28 29 if field_type in (('string', 'text', 'password')): 30 requires.append(validators.IS_LENGTH(field_length)) 31 elif field_type == 'json': 32 requires.append(validators.IS_EMPTY_OR(validators.IS_JSON())) 33 elif field_type == 'double' or field_type == 'float': 34 requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100)) 35 elif field_type == 'integer': 36 requires.append(validators.IS_INT_IN_RANGE(-2**31, 2**31)) 37 elif field_type == 'bigint': 38 requires.append(validators.IS_INT_IN_RANGE(-2**63, 2**63)) 39 elif field_type.startswith('decimal'): 40 requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10)) 41 elif field_type == 'date': 42 requires.append(validators.IS_DATE()) 43 elif field_type == 'time': 44 requires.append(validators.IS_TIME()) 45 elif field_type == 'datetime': 46 requires.append(validators.IS_DATETIME()) 47 elif db and field_type.startswith('reference') and \ 48 field_type.find('.') < 0 and \ 49 field_type[10:] in db.tables: 50 referenced = db[field_type[10:]] 51 if hasattr(referenced, '_format') and referenced._format: 52 requires = validators.IS_IN_DB(db, referenced._id, 53 referenced._format) 54 if field.unique: 55 requires._and = validators.IS_NOT_IN_DB(db, field) 56 if field.tablename == field_type[10:]: 57 return validators.IS_EMPTY_OR(requires) 58 return requires 59 elif db and field_type.startswith('list:reference') and \ 60 field_type.find('.') < 0 and \ 61 field_type[15:] in db.tables: 62 referenced = db[field_type[15:]] 63 if hasattr(referenced, '_format') and referenced._format: 64 requires = validators.IS_IN_DB(db, referenced._id, 65 referenced._format, multiple=True) 66 else: 67 requires = validators.IS_IN_DB(db, referenced._id, 68 multiple=True) 69 if field.unique: 70 requires._and = validators.IS_NOT_IN_DB(db, field) 71 if not field.notnull: 72 requires = validators.IS_EMPTY_OR(requires) 73 return requires 74 # does not get here for reference and list:reference 75 if field.unique: 76 requires.insert(0, validators.IS_NOT_IN_DB(db, field)) 77 excluded_fields = ['string', 'upload', 'text', 'password', 'boolean'] 78 if (field.notnull or field.unique) and not field_type in excluded_fields: 79 requires.insert(0, validators.IS_NOT_EMPTY()) 80 elif not field.notnull and not field.unique and requires: 81 requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None) 82 return requires 83 84 from gluon.serializers import custom_json, xml 85 from gluon.utils import web2py_uuid 86 from gluon import sqlhtml 87 88 89 DAL.serializers = {'json': custom_json, 'xml': xml} 90 DAL.validators_method = _default_validators 91 DAL.uuid = lambda x: web2py_uuid() 92 DAL.representers = { 93 'rows_render': sqlhtml.represent, 94 'rows_xml': sqlhtml.SQLTABLE 95 } 96 DAL.Field = Field 97 DAL.Table = Table 98 99 #: add web2py contrib drivers to pyDAL 100 from pydal.drivers import DRIVERS 101 if not DRIVERS.get('pymysql'): 102 try: 103 from .contrib import pymysql 104 DRIVERS['pymysql'] = pymysql 105 except: 106 pass 107 if not DRIVERS.get('pyodbc'): 108 try: 109 from .contrib import pypyodbc as pyodbc 110 DRIVERS['pyodbc'] = pyodbc 111 except: 112 pass 113 if not DRIVERS.get('pg8000'): 114 try: 115 from .contrib import pg8000 116 DRIVERS['pg8000'] = pg8000 117 except: 118 pass 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/gluon/dal.py b/gluon/dal.py --- a/gluon/dal.py +++ b/gluon/dal.py @@ -75,10 +75,10 @@ if field.unique: requires.insert(0, validators.IS_NOT_IN_DB(db, field)) excluded_fields = ['string', 'upload', 'text', 'password', 'boolean'] - if (field.notnull or field.unique) and not field_type in excluded_fields: + if (field.notnull or field.unique) and field_type not in excluded_fields: requires.insert(0, validators.IS_NOT_EMPTY()) elif not field.notnull and not field.unique and requires: - requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None) + requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None) return requires from gluon.serializers import custom_json, xml
{"golden_diff": "diff --git a/gluon/dal.py b/gluon/dal.py\n--- a/gluon/dal.py\n+++ b/gluon/dal.py\n@@ -75,10 +75,10 @@\n if field.unique:\n requires.insert(0, validators.IS_NOT_IN_DB(db, field))\n excluded_fields = ['string', 'upload', 'text', 'password', 'boolean']\n- if (field.notnull or field.unique) and not field_type in excluded_fields:\n+ if (field.notnull or field.unique) and field_type not in excluded_fields:\n requires.insert(0, validators.IS_NOT_EMPTY())\n elif not field.notnull and not field.unique and requires:\n- requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None)\n+ requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None)\n return requires\n \n from gluon.serializers import custom_json, xml\n", "issue": "IS_EMPTY_OR validator returns incorrect \"empty\" value\nWhen setting default validators, the https://github.com/web2py/web2py/commit/bdbc053285b67fd3ee02f2ea862b30ca495f33e2 commit mistakenly sets the `null` attribute of the `IS_EMPTY_OR` validator to `''` for _all_ field types rather than just the string based field types.\n\n[This line](https://github.com/web2py/web2py/blob/1877f497309e71918aa78e1a1288cbe3cb5392ec/gluon/dal.py#L81):\n\n```\n requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None)\n```\n\nshould instead be:\n\n```\n requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None)\n```\n\nNotice, `field.type` rather than `field`.\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n| This file is part of the web2py Web Framework\n| Copyrighted by Massimo Di Pierro <[email protected]>\n| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nTakes care of adapting pyDAL to web2py's needs\n-----------------------------------------------\n\"\"\"\n\nfrom pydal import DAL as DAL\nfrom pydal import Field\nfrom pydal.objects import Row, Rows, Table, Query, Set, Expression\nfrom pydal import SQLCustomType, geoPoint, geoLine, geoPolygon\n\ndef _default_validators(db, field):\n \"\"\"\n Field type validation, using web2py's validators mechanism.\n\n makes sure the content of a field is in line with the declared\n fieldtype\n \"\"\"\n from gluon import validators\n field_type, field_length = field.type, field.length\n requires = []\n\n if field_type in (('string', 'text', 'password')):\n requires.append(validators.IS_LENGTH(field_length))\n elif field_type == 'json':\n requires.append(validators.IS_EMPTY_OR(validators.IS_JSON()))\n elif field_type == 'double' or field_type == 'float':\n requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100))\n elif field_type == 'integer':\n requires.append(validators.IS_INT_IN_RANGE(-2**31, 2**31))\n elif field_type == 'bigint':\n requires.append(validators.IS_INT_IN_RANGE(-2**63, 2**63))\n elif field_type.startswith('decimal'):\n requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10))\n elif field_type == 'date':\n requires.append(validators.IS_DATE())\n elif field_type == 'time':\n requires.append(validators.IS_TIME())\n elif field_type == 'datetime':\n requires.append(validators.IS_DATETIME())\n elif db and field_type.startswith('reference') and \\\n field_type.find('.') < 0 and \\\n field_type[10:] in db.tables:\n referenced = db[field_type[10:]]\n if hasattr(referenced, '_format') and referenced._format:\n requires = validators.IS_IN_DB(db, referenced._id,\n referenced._format)\n if field.unique:\n requires._and = validators.IS_NOT_IN_DB(db, field)\n if field.tablename == field_type[10:]:\n return validators.IS_EMPTY_OR(requires)\n return requires\n elif db and field_type.startswith('list:reference') and \\\n field_type.find('.') < 0 and \\\n field_type[15:] in db.tables:\n referenced = db[field_type[15:]]\n if hasattr(referenced, '_format') and referenced._format:\n requires = validators.IS_IN_DB(db, referenced._id,\n referenced._format, multiple=True)\n else:\n requires = validators.IS_IN_DB(db, referenced._id,\n multiple=True)\n if field.unique:\n requires._and = validators.IS_NOT_IN_DB(db, field)\n if not field.notnull:\n requires = validators.IS_EMPTY_OR(requires)\n return requires\n # does not get here for reference and list:reference\n if field.unique:\n requires.insert(0, validators.IS_NOT_IN_DB(db, field))\n excluded_fields = ['string', 'upload', 'text', 'password', 'boolean']\n if (field.notnull or field.unique) and not field_type in excluded_fields:\n requires.insert(0, validators.IS_NOT_EMPTY())\n elif not field.notnull and not field.unique and requires:\n requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field in ('string', 'text', 'password') else None)\n return requires\n\nfrom gluon.serializers import custom_json, xml\nfrom gluon.utils import web2py_uuid\nfrom gluon import sqlhtml\n\n\nDAL.serializers = {'json': custom_json, 'xml': xml}\nDAL.validators_method = _default_validators\nDAL.uuid = lambda x: web2py_uuid()\nDAL.representers = {\n 'rows_render': sqlhtml.represent,\n 'rows_xml': sqlhtml.SQLTABLE\n}\nDAL.Field = Field\nDAL.Table = Table\n\n#: add web2py contrib drivers to pyDAL\nfrom pydal.drivers import DRIVERS\nif not DRIVERS.get('pymysql'):\n try:\n from .contrib import pymysql\n DRIVERS['pymysql'] = pymysql\n except:\n pass\nif not DRIVERS.get('pyodbc'):\n try:\n from .contrib import pypyodbc as pyodbc\n DRIVERS['pyodbc'] = pyodbc\n except:\n pass\nif not DRIVERS.get('pg8000'):\n try:\n from .contrib import pg8000\n DRIVERS['pg8000'] = pg8000\n except:\n pass\n", "path": "gluon/dal.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n| This file is part of the web2py Web Framework\n| Copyrighted by Massimo Di Pierro <[email protected]>\n| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)\n\nTakes care of adapting pyDAL to web2py's needs\n-----------------------------------------------\n\"\"\"\n\nfrom pydal import DAL as DAL\nfrom pydal import Field\nfrom pydal.objects import Row, Rows, Table, Query, Set, Expression\nfrom pydal import SQLCustomType, geoPoint, geoLine, geoPolygon\n\ndef _default_validators(db, field):\n \"\"\"\n Field type validation, using web2py's validators mechanism.\n\n makes sure the content of a field is in line with the declared\n fieldtype\n \"\"\"\n from gluon import validators\n field_type, field_length = field.type, field.length\n requires = []\n\n if field_type in (('string', 'text', 'password')):\n requires.append(validators.IS_LENGTH(field_length))\n elif field_type == 'json':\n requires.append(validators.IS_EMPTY_OR(validators.IS_JSON()))\n elif field_type == 'double' or field_type == 'float':\n requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100))\n elif field_type == 'integer':\n requires.append(validators.IS_INT_IN_RANGE(-2**31, 2**31))\n elif field_type == 'bigint':\n requires.append(validators.IS_INT_IN_RANGE(-2**63, 2**63))\n elif field_type.startswith('decimal'):\n requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10))\n elif field_type == 'date':\n requires.append(validators.IS_DATE())\n elif field_type == 'time':\n requires.append(validators.IS_TIME())\n elif field_type == 'datetime':\n requires.append(validators.IS_DATETIME())\n elif db and field_type.startswith('reference') and \\\n field_type.find('.') < 0 and \\\n field_type[10:] in db.tables:\n referenced = db[field_type[10:]]\n if hasattr(referenced, '_format') and referenced._format:\n requires = validators.IS_IN_DB(db, referenced._id,\n referenced._format)\n if field.unique:\n requires._and = validators.IS_NOT_IN_DB(db, field)\n if field.tablename == field_type[10:]:\n return validators.IS_EMPTY_OR(requires)\n return requires\n elif db and field_type.startswith('list:reference') and \\\n field_type.find('.') < 0 and \\\n field_type[15:] in db.tables:\n referenced = db[field_type[15:]]\n if hasattr(referenced, '_format') and referenced._format:\n requires = validators.IS_IN_DB(db, referenced._id,\n referenced._format, multiple=True)\n else:\n requires = validators.IS_IN_DB(db, referenced._id,\n multiple=True)\n if field.unique:\n requires._and = validators.IS_NOT_IN_DB(db, field)\n if not field.notnull:\n requires = validators.IS_EMPTY_OR(requires)\n return requires\n # does not get here for reference and list:reference\n if field.unique:\n requires.insert(0, validators.IS_NOT_IN_DB(db, field))\n excluded_fields = ['string', 'upload', 'text', 'password', 'boolean']\n if (field.notnull or field.unique) and field_type not in excluded_fields:\n requires.insert(0, validators.IS_NOT_EMPTY())\n elif not field.notnull and not field.unique and requires:\n requires[0] = validators.IS_EMPTY_OR(requires[0], null='' if field.type in ('string', 'text', 'password') else None)\n return requires\n\nfrom gluon.serializers import custom_json, xml\nfrom gluon.utils import web2py_uuid\nfrom gluon import sqlhtml\n\n\nDAL.serializers = {'json': custom_json, 'xml': xml}\nDAL.validators_method = _default_validators\nDAL.uuid = lambda x: web2py_uuid()\nDAL.representers = {\n 'rows_render': sqlhtml.represent,\n 'rows_xml': sqlhtml.SQLTABLE\n}\nDAL.Field = Field\nDAL.Table = Table\n\n#: add web2py contrib drivers to pyDAL\nfrom pydal.drivers import DRIVERS\nif not DRIVERS.get('pymysql'):\n try:\n from .contrib import pymysql\n DRIVERS['pymysql'] = pymysql\n except:\n pass\nif not DRIVERS.get('pyodbc'):\n try:\n from .contrib import pypyodbc as pyodbc\n DRIVERS['pyodbc'] = pyodbc\n except:\n pass\nif not DRIVERS.get('pg8000'):\n try:\n from .contrib import pg8000\n DRIVERS['pg8000'] = pg8000\n except:\n pass\n", "path": "gluon/dal.py"}]}
1,832
233
gh_patches_debug_7174
rasdani/github-patches
git_diff
cowrie__cowrie-1054
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Bug in csirtg plugin @wesyoung Not sure when this bug started, but just looked today at my honeypots and saw this happening all over the place in the logs. ``` 2018-02-11T16:53:14-0500 [twisted.internet.defer#critical] Unhandled error in Deferred: 2018-02-11T16:53:14-0500 [twisted.internet.defer#critical] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 289, in connectionLost protocol.connectionLost(reason) File "/usr/local/lib/python2.7/dist-packages/twisted/web/client.py", line 223, in connectionLost self.factory._disconnectedDeferred.callback(None) File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 459, in callback self._startRunCallbacks(result) File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 567, in _startRunCallbacks self._runCallbacks() --- <exception caught here> --- File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/home/cowrie/cowrie/cowrie/commands/wget.py", line 241, in error url=self.url) File "/home/cowrie/cowrie/cowrie/shell/protocol.py", line 80, in logDispatch pt.factory.logDispatch(*msg, **args) File "/home/cowrie/cowrie/cowrie/telnet/transport.py", line 43, in logDispatch output.logDispatch(*msg, **args) File "/home/cowrie/cowrie/cowrie/core/output.py", line 117, in logDispatch self.emit(ev) File "/home/cowrie/cowrie/cowrie/core/output.py", line 206, in emit self.write(ev) File "/home/cowrie/cowrie/cowrie/output/csirtg.py", line 43, in write system = e['system'] exceptions.KeyError: 'system' ``` --- 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/cowrie/output/csirtg.py` Content: ``` 1 from __future__ import absolute_import, division 2 3 import os 4 from datetime import datetime 5 6 from csirtgsdk.client import Client 7 from csirtgsdk.indicator import Indicator 8 9 from twisted.python import log 10 11 import cowrie.core.output 12 from cowrie.core.config import CONFIG 13 14 USERNAME = os.environ.get('CSIRTG_USER') 15 FEED = os.environ.get('CSIRTG_FEED') 16 TOKEN = os.environ.get('CSIRG_TOKEN') 17 DESCRIPTION = os.environ.get('CSIRTG_DESCRIPTION', 'random scanning activity') 18 19 20 class Output(cowrie.core.output.Output): 21 def __init__(self): 22 self.user = CONFIG.get('output_csirtg', 'username') or USERNAME 23 self.feed = CONFIG.get('output_csirtg', 'feed') or FEED 24 self.token = CONFIG.get('output_csirtg', 'token') or TOKEN 25 try: 26 self.description = CONFIG.get('output_csirtg', 'description') 27 except Exception: 28 self.description = DESCRIPTION 29 self.context = {} 30 self.client = Client(token=self.token) 31 cowrie.core.output.Output.__init__(self) 32 33 def start(self, ): 34 pass 35 36 def stop(self): 37 pass 38 39 def write(self, e): 40 peerIP = e['src_ip'] 41 ts = e['timestamp'] 42 system = e['system'] 43 44 if system not in ['cowrie.ssh.factory.CowrieSSHFactory', 'cowrie.telnet.transport.HoneyPotTelnetFactory']: 45 return 46 47 today = str(datetime.now().date()) 48 49 if not self.context.get(today): 50 self.context = {} 51 self.context[today] = set() 52 53 key = ','.join([peerIP, system]) 54 55 if key in self.context[today]: 56 return 57 58 self.context[today].add(key) 59 60 tags = 'scanner,ssh' 61 port = 22 62 if e['system'] == 'cowrie.telnet.transport.HoneyPotTelnetFactory': 63 tags = 'scanner,telnet' 64 port = 23 65 66 i = { 67 'user': self.user, 68 'feed': self.feed, 69 'indicator': peerIP, 70 'portlist': port, 71 'protocol': 'tcp', 72 'tags': tags, 73 'firsttime': ts, 74 'lasttime': ts, 75 'description': self.description 76 } 77 78 ret = Indicator(self.client, i).submit() 79 log.msg('logged to csirtg %s ' % ret['location']) 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/src/cowrie/output/csirtg.py b/src/cowrie/output/csirtg.py --- a/src/cowrie/output/csirtg.py +++ b/src/cowrie/output/csirtg.py @@ -39,9 +39,10 @@ def write(self, e): peerIP = e['src_ip'] ts = e['timestamp'] - system = e['system'] + system = e.get('system', None) - if system not in ['cowrie.ssh.factory.CowrieSSHFactory', 'cowrie.telnet.transport.HoneyPotTelnetFactory']: + if system not in ['cowrie.ssh.factory.CowrieSSHFactory', + 'cowrie.telnet.transport.HoneyPotTelnetFactory']: return today = str(datetime.now().date())
{"golden_diff": "diff --git a/src/cowrie/output/csirtg.py b/src/cowrie/output/csirtg.py\n--- a/src/cowrie/output/csirtg.py\n+++ b/src/cowrie/output/csirtg.py\n@@ -39,9 +39,10 @@\n def write(self, e):\n peerIP = e['src_ip']\n ts = e['timestamp']\n- system = e['system']\n+ system = e.get('system', None)\n \n- if system not in ['cowrie.ssh.factory.CowrieSSHFactory', 'cowrie.telnet.transport.HoneyPotTelnetFactory']:\n+ if system not in ['cowrie.ssh.factory.CowrieSSHFactory',\n+ 'cowrie.telnet.transport.HoneyPotTelnetFactory']:\n return\n \n today = str(datetime.now().date())\n", "issue": "Bug in csirtg plugin\n@wesyoung Not sure when this bug started, but just looked today at my honeypots and saw this happening all over the place in the logs.\r\n\r\n```\r\n2018-02-11T16:53:14-0500 [twisted.internet.defer#critical] Unhandled error in Deferred:\r\n2018-02-11T16:53:14-0500 [twisted.internet.defer#critical]\r\n\tTraceback (most recent call last):\r\n\t File \"/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py\", line 289, in connectionLost\r\n\t protocol.connectionLost(reason)\r\n\t File \"/usr/local/lib/python2.7/dist-packages/twisted/web/client.py\", line 223, in connectionLost\r\n\t self.factory._disconnectedDeferred.callback(None)\r\n\t File \"/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py\", line 459, in callback\r\n\t self._startRunCallbacks(result)\r\n\t File \"/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py\", line 567, in _startRunCallbacks\r\n\t self._runCallbacks()\r\n\t--- <exception caught here> ---\r\n\t File \"/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py\", line 653, in _runCallbacks\r\n\t current.result = callback(current.result, *args, **kw)\r\n\t File \"/home/cowrie/cowrie/cowrie/commands/wget.py\", line 241, in error\r\n\t url=self.url)\r\n\t File \"/home/cowrie/cowrie/cowrie/shell/protocol.py\", line 80, in logDispatch\r\n\t pt.factory.logDispatch(*msg, **args)\r\n\t File \"/home/cowrie/cowrie/cowrie/telnet/transport.py\", line 43, in logDispatch\r\n\t output.logDispatch(*msg, **args)\r\n\t File \"/home/cowrie/cowrie/cowrie/core/output.py\", line 117, in logDispatch\r\n\t self.emit(ev)\r\n\t File \"/home/cowrie/cowrie/cowrie/core/output.py\", line 206, in emit\r\n\t self.write(ev)\r\n\t File \"/home/cowrie/cowrie/cowrie/output/csirtg.py\", line 43, in write\r\n\t system = e['system']\r\n\texceptions.KeyError: 'system'\r\n```\n", "before_files": [{"content": "from __future__ import absolute_import, division\n\nimport os\nfrom datetime import datetime\n\nfrom csirtgsdk.client import Client\nfrom csirtgsdk.indicator import Indicator\n\nfrom twisted.python import log\n\nimport cowrie.core.output\nfrom cowrie.core.config import CONFIG\n\nUSERNAME = os.environ.get('CSIRTG_USER')\nFEED = os.environ.get('CSIRTG_FEED')\nTOKEN = os.environ.get('CSIRG_TOKEN')\nDESCRIPTION = os.environ.get('CSIRTG_DESCRIPTION', 'random scanning activity')\n\n\nclass Output(cowrie.core.output.Output):\n def __init__(self):\n self.user = CONFIG.get('output_csirtg', 'username') or USERNAME\n self.feed = CONFIG.get('output_csirtg', 'feed') or FEED\n self.token = CONFIG.get('output_csirtg', 'token') or TOKEN\n try:\n self.description = CONFIG.get('output_csirtg', 'description')\n except Exception:\n self.description = DESCRIPTION\n self.context = {}\n self.client = Client(token=self.token)\n cowrie.core.output.Output.__init__(self)\n\n def start(self, ):\n pass\n\n def stop(self):\n pass\n\n def write(self, e):\n peerIP = e['src_ip']\n ts = e['timestamp']\n system = e['system']\n\n if system not in ['cowrie.ssh.factory.CowrieSSHFactory', 'cowrie.telnet.transport.HoneyPotTelnetFactory']:\n return\n\n today = str(datetime.now().date())\n\n if not self.context.get(today):\n self.context = {}\n self.context[today] = set()\n\n key = ','.join([peerIP, system])\n\n if key in self.context[today]:\n return\n\n self.context[today].add(key)\n\n tags = 'scanner,ssh'\n port = 22\n if e['system'] == 'cowrie.telnet.transport.HoneyPotTelnetFactory':\n tags = 'scanner,telnet'\n port = 23\n\n i = {\n 'user': self.user,\n 'feed': self.feed,\n 'indicator': peerIP,\n 'portlist': port,\n 'protocol': 'tcp',\n 'tags': tags,\n 'firsttime': ts,\n 'lasttime': ts,\n 'description': self.description\n }\n\n ret = Indicator(self.client, i).submit()\n log.msg('logged to csirtg %s ' % ret['location'])\n", "path": "src/cowrie/output/csirtg.py"}], "after_files": [{"content": "from __future__ import absolute_import, division\n\nimport os\nfrom datetime import datetime\n\nfrom csirtgsdk.client import Client\nfrom csirtgsdk.indicator import Indicator\n\nfrom twisted.python import log\n\nimport cowrie.core.output\nfrom cowrie.core.config import CONFIG\n\nUSERNAME = os.environ.get('CSIRTG_USER')\nFEED = os.environ.get('CSIRTG_FEED')\nTOKEN = os.environ.get('CSIRG_TOKEN')\nDESCRIPTION = os.environ.get('CSIRTG_DESCRIPTION', 'random scanning activity')\n\n\nclass Output(cowrie.core.output.Output):\n def __init__(self):\n self.user = CONFIG.get('output_csirtg', 'username') or USERNAME\n self.feed = CONFIG.get('output_csirtg', 'feed') or FEED\n self.token = CONFIG.get('output_csirtg', 'token') or TOKEN\n try:\n self.description = CONFIG.get('output_csirtg', 'description')\n except Exception:\n self.description = DESCRIPTION\n self.context = {}\n self.client = Client(token=self.token)\n cowrie.core.output.Output.__init__(self)\n\n def start(self, ):\n pass\n\n def stop(self):\n pass\n\n def write(self, e):\n peerIP = e['src_ip']\n ts = e['timestamp']\n system = e.get('system', None)\n\n if system not in ['cowrie.ssh.factory.CowrieSSHFactory',\n 'cowrie.telnet.transport.HoneyPotTelnetFactory']:\n return\n\n today = str(datetime.now().date())\n\n if not self.context.get(today):\n self.context = {}\n self.context[today] = set()\n\n key = ','.join([peerIP, system])\n\n if key in self.context[today]:\n return\n\n self.context[today].add(key)\n\n tags = 'scanner,ssh'\n port = 22\n if e['system'] == 'cowrie.telnet.transport.HoneyPotTelnetFactory':\n tags = 'scanner,telnet'\n port = 23\n\n i = {\n 'user': self.user,\n 'feed': self.feed,\n 'indicator': peerIP,\n 'portlist': port,\n 'protocol': 'tcp',\n 'tags': tags,\n 'firsttime': ts,\n 'lasttime': ts,\n 'description': self.description\n }\n\n ret = Indicator(self.client, i).submit()\n log.msg('logged to csirtg %s ' % ret['location'])\n", "path": "src/cowrie/output/csirtg.py"}]}
1,499
180
gh_patches_debug_5664
rasdani/github-patches
git_diff
cisagov__manage.get.gov-278
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- DomainApplication list on logged in user homepage Outcome: A list (limited to one now) of domain applications on the homepage of a logged in user. A/C: As a user I want to see my in progress applications for a domain. As a user I want to be able to select an application that is `In Progress` and continue my progress. As a user I want to be able to view submitted applications. --- 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/views/index.py` Content: ``` 1 from django.shortcuts import render 2 3 4 def index(request): 5 """This page is available to anyone without logging in.""" 6 return render(request, "home.html") 7 ``` --- 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/views/index.py b/src/registrar/views/index.py --- a/src/registrar/views/index.py +++ b/src/registrar/views/index.py @@ -1,6 +1,12 @@ from django.shortcuts import render +from registrar.models import DomainApplication + def index(request): """This page is available to anyone without logging in.""" - return render(request, "home.html") + context = {} + if request.user.is_authenticated: + applications = DomainApplication.objects.filter(creator=request.user) + context["domain_applications"] = applications + return render(request, "home.html", context)
{"golden_diff": "diff --git a/src/registrar/views/index.py b/src/registrar/views/index.py\n--- a/src/registrar/views/index.py\n+++ b/src/registrar/views/index.py\n@@ -1,6 +1,12 @@\n from django.shortcuts import render\n \n+from registrar.models import DomainApplication\n+\n \n def index(request):\n \"\"\"This page is available to anyone without logging in.\"\"\"\n- return render(request, \"home.html\")\n+ context = {}\n+ if request.user.is_authenticated:\n+ applications = DomainApplication.objects.filter(creator=request.user)\n+ context[\"domain_applications\"] = applications\n+ return render(request, \"home.html\", context)\n", "issue": "DomainApplication list on logged in user homepage\nOutcome: A list (limited to one now) of domain applications on the homepage of a logged in user. \n\nA/C: As a user I want to see my in progress applications for a domain. As a user I want to be able to select an application that is `In Progress` and continue my progress. As a user I want to be able to view submitted applications. \n", "before_files": [{"content": "from django.shortcuts import render\n\n\ndef index(request):\n \"\"\"This page is available to anyone without logging in.\"\"\"\n return render(request, \"home.html\")\n", "path": "src/registrar/views/index.py"}], "after_files": [{"content": "from django.shortcuts import render\n\nfrom registrar.models import DomainApplication\n\n\ndef index(request):\n \"\"\"This page is available to anyone without logging in.\"\"\"\n context = {}\n if request.user.is_authenticated:\n applications = DomainApplication.objects.filter(creator=request.user)\n context[\"domain_applications\"] = applications\n return render(request, \"home.html\", context)\n", "path": "src/registrar/views/index.py"}]}
387
138
gh_patches_debug_14729
rasdani/github-patches
git_diff
dotkom__onlineweb4-612
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Gravatar default images do not load correctly --- 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/authentication/templatetags/gravatar_url_resolver.py` Content: ``` 1 from django import template 2 from django.conf import settings 3 import urllib, hashlib 4 5 register = template.Library() 6 7 @register.assignment_tag(takes_context=True) 8 def gravatar_url(context, user, size): 9 default = "%s%s_%s.png" % (context['request'].META['HTTP_HOST'], 10 settings.DEFAULT_PROFILE_PICTURE_PREFIX, user.gender) 11 gravatar_url = "https://www.gravatar.com/avatar/" + hashlib.md5(user.get_email().email).hexdigest() + "?" 12 gravatar_url += urllib.urlencode({'d': default, 's':str(size)}) 13 14 return gravatar_url ``` --- 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/authentication/templatetags/gravatar_url_resolver.py b/apps/authentication/templatetags/gravatar_url_resolver.py --- a/apps/authentication/templatetags/gravatar_url_resolver.py +++ b/apps/authentication/templatetags/gravatar_url_resolver.py @@ -6,8 +6,11 @@ @register.assignment_tag(takes_context=True) def gravatar_url(context, user, size): - default = "%s%s_%s.png" % (context['request'].META['HTTP_HOST'], + + prefix = "https://" if context['request'].is_secure() else "http://" + default = "%s%s%s_%s.png" % (prefix, context['request'].META['HTTP_HOST'], settings.DEFAULT_PROFILE_PICTURE_PREFIX, user.gender) + gravatar_url = "https://www.gravatar.com/avatar/" + hashlib.md5(user.get_email().email).hexdigest() + "?" gravatar_url += urllib.urlencode({'d': default, 's':str(size)})
{"golden_diff": "diff --git a/apps/authentication/templatetags/gravatar_url_resolver.py b/apps/authentication/templatetags/gravatar_url_resolver.py\n--- a/apps/authentication/templatetags/gravatar_url_resolver.py\n+++ b/apps/authentication/templatetags/gravatar_url_resolver.py\n@@ -6,8 +6,11 @@\n \n @register.assignment_tag(takes_context=True)\n def gravatar_url(context, user, size):\n- default = \"%s%s_%s.png\" % (context['request'].META['HTTP_HOST'],\n+\n+ prefix = \"https://\" if context['request'].is_secure() else \"http://\"\n+ default = \"%s%s%s_%s.png\" % (prefix, context['request'].META['HTTP_HOST'],\n settings.DEFAULT_PROFILE_PICTURE_PREFIX, user.gender)\n+\n gravatar_url = \"https://www.gravatar.com/avatar/\" + hashlib.md5(user.get_email().email).hexdigest() + \"?\"\n gravatar_url += urllib.urlencode({'d': default, 's':str(size)})\n", "issue": "Gravatar default images do not load correctly\n\n", "before_files": [{"content": "from django import template\nfrom django.conf import settings\nimport urllib, hashlib\n \nregister = template.Library()\n\[email protected]_tag(takes_context=True)\ndef gravatar_url(context, user, size):\n default = \"%s%s_%s.png\" % (context['request'].META['HTTP_HOST'],\n settings.DEFAULT_PROFILE_PICTURE_PREFIX, user.gender)\n gravatar_url = \"https://www.gravatar.com/avatar/\" + hashlib.md5(user.get_email().email).hexdigest() + \"?\"\n gravatar_url += urllib.urlencode({'d': default, 's':str(size)})\n\n return gravatar_url", "path": "apps/authentication/templatetags/gravatar_url_resolver.py"}], "after_files": [{"content": "from django import template\nfrom django.conf import settings\nimport urllib, hashlib\n \nregister = template.Library()\n\[email protected]_tag(takes_context=True)\ndef gravatar_url(context, user, size):\n\n prefix = \"https://\" if context['request'].is_secure() else \"http://\"\n default = \"%s%s%s_%s.png\" % (prefix, context['request'].META['HTTP_HOST'],\n settings.DEFAULT_PROFILE_PICTURE_PREFIX, user.gender)\n\n gravatar_url = \"https://www.gravatar.com/avatar/\" + hashlib.md5(user.get_email().email).hexdigest() + \"?\"\n gravatar_url += urllib.urlencode({'d': default, 's':str(size)})\n\n return gravatar_url", "path": "apps/authentication/templatetags/gravatar_url_resolver.py"}]}
421
218
gh_patches_debug_17320
rasdani/github-patches
git_diff
sql-machine-learning__elasticdl-1324
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Only keep necessary dependencies in requirements.txt Currently, we have one single `requirements.txt` file which contains some unnecessary dependencies used for testing only such as `pytest`, `pytest-cov`, and `mock`. They should not be part of `requirements.txt` and should not be distributed with `elasticdl` Python package. --- 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 find_packages, setup 2 3 with open("elasticdl/requirements.txt") as f: 4 requirements = f.read().splitlines() 5 6 setup( 7 name="elasticdl", 8 version="develop", 9 description="A Kubernetes-native Deep Learning Framework", 10 long_description="ElasticDL is a Kubernetes-native deep learning framework" 11 " built on top of TensorFlow 2.0 that supports" 12 " fault-tolerance and elastic scheduling.", 13 long_description_content_type="text/markdown", 14 author="Ant Financial", 15 url="https://elasticdl.org", 16 install_requires=requirements, 17 packages=find_packages(exclude=["*test*"]), 18 package_data={"": ["proto/elasticdl.proto", "docker/*", "Makefile"]}, 19 entry_points={ 20 "console_scripts": ["elasticdl=elasticdl.python.elasticdl.client:main"] 21 }, 22 ) 23 ``` --- 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 @@ -1,7 +1,11 @@ from setuptools import find_packages, setup with open("elasticdl/requirements.txt") as f: - requirements = f.read().splitlines() + required_deps = f.read().splitlines() + +extras = {} +with open("elasticdl/requirements-dev.txt") as f: + extras["develop"] = f.read().splitlines() setup( name="elasticdl", @@ -13,7 +17,8 @@ long_description_content_type="text/markdown", author="Ant Financial", url="https://elasticdl.org", - install_requires=requirements, + install_requires=required_deps, + extras_require=extras, packages=find_packages(exclude=["*test*"]), package_data={"": ["proto/elasticdl.proto", "docker/*", "Makefile"]}, entry_points={
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -1,7 +1,11 @@\n from setuptools import find_packages, setup\n \n with open(\"elasticdl/requirements.txt\") as f:\n- requirements = f.read().splitlines()\n+ required_deps = f.read().splitlines()\n+\n+extras = {}\n+with open(\"elasticdl/requirements-dev.txt\") as f:\n+ extras[\"develop\"] = f.read().splitlines()\n \n setup(\n name=\"elasticdl\",\n@@ -13,7 +17,8 @@\n long_description_content_type=\"text/markdown\",\n author=\"Ant Financial\",\n url=\"https://elasticdl.org\",\n- install_requires=requirements,\n+ install_requires=required_deps,\n+ extras_require=extras,\n packages=find_packages(exclude=[\"*test*\"]),\n package_data={\"\": [\"proto/elasticdl.proto\", \"docker/*\", \"Makefile\"]},\n entry_points={\n", "issue": "Only keep necessary dependencies in requirements.txt\nCurrently, we have one single `requirements.txt` file which contains some unnecessary dependencies used for testing only such as `pytest`, `pytest-cov`, and `mock`. They should not be part of `requirements.txt` and should not be distributed with `elasticdl` Python package.\n", "before_files": [{"content": "from setuptools import find_packages, setup\n\nwith open(\"elasticdl/requirements.txt\") as f:\n requirements = f.read().splitlines()\n\nsetup(\n name=\"elasticdl\",\n version=\"develop\",\n description=\"A Kubernetes-native Deep Learning Framework\",\n long_description=\"ElasticDL is a Kubernetes-native deep learning framework\"\n \" built on top of TensorFlow 2.0 that supports\"\n \" fault-tolerance and elastic scheduling.\",\n long_description_content_type=\"text/markdown\",\n author=\"Ant Financial\",\n url=\"https://elasticdl.org\",\n install_requires=requirements,\n packages=find_packages(exclude=[\"*test*\"]),\n package_data={\"\": [\"proto/elasticdl.proto\", \"docker/*\", \"Makefile\"]},\n entry_points={\n \"console_scripts\": [\"elasticdl=elasticdl.python.elasticdl.client:main\"]\n },\n)\n", "path": "setup.py"}], "after_files": [{"content": "from setuptools import find_packages, setup\n\nwith open(\"elasticdl/requirements.txt\") as f:\n required_deps = f.read().splitlines()\n\nextras = {}\nwith open(\"elasticdl/requirements-dev.txt\") as f:\n extras[\"develop\"] = f.read().splitlines()\n\nsetup(\n name=\"elasticdl\",\n version=\"develop\",\n description=\"A Kubernetes-native Deep Learning Framework\",\n long_description=\"ElasticDL is a Kubernetes-native deep learning framework\"\n \" built on top of TensorFlow 2.0 that supports\"\n \" fault-tolerance and elastic scheduling.\",\n long_description_content_type=\"text/markdown\",\n author=\"Ant Financial\",\n url=\"https://elasticdl.org\",\n install_requires=required_deps,\n extras_require=extras,\n packages=find_packages(exclude=[\"*test*\"]),\n package_data={\"\": [\"proto/elasticdl.proto\", \"docker/*\", \"Makefile\"]},\n entry_points={\n \"console_scripts\": [\"elasticdl=elasticdl.python.elasticdl.client:main\"]\n },\n)\n", "path": "setup.py"}]}
539
208
gh_patches_debug_13147
rasdani/github-patches
git_diff
google__jax-399
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- float16 support Add support for `np.float16`. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `jax/abstract_arrays.py` Content: ``` 1 # Copyright 2018 Google LLC 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 # https://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 from __future__ import division 17 from __future__ import print_function 18 19 import numpy as onp 20 import six 21 22 from . import core 23 from . import ad_util 24 from . util import prod 25 from .lib import xla_bridge 26 27 28 def concretization_err_msg(fun): 29 fname = getattr(fun, "__name__", fun) 30 msg = ("Abstract value passed to `{}`, which requires a concrete value. " 31 "The function to be transformed can't be traced at the required level " 32 "of abstraction. If using `jit`, try using `static_argnums` or " 33 "applying `jit` to smaller subfunctions instead.") 34 return msg.format(fname) 35 36 def concretization_function_error(fun): 37 def error(self, *args): 38 raise TypeError(concretization_err_msg(fun)) 39 return error 40 41 42 class UnshapedArray(core.AbstractValue): 43 __slots__ = ['dtype'] 44 array_abstraction_level = 3 45 46 def __init__(self, dtype): 47 self.dtype = dtype 48 49 def __eq__(self, other): 50 return type(self) is type(other) and self.dtype == other.dtype 51 52 def __hash__(self): 53 return hash(str(self.dtype)) 54 55 def __repr__(self): 56 return '{}({})'.format(self.__class__.__name__, self.str_short()) 57 58 _bool = _nonzero = concretization_function_error(bool) 59 _float = concretization_function_error(float) 60 _int = concretization_function_error(int) 61 if six.PY2: 62 _long = concretization_function_error(long) # noqa: F821 63 _complex = concretization_function_error(complex) 64 _hex = concretization_function_error(hex) 65 _oct = concretization_function_error(oct) 66 67 def at_least_vspace(self): 68 return self 69 70 def join(self, other): 71 return self 72 73 def str_short(self): 74 return onp.dtype(self.dtype).name 75 76 77 class ShapedArray(UnshapedArray): 78 __slots__ = ['shape'] 79 array_abstraction_level = 2 80 81 def __init__(self, shape, dtype): 82 self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(dtype)) 83 self.shape = shape 84 85 ndim = property(lambda self: len(self.shape)) 86 size = property(lambda self: prod(self.shape)) 87 88 def __eq__(self, other): 89 return (type(self) is type(other) 90 and self.dtype == other.dtype and self.shape == other.shape) 91 92 def __hash__(self): 93 return hash((self.shape, str(self.dtype))) 94 95 def at_least_vspace(self): 96 return self 97 98 def join(self, other): 99 if self.shape == other.shape and self.dtype == other.dtype: 100 return self 101 elif self.dtype == other.dtype: 102 return UnshapedArray(self.dtype) 103 else: 104 raise TypeError(other) 105 106 def str_short(self): 107 dtypestr = onp.dtype(self.dtype).name 108 shapestr = ','.join(map(str, self.shape)) 109 return '{}[{}]'.format(dtypestr, shapestr) 110 111 def __len__(self): 112 try: 113 return self.shape[0] 114 except IndexError: 115 raise TypeError("len() of unsized object") # same as numpy error 116 117 def _len(self, ignored_tracer): 118 return len(self) 119 120 121 class ConcreteArray(ShapedArray): 122 __slots__ = ['val'] 123 array_abstraction_level = 0 124 125 def __init__(self, val): 126 self.val = val 127 self.shape = onp.shape(val) 128 # canonicalized self.dtype doesn't necessarily match self.val 129 self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(onp.result_type(val))) 130 assert self.dtype != onp.dtype('O') 131 132 def __eq__(self, other): 133 return (type(self) is type(other) and self.dtype == other.dtype 134 and self.shape == other.shape and onp.all(self.val == other.val)) 135 136 def __hash__(self): 137 return id(self.val) 138 139 def at_least_vspace(self): 140 return ShapedArray(self.shape, self.dtype) 141 142 def join(self, other): 143 if self == other: 144 return self 145 elif self.shape == other.shape and self.dtype == other.dtype: 146 return ShapedArray(self.shape, self.dtype) 147 elif self.dtype == other.dtype: 148 return UnshapedArray(self.dtype) 149 else: 150 raise TypeError(other) 151 152 def str_short(self): 153 return str(self.val) 154 155 156 def make_shaped_array(x): 157 dtype = xla_bridge.canonicalize_dtype(onp.result_type(x)) 158 return ShapedArray(onp.shape(x), dtype) 159 160 def zeros_like_array(x): 161 dtype = xla_bridge.canonicalize_dtype(onp.result_type(x)) 162 return onp.broadcast_to(onp.array(0, dtype), onp.shape(x)) 163 164 array_types = [onp.ndarray, onp.float64, onp.float32, onp.complex64, 165 onp.complex128, onp.int64, onp.int32, onp.bool_, onp.uint64, 166 onp.uint32, complex, float, int, bool] 167 168 for t in array_types: 169 core.pytype_aval_mappings[t] = ConcreteArray 170 ad_util.jaxval_zeros_likers[t] = zeros_like_array 171 ``` --- 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/jax/abstract_arrays.py b/jax/abstract_arrays.py --- a/jax/abstract_arrays.py +++ b/jax/abstract_arrays.py @@ -161,9 +161,11 @@ dtype = xla_bridge.canonicalize_dtype(onp.result_type(x)) return onp.broadcast_to(onp.array(0, dtype), onp.shape(x)) -array_types = [onp.ndarray, onp.float64, onp.float32, onp.complex64, - onp.complex128, onp.int64, onp.int32, onp.bool_, onp.uint64, - onp.uint32, complex, float, int, bool] +array_types = [onp.ndarray, onp.float64, onp.float32, onp.float16, + onp.complex64, onp.complex128, + onp.int64, onp.int32, onp.int16, onp.int8, + onp.bool_, onp.uint64, onp.uint32, onp.uint16, onp.uint8, + complex, float, int, bool] for t in array_types: core.pytype_aval_mappings[t] = ConcreteArray
{"golden_diff": "diff --git a/jax/abstract_arrays.py b/jax/abstract_arrays.py\n--- a/jax/abstract_arrays.py\n+++ b/jax/abstract_arrays.py\n@@ -161,9 +161,11 @@\n dtype = xla_bridge.canonicalize_dtype(onp.result_type(x))\n return onp.broadcast_to(onp.array(0, dtype), onp.shape(x))\n \n-array_types = [onp.ndarray, onp.float64, onp.float32, onp.complex64,\n- onp.complex128, onp.int64, onp.int32, onp.bool_, onp.uint64,\n- onp.uint32, complex, float, int, bool]\n+array_types = [onp.ndarray, onp.float64, onp.float32, onp.float16,\n+ onp.complex64, onp.complex128,\n+ onp.int64, onp.int32, onp.int16, onp.int8,\n+ onp.bool_, onp.uint64, onp.uint32, onp.uint16, onp.uint8,\n+ complex, float, int, bool]\n \n for t in array_types:\n core.pytype_aval_mappings[t] = ConcreteArray\n", "issue": "float16 support\nAdd support for `np.float16`.\n", "before_files": [{"content": "# Copyright 2018 Google LLC\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# https://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\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as onp\nimport six\n\nfrom . import core\nfrom . import ad_util\nfrom . util import prod\nfrom .lib import xla_bridge\n\n\ndef concretization_err_msg(fun):\n fname = getattr(fun, \"__name__\", fun)\n msg = (\"Abstract value passed to `{}`, which requires a concrete value. \"\n \"The function to be transformed can't be traced at the required level \"\n \"of abstraction. If using `jit`, try using `static_argnums` or \"\n \"applying `jit` to smaller subfunctions instead.\")\n return msg.format(fname)\n\ndef concretization_function_error(fun):\n def error(self, *args):\n raise TypeError(concretization_err_msg(fun))\n return error\n\n\nclass UnshapedArray(core.AbstractValue):\n __slots__ = ['dtype']\n array_abstraction_level = 3\n\n def __init__(self, dtype):\n self.dtype = dtype\n\n def __eq__(self, other):\n return type(self) is type(other) and self.dtype == other.dtype\n\n def __hash__(self):\n return hash(str(self.dtype))\n\n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__, self.str_short())\n\n _bool = _nonzero = concretization_function_error(bool)\n _float = concretization_function_error(float)\n _int = concretization_function_error(int)\n if six.PY2:\n _long = concretization_function_error(long) # noqa: F821\n _complex = concretization_function_error(complex)\n _hex = concretization_function_error(hex)\n _oct = concretization_function_error(oct)\n\n def at_least_vspace(self):\n return self\n\n def join(self, other):\n return self\n\n def str_short(self):\n return onp.dtype(self.dtype).name\n\n\nclass ShapedArray(UnshapedArray):\n __slots__ = ['shape']\n array_abstraction_level = 2\n\n def __init__(self, shape, dtype):\n self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(dtype))\n self.shape = shape\n\n ndim = property(lambda self: len(self.shape))\n size = property(lambda self: prod(self.shape))\n\n def __eq__(self, other):\n return (type(self) is type(other)\n and self.dtype == other.dtype and self.shape == other.shape)\n\n def __hash__(self):\n return hash((self.shape, str(self.dtype)))\n\n def at_least_vspace(self):\n return self\n\n def join(self, other):\n if self.shape == other.shape and self.dtype == other.dtype:\n return self\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype)\n else:\n raise TypeError(other)\n\n def str_short(self):\n dtypestr = onp.dtype(self.dtype).name\n shapestr = ','.join(map(str, self.shape))\n return '{}[{}]'.format(dtypestr, shapestr)\n\n def __len__(self):\n try:\n return self.shape[0]\n except IndexError:\n raise TypeError(\"len() of unsized object\") # same as numpy error\n\n def _len(self, ignored_tracer):\n return len(self)\n\n\nclass ConcreteArray(ShapedArray):\n __slots__ = ['val']\n array_abstraction_level = 0\n\n def __init__(self, val):\n self.val = val\n self.shape = onp.shape(val)\n # canonicalized self.dtype doesn't necessarily match self.val\n self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(onp.result_type(val)))\n assert self.dtype != onp.dtype('O')\n\n def __eq__(self, other):\n return (type(self) is type(other) and self.dtype == other.dtype\n and self.shape == other.shape and onp.all(self.val == other.val))\n\n def __hash__(self):\n return id(self.val)\n\n def at_least_vspace(self):\n return ShapedArray(self.shape, self.dtype)\n\n def join(self, other):\n if self == other:\n return self\n elif self.shape == other.shape and self.dtype == other.dtype:\n return ShapedArray(self.shape, self.dtype)\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype)\n else:\n raise TypeError(other)\n\n def str_short(self):\n return str(self.val)\n\n\ndef make_shaped_array(x):\n dtype = xla_bridge.canonicalize_dtype(onp.result_type(x))\n return ShapedArray(onp.shape(x), dtype)\n\ndef zeros_like_array(x):\n dtype = xla_bridge.canonicalize_dtype(onp.result_type(x))\n return onp.broadcast_to(onp.array(0, dtype), onp.shape(x))\n\narray_types = [onp.ndarray, onp.float64, onp.float32, onp.complex64,\n onp.complex128, onp.int64, onp.int32, onp.bool_, onp.uint64,\n onp.uint32, complex, float, int, bool]\n\nfor t in array_types:\n core.pytype_aval_mappings[t] = ConcreteArray\n ad_util.jaxval_zeros_likers[t] = zeros_like_array\n", "path": "jax/abstract_arrays.py"}], "after_files": [{"content": "# Copyright 2018 Google LLC\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# https://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\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as onp\nimport six\n\nfrom . import core\nfrom . import ad_util\nfrom . util import prod\nfrom .lib import xla_bridge\n\n\ndef concretization_err_msg(fun):\n fname = getattr(fun, \"__name__\", fun)\n msg = (\"Abstract value passed to `{}`, which requires a concrete value. \"\n \"The function to be transformed can't be traced at the required level \"\n \"of abstraction. If using `jit`, try using `static_argnums` or \"\n \"applying `jit` to smaller subfunctions instead.\")\n return msg.format(fname)\n\ndef concretization_function_error(fun):\n def error(self, *args):\n raise TypeError(concretization_err_msg(fun))\n return error\n\n\nclass UnshapedArray(core.AbstractValue):\n __slots__ = ['dtype']\n array_abstraction_level = 3\n\n def __init__(self, dtype):\n self.dtype = dtype\n\n def __eq__(self, other):\n return type(self) is type(other) and self.dtype == other.dtype\n\n def __hash__(self):\n return hash(str(self.dtype))\n\n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__, self.str_short())\n\n _bool = _nonzero = concretization_function_error(bool)\n _float = concretization_function_error(float)\n _int = concretization_function_error(int)\n if six.PY2:\n _long = concretization_function_error(long) # noqa: F821\n _complex = concretization_function_error(complex)\n _hex = concretization_function_error(hex)\n _oct = concretization_function_error(oct)\n\n def at_least_vspace(self):\n return self\n\n def join(self, other):\n return self\n\n def str_short(self):\n return onp.dtype(self.dtype).name\n\n\nclass ShapedArray(UnshapedArray):\n __slots__ = ['shape']\n array_abstraction_level = 2\n\n def __init__(self, shape, dtype):\n self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(dtype))\n self.shape = shape\n\n ndim = property(lambda self: len(self.shape))\n size = property(lambda self: prod(self.shape))\n\n def __eq__(self, other):\n return (type(self) is type(other)\n and self.dtype == other.dtype and self.shape == other.shape)\n\n def __hash__(self):\n return hash((self.shape, str(self.dtype)))\n\n def at_least_vspace(self):\n return self\n\n def join(self, other):\n if self.shape == other.shape and self.dtype == other.dtype:\n return self\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype)\n else:\n raise TypeError(other)\n\n def str_short(self):\n dtypestr = onp.dtype(self.dtype).name\n shapestr = ','.join(map(str, self.shape))\n return '{}[{}]'.format(dtypestr, shapestr)\n\n def __len__(self):\n try:\n return self.shape[0]\n except IndexError:\n raise TypeError(\"len() of unsized object\") # same as numpy error\n\n def _len(self, ignored_tracer):\n return len(self)\n\n\nclass ConcreteArray(ShapedArray):\n __slots__ = ['val']\n array_abstraction_level = 0\n\n def __init__(self, val):\n self.val = val\n self.shape = onp.shape(val)\n # canonicalized self.dtype doesn't necessarily match self.val\n self.dtype = onp.dtype(xla_bridge.canonicalize_dtype(onp.result_type(val)))\n assert self.dtype != onp.dtype('O')\n\n def __eq__(self, other):\n return (type(self) is type(other) and self.dtype == other.dtype\n and self.shape == other.shape and onp.all(self.val == other.val))\n\n def __hash__(self):\n return id(self.val)\n\n def at_least_vspace(self):\n return ShapedArray(self.shape, self.dtype)\n\n def join(self, other):\n if self == other:\n return self\n elif self.shape == other.shape and self.dtype == other.dtype:\n return ShapedArray(self.shape, self.dtype)\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype)\n else:\n raise TypeError(other)\n\n def str_short(self):\n return str(self.val)\n\n\ndef make_shaped_array(x):\n dtype = xla_bridge.canonicalize_dtype(onp.result_type(x))\n return ShapedArray(onp.shape(x), dtype)\n\ndef zeros_like_array(x):\n dtype = xla_bridge.canonicalize_dtype(onp.result_type(x))\n return onp.broadcast_to(onp.array(0, dtype), onp.shape(x))\n\narray_types = [onp.ndarray, onp.float64, onp.float32, onp.float16,\n onp.complex64, onp.complex128,\n onp.int64, onp.int32, onp.int16, onp.int8,\n onp.bool_, onp.uint64, onp.uint32, onp.uint16, onp.uint8,\n complex, float, int, bool]\n\nfor t in array_types:\n core.pytype_aval_mappings[t] = ConcreteArray\n ad_util.jaxval_zeros_likers[t] = zeros_like_array\n", "path": "jax/abstract_arrays.py"}]}
1,997
290
gh_patches_debug_14455
rasdani/github-patches
git_diff
searx__searx-333
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Piratebay engine : update the URL The current URL is https://thepiratebay.se which doesn't respond. This one seems to work https://thepiratebay.mn (see https://en.wikipedia.org/wiki/The_Pirate_Bay ) Another solution : disable / remove the engine in settings.yml --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `searx/engines/piratebay.py` Content: ``` 1 # Piratebay (Videos, Music, Files) 2 # 3 # @website https://thepiratebay.se 4 # @provide-api no (nothing found) 5 # 6 # @using-api no 7 # @results HTML (using search portal) 8 # @stable yes (HTML can change) 9 # @parse url, title, content, seed, leech, magnetlink 10 11 from urlparse import urljoin 12 from cgi import escape 13 from urllib import quote 14 from lxml import html 15 from operator import itemgetter 16 from searx.engines.xpath import extract_text 17 18 # engine dependent config 19 categories = ['videos', 'music', 'files'] 20 paging = True 21 22 # search-url 23 url = 'https://thepiratebay.se/' 24 search_url = url + 'search/{search_term}/{pageno}/99/{search_type}' 25 26 # piratebay specific type-definitions 27 search_types = {'files': '0', 28 'music': '100', 29 'videos': '200'} 30 31 # specific xpath variables 32 magnet_xpath = './/a[@title="Download this torrent using magnet"]' 33 torrent_xpath = './/a[@title="Download this torrent"]' 34 content_xpath = './/font[@class="detDesc"]' 35 36 37 # do search-request 38 def request(query, params): 39 search_type = search_types.get(params['category'], '0') 40 41 params['url'] = search_url.format(search_term=quote(query), 42 search_type=search_type, 43 pageno=params['pageno'] - 1) 44 45 # FIX: SSLError: hostname 'kthepiratebay.se' 46 # doesn't match either of 'ssl2000.cloudflare.com', 'cloudflare.com', '*.cloudflare.com' 47 params['verify'] = False 48 49 return params 50 51 52 # get response from search-request 53 def response(resp): 54 results = [] 55 56 dom = html.fromstring(resp.text) 57 58 search_res = dom.xpath('//table[@id="searchResult"]//tr') 59 60 # return empty array if nothing is found 61 if not search_res: 62 return [] 63 64 # parse results 65 for result in search_res[1:]: 66 link = result.xpath('.//div[@class="detName"]//a')[0] 67 href = urljoin(url, link.attrib.get('href')) 68 title = extract_text(link) 69 content = escape(extract_text(result.xpath(content_xpath))) 70 seed, leech = result.xpath('.//td[@align="right"]/text()')[:2] 71 72 # convert seed to int if possible 73 if seed.isdigit(): 74 seed = int(seed) 75 else: 76 seed = 0 77 78 # convert leech to int if possible 79 if leech.isdigit(): 80 leech = int(leech) 81 else: 82 leech = 0 83 84 magnetlink = result.xpath(magnet_xpath)[0] 85 torrentfile_links = result.xpath(torrent_xpath) 86 if torrentfile_links: 87 torrentfile_link = torrentfile_links[0].attrib.get('href') 88 else: 89 torrentfile_link = None 90 91 # append result 92 results.append({'url': href, 93 'title': title, 94 'content': content, 95 'seed': seed, 96 'leech': leech, 97 'magnetlink': magnetlink.attrib.get('href'), 98 'torrentfile': torrentfile_link, 99 'template': 'torrent.html'}) 100 101 # return results sorted by seeder 102 return sorted(results, key=itemgetter('seed'), reverse=True) 103 ``` --- 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/searx/engines/piratebay.py b/searx/engines/piratebay.py --- a/searx/engines/piratebay.py +++ b/searx/engines/piratebay.py @@ -20,7 +20,7 @@ paging = True # search-url -url = 'https://thepiratebay.se/' +url = 'https://thepiratebay.am/' search_url = url + 'search/{search_term}/{pageno}/99/{search_type}' # piratebay specific type-definitions @@ -42,10 +42,6 @@ search_type=search_type, pageno=params['pageno'] - 1) - # FIX: SSLError: hostname 'kthepiratebay.se' - # doesn't match either of 'ssl2000.cloudflare.com', 'cloudflare.com', '*.cloudflare.com' - params['verify'] = False - return params
{"golden_diff": "diff --git a/searx/engines/piratebay.py b/searx/engines/piratebay.py\n--- a/searx/engines/piratebay.py\n+++ b/searx/engines/piratebay.py\n@@ -20,7 +20,7 @@\n paging = True\n \n # search-url\n-url = 'https://thepiratebay.se/'\n+url = 'https://thepiratebay.am/'\n search_url = url + 'search/{search_term}/{pageno}/99/{search_type}'\n \n # piratebay specific type-definitions\n@@ -42,10 +42,6 @@\n search_type=search_type,\n pageno=params['pageno'] - 1)\n \n- # FIX: SSLError: hostname 'kthepiratebay.se'\n- # doesn't match either of 'ssl2000.cloudflare.com', 'cloudflare.com', '*.cloudflare.com'\n- params['verify'] = False\n-\n return params\n", "issue": "Piratebay engine : update the URL\nThe current URL is https://thepiratebay.se which doesn't respond.\nThis one seems to work https://thepiratebay.mn (see https://en.wikipedia.org/wiki/The_Pirate_Bay )\n\nAnother solution : disable / remove the engine in settings.yml\n\n", "before_files": [{"content": "# Piratebay (Videos, Music, Files)\n#\n# @website https://thepiratebay.se\n# @provide-api no (nothing found)\n#\n# @using-api no\n# @results HTML (using search portal)\n# @stable yes (HTML can change)\n# @parse url, title, content, seed, leech, magnetlink\n\nfrom urlparse import urljoin\nfrom cgi import escape\nfrom urllib import quote\nfrom lxml import html\nfrom operator import itemgetter\nfrom searx.engines.xpath import extract_text\n\n# engine dependent config\ncategories = ['videos', 'music', 'files']\npaging = True\n\n# search-url\nurl = 'https://thepiratebay.se/'\nsearch_url = url + 'search/{search_term}/{pageno}/99/{search_type}'\n\n# piratebay specific type-definitions\nsearch_types = {'files': '0',\n 'music': '100',\n 'videos': '200'}\n\n# specific xpath variables\nmagnet_xpath = './/a[@title=\"Download this torrent using magnet\"]'\ntorrent_xpath = './/a[@title=\"Download this torrent\"]'\ncontent_xpath = './/font[@class=\"detDesc\"]'\n\n\n# do search-request\ndef request(query, params):\n search_type = search_types.get(params['category'], '0')\n\n params['url'] = search_url.format(search_term=quote(query),\n search_type=search_type,\n pageno=params['pageno'] - 1)\n\n # FIX: SSLError: hostname 'kthepiratebay.se'\n # doesn't match either of 'ssl2000.cloudflare.com', 'cloudflare.com', '*.cloudflare.com'\n params['verify'] = False\n\n return params\n\n\n# get response from search-request\ndef response(resp):\n results = []\n\n dom = html.fromstring(resp.text)\n\n search_res = dom.xpath('//table[@id=\"searchResult\"]//tr')\n\n # return empty array if nothing is found\n if not search_res:\n return []\n\n # parse results\n for result in search_res[1:]:\n link = result.xpath('.//div[@class=\"detName\"]//a')[0]\n href = urljoin(url, link.attrib.get('href'))\n title = extract_text(link)\n content = escape(extract_text(result.xpath(content_xpath)))\n seed, leech = result.xpath('.//td[@align=\"right\"]/text()')[:2]\n\n # convert seed to int if possible\n if seed.isdigit():\n seed = int(seed)\n else:\n seed = 0\n\n # convert leech to int if possible\n if leech.isdigit():\n leech = int(leech)\n else:\n leech = 0\n\n magnetlink = result.xpath(magnet_xpath)[0]\n torrentfile_links = result.xpath(torrent_xpath)\n if torrentfile_links:\n torrentfile_link = torrentfile_links[0].attrib.get('href')\n else:\n torrentfile_link = None\n\n # append result\n results.append({'url': href,\n 'title': title,\n 'content': content,\n 'seed': seed,\n 'leech': leech,\n 'magnetlink': magnetlink.attrib.get('href'),\n 'torrentfile': torrentfile_link,\n 'template': 'torrent.html'})\n\n # return results sorted by seeder\n return sorted(results, key=itemgetter('seed'), reverse=True)\n", "path": "searx/engines/piratebay.py"}], "after_files": [{"content": "# Piratebay (Videos, Music, Files)\n#\n# @website https://thepiratebay.se\n# @provide-api no (nothing found)\n#\n# @using-api no\n# @results HTML (using search portal)\n# @stable yes (HTML can change)\n# @parse url, title, content, seed, leech, magnetlink\n\nfrom urlparse import urljoin\nfrom cgi import escape\nfrom urllib import quote\nfrom lxml import html\nfrom operator import itemgetter\nfrom searx.engines.xpath import extract_text\n\n# engine dependent config\ncategories = ['videos', 'music', 'files']\npaging = True\n\n# search-url\nurl = 'https://thepiratebay.am/'\nsearch_url = url + 'search/{search_term}/{pageno}/99/{search_type}'\n\n# piratebay specific type-definitions\nsearch_types = {'files': '0',\n 'music': '100',\n 'videos': '200'}\n\n# specific xpath variables\nmagnet_xpath = './/a[@title=\"Download this torrent using magnet\"]'\ntorrent_xpath = './/a[@title=\"Download this torrent\"]'\ncontent_xpath = './/font[@class=\"detDesc\"]'\n\n\n# do search-request\ndef request(query, params):\n search_type = search_types.get(params['category'], '0')\n\n params['url'] = search_url.format(search_term=quote(query),\n search_type=search_type,\n pageno=params['pageno'] - 1)\n\n return params\n\n\n# get response from search-request\ndef response(resp):\n results = []\n\n dom = html.fromstring(resp.text)\n\n search_res = dom.xpath('//table[@id=\"searchResult\"]//tr')\n\n # return empty array if nothing is found\n if not search_res:\n return []\n\n # parse results\n for result in search_res[1:]:\n link = result.xpath('.//div[@class=\"detName\"]//a')[0]\n href = urljoin(url, link.attrib.get('href'))\n title = extract_text(link)\n content = escape(extract_text(result.xpath(content_xpath)))\n seed, leech = result.xpath('.//td[@align=\"right\"]/text()')[:2]\n\n # convert seed to int if possible\n if seed.isdigit():\n seed = int(seed)\n else:\n seed = 0\n\n # convert leech to int if possible\n if leech.isdigit():\n leech = int(leech)\n else:\n leech = 0\n\n magnetlink = result.xpath(magnet_xpath)[0]\n torrentfile_links = result.xpath(torrent_xpath)\n if torrentfile_links:\n torrentfile_link = torrentfile_links[0].attrib.get('href')\n else:\n torrentfile_link = None\n\n # append result\n results.append({'url': href,\n 'title': title,\n 'content': content,\n 'seed': seed,\n 'leech': leech,\n 'magnetlink': magnetlink.attrib.get('href'),\n 'torrentfile': torrentfile_link,\n 'template': 'torrent.html'})\n\n # return results sorted by seeder\n return sorted(results, key=itemgetter('seed'), reverse=True)\n", "path": "searx/engines/piratebay.py"}]}
1,276
215
gh_patches_debug_275
rasdani/github-patches
git_diff
sanic-org__sanic-878
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- 0.5.5 release request Because 0.5.4 has actual protocol parsing problem (#755) I request to quickly release 0.5.5. It causes actual request loss and unhandlable 400 errors for the sanic users. (unless they make local patch for sanic) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `sanic/__init__.py` Content: ``` 1 from sanic.app import Sanic 2 from sanic.blueprints import Blueprint 3 4 __version__ = '0.5.4' 5 6 __all__ = ['Sanic', 'Blueprint'] 7 ``` --- 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/sanic/__init__.py b/sanic/__init__.py --- a/sanic/__init__.py +++ b/sanic/__init__.py @@ -1,6 +1,6 @@ from sanic.app import Sanic from sanic.blueprints import Blueprint -__version__ = '0.5.4' +__version__ = '0.6.0' __all__ = ['Sanic', 'Blueprint']
{"golden_diff": "diff --git a/sanic/__init__.py b/sanic/__init__.py\n--- a/sanic/__init__.py\n+++ b/sanic/__init__.py\n@@ -1,6 +1,6 @@\n from sanic.app import Sanic\n from sanic.blueprints import Blueprint\n \n-__version__ = '0.5.4'\n+__version__ = '0.6.0'\n \n __all__ = ['Sanic', 'Blueprint']\n", "issue": "0.5.5 release request\nBecause 0.5.4 has actual protocol parsing problem (#755) I request to quickly release 0.5.5.\r\n\r\nIt causes actual request loss and unhandlable 400 errors for the sanic users. (unless they make local patch for sanic)\n", "before_files": [{"content": "from sanic.app import Sanic\nfrom sanic.blueprints import Blueprint\n\n__version__ = '0.5.4'\n\n__all__ = ['Sanic', 'Blueprint']\n", "path": "sanic/__init__.py"}], "after_files": [{"content": "from sanic.app import Sanic\nfrom sanic.blueprints import Blueprint\n\n__version__ = '0.6.0'\n\n__all__ = ['Sanic', 'Blueprint']\n", "path": "sanic/__init__.py"}]}
376
98
gh_patches_debug_35118
rasdani/github-patches
git_diff
unionai-oss__pandera-1595
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add a polars `Series` type **Is your feature request related to a problem? Please describe.** This would provide a similar `pandera.typing.Series` type for the polars API that exists for pandas and other backends. It is not strictly necessary since it does not get checked, but it would be good to have to match the existing API and to help type checkers understand accessing string column names from the class attribute names. **Describe the solution you'd like** Allow for annotating polars data frame fields as: ```python import pandera.polars as pa from pandera.typing.polars import Series class MySchema(pa.DataFrameModel): a: Series[int] ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pandera/api/polars/model.py` Content: ``` 1 """Class-based api for polars models.""" 2 3 from typing import ( 4 Dict, 5 List, 6 Tuple, 7 Type, 8 ) 9 10 import pandas as pd 11 import polars as pl 12 from pandera.api.checks import Check 13 from pandera.api.dataframe.model import ( 14 DataFrameModel as _DataFrameModel, 15 get_dtype_kwargs, 16 ) 17 from pandera.api.dataframe.model_components import FieldInfo 18 from pandera.api.polars.container import DataFrameSchema 19 from pandera.api.polars.components import Column 20 from pandera.api.polars.model_config import BaseConfig 21 from pandera.engines import polars_engine as pe 22 from pandera.errors import SchemaInitError 23 from pandera.typing import AnnotationInfo 24 25 26 class DataFrameModel(_DataFrameModel[pl.LazyFrame, DataFrameSchema]): 27 """Model of a polars :class:`~pandera.api.pandas.container.DataFrameSchema`. 28 29 See the :ref:`User Guide <dataframe-models>` for more. 30 """ 31 32 Config: Type[BaseConfig] = BaseConfig 33 34 @classmethod 35 def build_schema_(cls, **kwargs): 36 return DataFrameSchema( 37 cls._build_columns(cls.__fields__, cls.__checks__), 38 checks=cls.__root_checks__, 39 **kwargs, 40 ) 41 42 @classmethod 43 def _build_columns( # pylint:disable=too-many-locals 44 cls, 45 fields: Dict[str, Tuple[AnnotationInfo, FieldInfo]], 46 checks: Dict[str, List[Check]], 47 ) -> Dict[str, Column]: 48 49 columns: Dict[str, Column] = {} 50 for field_name, (annotation, field) in fields.items(): 51 field_checks = checks.get(field_name, []) 52 field_name = field.name 53 check_name = getattr(field, "check_name", None) 54 55 engine_dtype = None 56 try: 57 engine_dtype = pe.Engine.dtype(annotation.raw_annotation) 58 dtype = engine_dtype.type 59 except TypeError as exc: 60 if annotation.metadata: 61 if field.dtype_kwargs: 62 raise TypeError( 63 "Cannot specify redundant 'dtype_kwargs' " 64 + f"for {annotation.raw_annotation}." 65 + "\n Usage Tip: Drop 'typing.Annotated'." 66 ) from exc 67 dtype_kwargs = get_dtype_kwargs(annotation) 68 dtype = annotation.arg(**dtype_kwargs) # type: ignore 69 elif annotation.default_dtype: 70 dtype = annotation.default_dtype 71 else: 72 dtype = annotation.arg 73 74 if ( 75 annotation.origin is None 76 or isinstance(annotation.origin, pl.datatypes.DataTypeClass) 77 or engine_dtype 78 ): 79 if check_name is False: 80 raise SchemaInitError( 81 f"'check_name' is not supported for {field_name}." 82 ) 83 84 column_kwargs = ( 85 field.column_properties( 86 dtype, 87 required=not annotation.optional, 88 checks=field_checks, 89 name=field_name, 90 ) 91 if field 92 else {} 93 ) 94 columns[field_name] = Column(**column_kwargs) 95 96 else: 97 origin_name = ( 98 f"{annotation.origin.__module__}." 99 f"{annotation.origin.__name__}" 100 ) 101 msg = ( 102 " Series[TYPE] annotations are not supported for polars. " 103 "Use the bare TYPE directly" 104 if origin_name == "pandera.typing.pandas.Series" 105 else "" 106 ) 107 raise SchemaInitError( 108 f"Invalid annotation '{field_name}: " 109 f"{annotation.raw_annotation}'.{msg}" 110 ) 111 112 return columns 113 114 @classmethod 115 def to_json_schema(cls): 116 """Serialize schema metadata into json-schema format. 117 118 :param dataframe_schema: schema to write to json-schema format. 119 120 .. note:: 121 122 This function is currently does not fully specify a pandera schema, 123 and is primarily used internally to render OpenAPI docs via the 124 FastAPI integration. 125 """ 126 schema = cls.to_schema() 127 empty = pd.DataFrame(columns=schema.columns.keys()).astype( 128 {k: v.type for k, v in schema.dtypes.items()} 129 ) 130 table_schema = pd.io.json.build_table_schema(empty) 131 132 def _field_json_schema(field): 133 return { 134 "type": "array", 135 "items": {"type": field["type"]}, 136 } 137 138 return { 139 "title": schema.name or "pandera.DataFrameSchema", 140 "type": "object", 141 "properties": { 142 field["name"]: _field_json_schema(field) 143 for field in table_schema["fields"] 144 }, 145 } 146 ``` Path: `pandera/typing/polars.py` Content: ``` 1 """Pandera type annotations for Polars.""" 2 3 from typing import TYPE_CHECKING, Generic, TypeVar 4 5 from packaging import version 6 7 from pandera.typing.common import DataFrameBase, DataFrameModel 8 9 10 try: 11 import polars as pl 12 13 POLARS_INSTALLED = True 14 except ImportError: 15 POLARS_INSTALLED = False 16 17 18 def polars_version(): 19 """Return the modin version.""" 20 return version.parse(pl.__version__) 21 22 23 # pylint:disable=invalid-name 24 if TYPE_CHECKING: 25 T = TypeVar("T") # pragma: no cover 26 else: 27 T = DataFrameModel 28 29 30 if POLARS_INSTALLED: 31 # pylint: disable=too-few-public-methods 32 class LazyFrame(DataFrameBase, pl.LazyFrame, Generic[T]): 33 """ 34 Pandera generic for pl.LazyFrame, only used for type annotation. 35 36 *new in 0.19.0* 37 """ 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/pandera/api/polars/model.py b/pandera/api/polars/model.py --- a/pandera/api/polars/model.py +++ b/pandera/api/polars/model.py @@ -21,6 +21,7 @@ from pandera.engines import polars_engine as pe from pandera.errors import SchemaInitError from pandera.typing import AnnotationInfo +from pandera.typing.polars import Series class DataFrameModel(_DataFrameModel[pl.LazyFrame, DataFrameSchema]): @@ -74,6 +75,7 @@ if ( annotation.origin is None or isinstance(annotation.origin, pl.datatypes.DataTypeClass) + or annotation.origin is Series or engine_dtype ): if check_name is False: @@ -94,19 +96,9 @@ columns[field_name] = Column(**column_kwargs) else: - origin_name = ( - f"{annotation.origin.__module__}." - f"{annotation.origin.__name__}" - ) - msg = ( - " Series[TYPE] annotations are not supported for polars. " - "Use the bare TYPE directly" - if origin_name == "pandera.typing.pandas.Series" - else "" - ) raise SchemaInitError( f"Invalid annotation '{field_name}: " - f"{annotation.raw_annotation}'.{msg}" + f"{annotation.raw_annotation}'." ) return columns diff --git a/pandera/typing/polars.py b/pandera/typing/polars.py --- a/pandera/typing/polars.py +++ b/pandera/typing/polars.py @@ -4,7 +4,11 @@ from packaging import version -from pandera.typing.common import DataFrameBase, DataFrameModel +from pandera.typing.common import ( + DataFrameBase, + DataFrameModel, + SeriesBase, +) try: @@ -35,3 +39,11 @@ *new in 0.19.0* """ + + # pylint: disable=too-few-public-methods + class Series(SeriesBase, pl.Series, Generic[T]): + """ + Pandera generic for pl.Series, only used for type annotation. + + *new in 0.19.0* + """
{"golden_diff": "diff --git a/pandera/api/polars/model.py b/pandera/api/polars/model.py\n--- a/pandera/api/polars/model.py\n+++ b/pandera/api/polars/model.py\n@@ -21,6 +21,7 @@\n from pandera.engines import polars_engine as pe\n from pandera.errors import SchemaInitError\n from pandera.typing import AnnotationInfo\n+from pandera.typing.polars import Series\n \n \n class DataFrameModel(_DataFrameModel[pl.LazyFrame, DataFrameSchema]):\n@@ -74,6 +75,7 @@\n if (\n annotation.origin is None\n or isinstance(annotation.origin, pl.datatypes.DataTypeClass)\n+ or annotation.origin is Series\n or engine_dtype\n ):\n if check_name is False:\n@@ -94,19 +96,9 @@\n columns[field_name] = Column(**column_kwargs)\n \n else:\n- origin_name = (\n- f\"{annotation.origin.__module__}.\"\n- f\"{annotation.origin.__name__}\"\n- )\n- msg = (\n- \" Series[TYPE] annotations are not supported for polars. \"\n- \"Use the bare TYPE directly\"\n- if origin_name == \"pandera.typing.pandas.Series\"\n- else \"\"\n- )\n raise SchemaInitError(\n f\"Invalid annotation '{field_name}: \"\n- f\"{annotation.raw_annotation}'.{msg}\"\n+ f\"{annotation.raw_annotation}'.\"\n )\n \n return columns\ndiff --git a/pandera/typing/polars.py b/pandera/typing/polars.py\n--- a/pandera/typing/polars.py\n+++ b/pandera/typing/polars.py\n@@ -4,7 +4,11 @@\n \n from packaging import version\n \n-from pandera.typing.common import DataFrameBase, DataFrameModel\n+from pandera.typing.common import (\n+ DataFrameBase,\n+ DataFrameModel,\n+ SeriesBase,\n+)\n \n \n try:\n@@ -35,3 +39,11 @@\n \n *new in 0.19.0*\n \"\"\"\n+\n+ # pylint: disable=too-few-public-methods\n+ class Series(SeriesBase, pl.Series, Generic[T]):\n+ \"\"\"\n+ Pandera generic for pl.Series, only used for type annotation.\n+\n+ *new in 0.19.0*\n+ \"\"\"\n", "issue": "Add a polars `Series` type\n**Is your feature request related to a problem? Please describe.**\r\nThis would provide a similar `pandera.typing.Series` type for the polars API that exists for pandas and other backends. It is not strictly necessary since it does not get checked, but it would be good to have to match the existing API and to help type checkers understand accessing string column names from the class attribute names.\r\n\r\n**Describe the solution you'd like**\r\nAllow for annotating polars data frame fields as:\r\n```python\r\nimport pandera.polars as pa\r\nfrom pandera.typing.polars import Series\r\n\r\nclass MySchema(pa.DataFrameModel):\r\n a: Series[int]\r\n```\r\n\n", "before_files": [{"content": "\"\"\"Class-based api for polars models.\"\"\"\n\nfrom typing import (\n Dict,\n List,\n Tuple,\n Type,\n)\n\nimport pandas as pd\nimport polars as pl\nfrom pandera.api.checks import Check\nfrom pandera.api.dataframe.model import (\n DataFrameModel as _DataFrameModel,\n get_dtype_kwargs,\n)\nfrom pandera.api.dataframe.model_components import FieldInfo\nfrom pandera.api.polars.container import DataFrameSchema\nfrom pandera.api.polars.components import Column\nfrom pandera.api.polars.model_config import BaseConfig\nfrom pandera.engines import polars_engine as pe\nfrom pandera.errors import SchemaInitError\nfrom pandera.typing import AnnotationInfo\n\n\nclass DataFrameModel(_DataFrameModel[pl.LazyFrame, DataFrameSchema]):\n \"\"\"Model of a polars :class:`~pandera.api.pandas.container.DataFrameSchema`.\n\n See the :ref:`User Guide <dataframe-models>` for more.\n \"\"\"\n\n Config: Type[BaseConfig] = BaseConfig\n\n @classmethod\n def build_schema_(cls, **kwargs):\n return DataFrameSchema(\n cls._build_columns(cls.__fields__, cls.__checks__),\n checks=cls.__root_checks__,\n **kwargs,\n )\n\n @classmethod\n def _build_columns( # pylint:disable=too-many-locals\n cls,\n fields: Dict[str, Tuple[AnnotationInfo, FieldInfo]],\n checks: Dict[str, List[Check]],\n ) -> Dict[str, Column]:\n\n columns: Dict[str, Column] = {}\n for field_name, (annotation, field) in fields.items():\n field_checks = checks.get(field_name, [])\n field_name = field.name\n check_name = getattr(field, \"check_name\", None)\n\n engine_dtype = None\n try:\n engine_dtype = pe.Engine.dtype(annotation.raw_annotation)\n dtype = engine_dtype.type\n except TypeError as exc:\n if annotation.metadata:\n if field.dtype_kwargs:\n raise TypeError(\n \"Cannot specify redundant 'dtype_kwargs' \"\n + f\"for {annotation.raw_annotation}.\"\n + \"\\n Usage Tip: Drop 'typing.Annotated'.\"\n ) from exc\n dtype_kwargs = get_dtype_kwargs(annotation)\n dtype = annotation.arg(**dtype_kwargs) # type: ignore\n elif annotation.default_dtype:\n dtype = annotation.default_dtype\n else:\n dtype = annotation.arg\n\n if (\n annotation.origin is None\n or isinstance(annotation.origin, pl.datatypes.DataTypeClass)\n or engine_dtype\n ):\n if check_name is False:\n raise SchemaInitError(\n f\"'check_name' is not supported for {field_name}.\"\n )\n\n column_kwargs = (\n field.column_properties(\n dtype,\n required=not annotation.optional,\n checks=field_checks,\n name=field_name,\n )\n if field\n else {}\n )\n columns[field_name] = Column(**column_kwargs)\n\n else:\n origin_name = (\n f\"{annotation.origin.__module__}.\"\n f\"{annotation.origin.__name__}\"\n )\n msg = (\n \" Series[TYPE] annotations are not supported for polars. \"\n \"Use the bare TYPE directly\"\n if origin_name == \"pandera.typing.pandas.Series\"\n else \"\"\n )\n raise SchemaInitError(\n f\"Invalid annotation '{field_name}: \"\n f\"{annotation.raw_annotation}'.{msg}\"\n )\n\n return columns\n\n @classmethod\n def to_json_schema(cls):\n \"\"\"Serialize schema metadata into json-schema format.\n\n :param dataframe_schema: schema to write to json-schema format.\n\n .. note::\n\n This function is currently does not fully specify a pandera schema,\n and is primarily used internally to render OpenAPI docs via the\n FastAPI integration.\n \"\"\"\n schema = cls.to_schema()\n empty = pd.DataFrame(columns=schema.columns.keys()).astype(\n {k: v.type for k, v in schema.dtypes.items()}\n )\n table_schema = pd.io.json.build_table_schema(empty)\n\n def _field_json_schema(field):\n return {\n \"type\": \"array\",\n \"items\": {\"type\": field[\"type\"]},\n }\n\n return {\n \"title\": schema.name or \"pandera.DataFrameSchema\",\n \"type\": \"object\",\n \"properties\": {\n field[\"name\"]: _field_json_schema(field)\n for field in table_schema[\"fields\"]\n },\n }\n", "path": "pandera/api/polars/model.py"}, {"content": "\"\"\"Pandera type annotations for Polars.\"\"\"\n\nfrom typing import TYPE_CHECKING, Generic, TypeVar\n\nfrom packaging import version\n\nfrom pandera.typing.common import DataFrameBase, DataFrameModel\n\n\ntry:\n import polars as pl\n\n POLARS_INSTALLED = True\nexcept ImportError:\n POLARS_INSTALLED = False\n\n\ndef polars_version():\n \"\"\"Return the modin version.\"\"\"\n return version.parse(pl.__version__)\n\n\n# pylint:disable=invalid-name\nif TYPE_CHECKING:\n T = TypeVar(\"T\") # pragma: no cover\nelse:\n T = DataFrameModel\n\n\nif POLARS_INSTALLED:\n # pylint: disable=too-few-public-methods\n class LazyFrame(DataFrameBase, pl.LazyFrame, Generic[T]):\n \"\"\"\n Pandera generic for pl.LazyFrame, only used for type annotation.\n\n *new in 0.19.0*\n \"\"\"\n", "path": "pandera/typing/polars.py"}], "after_files": [{"content": "\"\"\"Class-based api for polars models.\"\"\"\n\nfrom typing import (\n Dict,\n List,\n Tuple,\n Type,\n)\n\nimport pandas as pd\nimport polars as pl\nfrom pandera.api.checks import Check\nfrom pandera.api.dataframe.model import (\n DataFrameModel as _DataFrameModel,\n get_dtype_kwargs,\n)\nfrom pandera.api.dataframe.model_components import FieldInfo\nfrom pandera.api.polars.container import DataFrameSchema\nfrom pandera.api.polars.components import Column\nfrom pandera.api.polars.model_config import BaseConfig\nfrom pandera.engines import polars_engine as pe\nfrom pandera.errors import SchemaInitError\nfrom pandera.typing import AnnotationInfo\nfrom pandera.typing.polars import Series\n\n\nclass DataFrameModel(_DataFrameModel[pl.LazyFrame, DataFrameSchema]):\n \"\"\"Model of a polars :class:`~pandera.api.pandas.container.DataFrameSchema`.\n\n See the :ref:`User Guide <dataframe-models>` for more.\n \"\"\"\n\n Config: Type[BaseConfig] = BaseConfig\n\n @classmethod\n def build_schema_(cls, **kwargs):\n return DataFrameSchema(\n cls._build_columns(cls.__fields__, cls.__checks__),\n checks=cls.__root_checks__,\n **kwargs,\n )\n\n @classmethod\n def _build_columns( # pylint:disable=too-many-locals\n cls,\n fields: Dict[str, Tuple[AnnotationInfo, FieldInfo]],\n checks: Dict[str, List[Check]],\n ) -> Dict[str, Column]:\n\n columns: Dict[str, Column] = {}\n for field_name, (annotation, field) in fields.items():\n field_checks = checks.get(field_name, [])\n field_name = field.name\n check_name = getattr(field, \"check_name\", None)\n\n engine_dtype = None\n try:\n engine_dtype = pe.Engine.dtype(annotation.raw_annotation)\n dtype = engine_dtype.type\n except TypeError as exc:\n if annotation.metadata:\n if field.dtype_kwargs:\n raise TypeError(\n \"Cannot specify redundant 'dtype_kwargs' \"\n + f\"for {annotation.raw_annotation}.\"\n + \"\\n Usage Tip: Drop 'typing.Annotated'.\"\n ) from exc\n dtype_kwargs = get_dtype_kwargs(annotation)\n dtype = annotation.arg(**dtype_kwargs) # type: ignore\n elif annotation.default_dtype:\n dtype = annotation.default_dtype\n else:\n dtype = annotation.arg\n\n if (\n annotation.origin is None\n or isinstance(annotation.origin, pl.datatypes.DataTypeClass)\n or annotation.origin is Series\n or engine_dtype\n ):\n if check_name is False:\n raise SchemaInitError(\n f\"'check_name' is not supported for {field_name}.\"\n )\n\n column_kwargs = (\n field.column_properties(\n dtype,\n required=not annotation.optional,\n checks=field_checks,\n name=field_name,\n )\n if field\n else {}\n )\n columns[field_name] = Column(**column_kwargs)\n\n else:\n raise SchemaInitError(\n f\"Invalid annotation '{field_name}: \"\n f\"{annotation.raw_annotation}'.\"\n )\n\n return columns\n\n @classmethod\n def to_json_schema(cls):\n \"\"\"Serialize schema metadata into json-schema format.\n\n :param dataframe_schema: schema to write to json-schema format.\n\n .. note::\n\n This function is currently does not fully specify a pandera schema,\n and is primarily used internally to render OpenAPI docs via the\n FastAPI integration.\n \"\"\"\n schema = cls.to_schema()\n empty = pd.DataFrame(columns=schema.columns.keys()).astype(\n {k: v.type for k, v in schema.dtypes.items()}\n )\n table_schema = pd.io.json.build_table_schema(empty)\n\n def _field_json_schema(field):\n return {\n \"type\": \"array\",\n \"items\": {\"type\": field[\"type\"]},\n }\n\n return {\n \"title\": schema.name or \"pandera.DataFrameSchema\",\n \"type\": \"object\",\n \"properties\": {\n field[\"name\"]: _field_json_schema(field)\n for field in table_schema[\"fields\"]\n },\n }\n", "path": "pandera/api/polars/model.py"}, {"content": "\"\"\"Pandera type annotations for Polars.\"\"\"\n\nfrom typing import TYPE_CHECKING, Generic, TypeVar\n\nfrom packaging import version\n\nfrom pandera.typing.common import (\n DataFrameBase,\n DataFrameModel,\n SeriesBase,\n)\n\n\ntry:\n import polars as pl\n\n POLARS_INSTALLED = True\nexcept ImportError:\n POLARS_INSTALLED = False\n\n\ndef polars_version():\n \"\"\"Return the modin version.\"\"\"\n return version.parse(pl.__version__)\n\n\n# pylint:disable=invalid-name\nif TYPE_CHECKING:\n T = TypeVar(\"T\") # pragma: no cover\nelse:\n T = DataFrameModel\n\n\nif POLARS_INSTALLED:\n # pylint: disable=too-few-public-methods\n class LazyFrame(DataFrameBase, pl.LazyFrame, Generic[T]):\n \"\"\"\n Pandera generic for pl.LazyFrame, only used for type annotation.\n\n *new in 0.19.0*\n \"\"\"\n\n # pylint: disable=too-few-public-methods\n class Series(SeriesBase, pl.Series, Generic[T]):\n \"\"\"\n Pandera generic for pl.Series, only used for type annotation.\n\n *new in 0.19.0*\n \"\"\"\n", "path": "pandera/typing/polars.py"}]}
1,979
517
gh_patches_debug_31431
rasdani/github-patches
git_diff
CTFd__CTFd-1581
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Hidden scores, hides graphs for admins as well Hidden scores, hides graphs for admins 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: `CTFd/utils/decorators/visibility.py` Content: ``` 1 import functools 2 3 from flask import abort, redirect, render_template, request, url_for 4 5 from CTFd.constants.config import ( 6 AccountVisibilityTypes, 7 ChallengeVisibilityTypes, 8 ConfigTypes, 9 RegistrationVisibilityTypes, 10 ScoreVisibilityTypes, 11 ) 12 from CTFd.utils import get_config 13 from CTFd.utils.user import authed, is_admin 14 15 16 def check_score_visibility(f): 17 @functools.wraps(f) 18 def _check_score_visibility(*args, **kwargs): 19 v = get_config(ConfigTypes.SCORE_VISIBILITY) 20 if v == ScoreVisibilityTypes.PUBLIC: 21 return f(*args, **kwargs) 22 23 elif v == ScoreVisibilityTypes.PRIVATE: 24 if authed(): 25 return f(*args, **kwargs) 26 else: 27 if request.content_type == "application/json": 28 abort(403) 29 else: 30 return redirect(url_for("auth.login", next=request.full_path)) 31 32 elif v == ScoreVisibilityTypes.HIDDEN: 33 return ( 34 render_template("errors/403.html", error="Scores are currently hidden"), 35 403, 36 ) 37 38 elif v == ScoreVisibilityTypes.ADMINS: 39 if is_admin(): 40 return f(*args, **kwargs) 41 else: 42 abort(404) 43 44 return _check_score_visibility 45 46 47 def check_challenge_visibility(f): 48 @functools.wraps(f) 49 def _check_challenge_visibility(*args, **kwargs): 50 v = get_config(ConfigTypes.CHALLENGE_VISIBILITY) 51 if v == ChallengeVisibilityTypes.PUBLIC: 52 return f(*args, **kwargs) 53 54 elif v == ChallengeVisibilityTypes.PRIVATE: 55 if authed(): 56 return f(*args, **kwargs) 57 else: 58 if request.content_type == "application/json": 59 abort(403) 60 else: 61 return redirect(url_for("auth.login", next=request.full_path)) 62 63 elif v == ChallengeVisibilityTypes.ADMINS: 64 if is_admin(): 65 return f(*args, **kwargs) 66 else: 67 if authed(): 68 abort(403) 69 else: 70 return redirect(url_for("auth.login", next=request.full_path)) 71 72 return _check_challenge_visibility 73 74 75 def check_account_visibility(f): 76 @functools.wraps(f) 77 def _check_account_visibility(*args, **kwargs): 78 v = get_config(ConfigTypes.ACCOUNT_VISIBILITY) 79 if v == AccountVisibilityTypes.PUBLIC: 80 return f(*args, **kwargs) 81 82 elif v == AccountVisibilityTypes.PRIVATE: 83 if authed(): 84 return f(*args, **kwargs) 85 else: 86 if request.content_type == "application/json": 87 abort(403) 88 else: 89 return redirect(url_for("auth.login", next=request.full_path)) 90 91 elif v == AccountVisibilityTypes.ADMINS: 92 if is_admin(): 93 return f(*args, **kwargs) 94 else: 95 abort(404) 96 97 return _check_account_visibility 98 99 100 def check_registration_visibility(f): 101 @functools.wraps(f) 102 def _check_registration_visibility(*args, **kwargs): 103 v = get_config(ConfigTypes.REGISTRATION_VISIBILITY) 104 if v == RegistrationVisibilityTypes.PUBLIC: 105 return f(*args, **kwargs) 106 elif v == RegistrationVisibilityTypes.PRIVATE: 107 abort(404) 108 109 return _check_registration_visibility 110 ``` Path: `CTFd/scoreboard.py` Content: ``` 1 from flask import Blueprint, render_template 2 3 from CTFd.cache import cache, make_cache_key 4 from CTFd.utils import config 5 from CTFd.utils.decorators.visibility import check_score_visibility 6 from CTFd.utils.helpers import get_infos 7 from CTFd.utils.scores import get_standings 8 9 scoreboard = Blueprint("scoreboard", __name__) 10 11 12 @scoreboard.route("/scoreboard") 13 @check_score_visibility 14 @cache.cached(timeout=60, key_prefix=make_cache_key) 15 def listing(): 16 infos = get_infos() 17 18 if config.is_scoreboard_frozen(): 19 infos.append("Scoreboard has been frozen") 20 21 standings = get_standings() 22 return render_template("scoreboard.html", standings=standings, infos=infos) 23 ``` --- 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/CTFd/scoreboard.py b/CTFd/scoreboard.py --- a/CTFd/scoreboard.py +++ b/CTFd/scoreboard.py @@ -2,9 +2,11 @@ from CTFd.cache import cache, make_cache_key from CTFd.utils import config +from CTFd.utils.config.visibility import scores_visible from CTFd.utils.decorators.visibility import check_score_visibility from CTFd.utils.helpers import get_infos from CTFd.utils.scores import get_standings +from CTFd.utils.user import is_admin scoreboard = Blueprint("scoreboard", __name__) @@ -18,5 +20,8 @@ if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") + if is_admin() is True and scores_visible() is False: + infos.append("Scores are not currently visible to users") + standings = get_standings() return render_template("scoreboard.html", standings=standings, infos=infos) diff --git a/CTFd/utils/decorators/visibility.py b/CTFd/utils/decorators/visibility.py --- a/CTFd/utils/decorators/visibility.py +++ b/CTFd/utils/decorators/visibility.py @@ -30,10 +30,18 @@ return redirect(url_for("auth.login", next=request.full_path)) elif v == ScoreVisibilityTypes.HIDDEN: - return ( - render_template("errors/403.html", error="Scores are currently hidden"), - 403, - ) + if is_admin(): + return f(*args, **kwargs) + else: + if request.content_type == "application/json": + abort(403) + else: + return ( + render_template( + "errors/403.html", error="Scores are currently hidden" + ), + 403, + ) elif v == ScoreVisibilityTypes.ADMINS: if is_admin():
{"golden_diff": "diff --git a/CTFd/scoreboard.py b/CTFd/scoreboard.py\n--- a/CTFd/scoreboard.py\n+++ b/CTFd/scoreboard.py\n@@ -2,9 +2,11 @@\n \n from CTFd.cache import cache, make_cache_key\n from CTFd.utils import config\n+from CTFd.utils.config.visibility import scores_visible\n from CTFd.utils.decorators.visibility import check_score_visibility\n from CTFd.utils.helpers import get_infos\n from CTFd.utils.scores import get_standings\n+from CTFd.utils.user import is_admin\n \n scoreboard = Blueprint(\"scoreboard\", __name__)\n \n@@ -18,5 +20,8 @@\n if config.is_scoreboard_frozen():\n infos.append(\"Scoreboard has been frozen\")\n \n+ if is_admin() is True and scores_visible() is False:\n+ infos.append(\"Scores are not currently visible to users\")\n+\n standings = get_standings()\n return render_template(\"scoreboard.html\", standings=standings, infos=infos)\ndiff --git a/CTFd/utils/decorators/visibility.py b/CTFd/utils/decorators/visibility.py\n--- a/CTFd/utils/decorators/visibility.py\n+++ b/CTFd/utils/decorators/visibility.py\n@@ -30,10 +30,18 @@\n return redirect(url_for(\"auth.login\", next=request.full_path))\n \n elif v == ScoreVisibilityTypes.HIDDEN:\n- return (\n- render_template(\"errors/403.html\", error=\"Scores are currently hidden\"),\n- 403,\n- )\n+ if is_admin():\n+ return f(*args, **kwargs)\n+ else:\n+ if request.content_type == \"application/json\":\n+ abort(403)\n+ else:\n+ return (\n+ render_template(\n+ \"errors/403.html\", error=\"Scores are currently hidden\"\n+ ),\n+ 403,\n+ )\n \n elif v == ScoreVisibilityTypes.ADMINS:\n if is_admin():\n", "issue": "Hidden scores, hides graphs for admins as well\nHidden scores, hides graphs for admins as well. \n", "before_files": [{"content": "import functools\n\nfrom flask import abort, redirect, render_template, request, url_for\n\nfrom CTFd.constants.config import (\n AccountVisibilityTypes,\n ChallengeVisibilityTypes,\n ConfigTypes,\n RegistrationVisibilityTypes,\n ScoreVisibilityTypes,\n)\nfrom CTFd.utils import get_config\nfrom CTFd.utils.user import authed, is_admin\n\n\ndef check_score_visibility(f):\n @functools.wraps(f)\n def _check_score_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.SCORE_VISIBILITY)\n if v == ScoreVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == ScoreVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == ScoreVisibilityTypes.HIDDEN:\n return (\n render_template(\"errors/403.html\", error=\"Scores are currently hidden\"),\n 403,\n )\n\n elif v == ScoreVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n abort(404)\n\n return _check_score_visibility\n\n\ndef check_challenge_visibility(f):\n @functools.wraps(f)\n def _check_challenge_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.CHALLENGE_VISIBILITY)\n if v == ChallengeVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == ChallengeVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == ChallengeVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n if authed():\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n return _check_challenge_visibility\n\n\ndef check_account_visibility(f):\n @functools.wraps(f)\n def _check_account_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.ACCOUNT_VISIBILITY)\n if v == AccountVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == AccountVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == AccountVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n abort(404)\n\n return _check_account_visibility\n\n\ndef check_registration_visibility(f):\n @functools.wraps(f)\n def _check_registration_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.REGISTRATION_VISIBILITY)\n if v == RegistrationVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n elif v == RegistrationVisibilityTypes.PRIVATE:\n abort(404)\n\n return _check_registration_visibility\n", "path": "CTFd/utils/decorators/visibility.py"}, {"content": "from flask import Blueprint, render_template\n\nfrom CTFd.cache import cache, make_cache_key\nfrom CTFd.utils import config\nfrom CTFd.utils.decorators.visibility import check_score_visibility\nfrom CTFd.utils.helpers import get_infos\nfrom CTFd.utils.scores import get_standings\n\nscoreboard = Blueprint(\"scoreboard\", __name__)\n\n\[email protected](\"/scoreboard\")\n@check_score_visibility\[email protected](timeout=60, key_prefix=make_cache_key)\ndef listing():\n infos = get_infos()\n\n if config.is_scoreboard_frozen():\n infos.append(\"Scoreboard has been frozen\")\n\n standings = get_standings()\n return render_template(\"scoreboard.html\", standings=standings, infos=infos)\n", "path": "CTFd/scoreboard.py"}], "after_files": [{"content": "import functools\n\nfrom flask import abort, redirect, render_template, request, url_for\n\nfrom CTFd.constants.config import (\n AccountVisibilityTypes,\n ChallengeVisibilityTypes,\n ConfigTypes,\n RegistrationVisibilityTypes,\n ScoreVisibilityTypes,\n)\nfrom CTFd.utils import get_config\nfrom CTFd.utils.user import authed, is_admin\n\n\ndef check_score_visibility(f):\n @functools.wraps(f)\n def _check_score_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.SCORE_VISIBILITY)\n if v == ScoreVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == ScoreVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == ScoreVisibilityTypes.HIDDEN:\n if is_admin():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return (\n render_template(\n \"errors/403.html\", error=\"Scores are currently hidden\"\n ),\n 403,\n )\n\n elif v == ScoreVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n abort(404)\n\n return _check_score_visibility\n\n\ndef check_challenge_visibility(f):\n @functools.wraps(f)\n def _check_challenge_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.CHALLENGE_VISIBILITY)\n if v == ChallengeVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == ChallengeVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == ChallengeVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n if authed():\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n return _check_challenge_visibility\n\n\ndef check_account_visibility(f):\n @functools.wraps(f)\n def _check_account_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.ACCOUNT_VISIBILITY)\n if v == AccountVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n\n elif v == AccountVisibilityTypes.PRIVATE:\n if authed():\n return f(*args, **kwargs)\n else:\n if request.content_type == \"application/json\":\n abort(403)\n else:\n return redirect(url_for(\"auth.login\", next=request.full_path))\n\n elif v == AccountVisibilityTypes.ADMINS:\n if is_admin():\n return f(*args, **kwargs)\n else:\n abort(404)\n\n return _check_account_visibility\n\n\ndef check_registration_visibility(f):\n @functools.wraps(f)\n def _check_registration_visibility(*args, **kwargs):\n v = get_config(ConfigTypes.REGISTRATION_VISIBILITY)\n if v == RegistrationVisibilityTypes.PUBLIC:\n return f(*args, **kwargs)\n elif v == RegistrationVisibilityTypes.PRIVATE:\n abort(404)\n\n return _check_registration_visibility\n", "path": "CTFd/utils/decorators/visibility.py"}, {"content": "from flask import Blueprint, render_template\n\nfrom CTFd.cache import cache, make_cache_key\nfrom CTFd.utils import config\nfrom CTFd.utils.config.visibility import scores_visible\nfrom CTFd.utils.decorators.visibility import check_score_visibility\nfrom CTFd.utils.helpers import get_infos\nfrom CTFd.utils.scores import get_standings\nfrom CTFd.utils.user import is_admin\n\nscoreboard = Blueprint(\"scoreboard\", __name__)\n\n\[email protected](\"/scoreboard\")\n@check_score_visibility\[email protected](timeout=60, key_prefix=make_cache_key)\ndef listing():\n infos = get_infos()\n\n if config.is_scoreboard_frozen():\n infos.append(\"Scoreboard has been frozen\")\n\n if is_admin() is True and scores_visible() is False:\n infos.append(\"Scores are not currently visible to users\")\n\n standings = get_standings()\n return render_template(\"scoreboard.html\", standings=standings, infos=infos)\n", "path": "CTFd/scoreboard.py"}]}
1,444
449
gh_patches_debug_28399
rasdani/github-patches
git_diff
mirumee__ariadne-1162
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Python 3.12 has deprecation warnings Ariadne produces few warnings when ran on Py3.12. Most of those are out of our hands as they are coming from dependencies, but there are some we should fix: ``` /ariadne/ariadne/contrib/tracing/apollotracing.py:36: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). self.start_date = datetime.utcnow() /ariadne/ariadne/contrib/tracing/apollotracing.py:96: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC). "end": datetime.utcnow(), ``` --- 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/contrib/tracing/apollotracing.py` Content: ``` 1 from datetime import datetime 2 from inspect import iscoroutinefunction 3 from typing import Any, List, Optional, cast 4 5 from graphql import GraphQLResolveInfo 6 from graphql.pyutils import is_awaitable 7 8 from ...types import ContextValue, Extension, Resolver 9 from .utils import format_path, should_trace 10 11 try: 12 from time import perf_counter_ns 13 except ImportError: 14 # Py 3.6 fallback 15 from time import perf_counter 16 17 NS_IN_SECOND = 1000000000 18 19 def perf_counter_ns() -> int: 20 return int(perf_counter() * NS_IN_SECOND) 21 22 23 TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" 24 25 26 class ApolloTracingExtension(Extension): 27 def __init__(self, trace_default_resolver: bool = False) -> None: 28 self.trace_default_resolver = trace_default_resolver 29 self.start_date: Optional[datetime] = None 30 self.start_timestamp: int = 0 31 self.resolvers: List[dict] = [] 32 33 self._totals = None 34 35 def request_started(self, context: ContextValue): 36 self.start_date = datetime.utcnow() 37 self.start_timestamp = perf_counter_ns() 38 39 def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs): 40 if not should_trace(info, self.trace_default_resolver): 41 return next_(obj, info, **kwargs) 42 43 if iscoroutinefunction(next_): 44 return self.resolve_async(next_, obj, info, **kwargs) 45 46 return self.resolve_sync(next_, obj, info, **kwargs) 47 48 async def resolve_async( 49 self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs 50 ): 51 start_timestamp = perf_counter_ns() 52 record = { 53 "path": format_path(info.path), 54 "parentType": str(info.parent_type), 55 "fieldName": info.field_name, 56 "returnType": str(info.return_type), 57 "startOffset": start_timestamp - cast(int, self.start_timestamp), 58 } 59 self.resolvers.append(record) 60 try: 61 result = next_(obj, info, **kwargs) 62 if is_awaitable(result): 63 result = await result 64 return result 65 finally: 66 end_timestamp = perf_counter_ns() 67 record["duration"] = end_timestamp - start_timestamp 68 69 def resolve_sync( 70 self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs 71 ): 72 start_timestamp = perf_counter_ns() 73 record = { 74 "path": format_path(info.path), 75 "parentType": str(info.parent_type), 76 "fieldName": info.field_name, 77 "returnType": str(info.return_type), 78 "startOffset": start_timestamp - cast(int, self.start_timestamp), 79 } 80 self.resolvers.append(record) 81 try: 82 result = next_(obj, info, **kwargs) 83 return result 84 finally: 85 end_timestamp = perf_counter_ns() 86 record["duration"] = end_timestamp - start_timestamp 87 88 def get_totals(self): 89 if self._totals is None: 90 self._totals = self._get_totals() 91 return self._totals 92 93 def _get_totals(self): 94 return { 95 "start": self.start_date, 96 "end": datetime.utcnow(), 97 "duration": perf_counter_ns() - self.start_timestamp, 98 "resolvers": self.resolvers, 99 } 100 101 def format(self, context: ContextValue): 102 totals = self.get_totals() 103 104 return { 105 "tracing": { 106 "version": 1, 107 "startTime": totals["start"].strftime(TIMESTAMP_FORMAT), 108 "endTime": totals["end"].strftime(TIMESTAMP_FORMAT), 109 "duration": totals["duration"], 110 "execution": {"resolvers": totals["resolvers"]}, 111 } 112 } 113 ``` --- 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/contrib/tracing/apollotracing.py b/ariadne/contrib/tracing/apollotracing.py --- a/ariadne/contrib/tracing/apollotracing.py +++ b/ariadne/contrib/tracing/apollotracing.py @@ -1,4 +1,3 @@ -from datetime import datetime from inspect import iscoroutinefunction from typing import Any, List, Optional, cast @@ -20,6 +19,19 @@ return int(perf_counter() * NS_IN_SECOND) +try: + from datetime import UTC, datetime # type: ignore[attr-defined] + + def utc_now(): + return datetime.now(UTC) + +except ImportError: + from datetime import datetime + + def utc_now(): + return datetime.utcnow() + + TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @@ -33,7 +45,7 @@ self._totals = None def request_started(self, context: ContextValue): - self.start_date = datetime.utcnow() + self.start_date = utc_now() self.start_timestamp = perf_counter_ns() def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs): @@ -93,7 +105,7 @@ def _get_totals(self): return { "start": self.start_date, - "end": datetime.utcnow(), + "end": utc_now(), "duration": perf_counter_ns() - self.start_timestamp, "resolvers": self.resolvers, }
{"golden_diff": "diff --git a/ariadne/contrib/tracing/apollotracing.py b/ariadne/contrib/tracing/apollotracing.py\n--- a/ariadne/contrib/tracing/apollotracing.py\n+++ b/ariadne/contrib/tracing/apollotracing.py\n@@ -1,4 +1,3 @@\n-from datetime import datetime\n from inspect import iscoroutinefunction\n from typing import Any, List, Optional, cast\n \n@@ -20,6 +19,19 @@\n return int(perf_counter() * NS_IN_SECOND)\n \n \n+try:\n+ from datetime import UTC, datetime # type: ignore[attr-defined]\n+\n+ def utc_now():\n+ return datetime.now(UTC)\n+\n+except ImportError:\n+ from datetime import datetime\n+\n+ def utc_now():\n+ return datetime.utcnow()\n+\n+\n TIMESTAMP_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n \n \n@@ -33,7 +45,7 @@\n self._totals = None\n \n def request_started(self, context: ContextValue):\n- self.start_date = datetime.utcnow()\n+ self.start_date = utc_now()\n self.start_timestamp = perf_counter_ns()\n \n def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs):\n@@ -93,7 +105,7 @@\n def _get_totals(self):\n return {\n \"start\": self.start_date,\n- \"end\": datetime.utcnow(),\n+ \"end\": utc_now(),\n \"duration\": perf_counter_ns() - self.start_timestamp,\n \"resolvers\": self.resolvers,\n }\n", "issue": "Python 3.12 has deprecation warnings\nAriadne produces few warnings when ran on Py3.12. Most of those are out of our hands as they are coming from dependencies, but there are some we should fix:\r\n\r\n```\r\n\r\n /ariadne/ariadne/contrib/tracing/apollotracing.py:36: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).\r\n self.start_date = datetime.utcnow()\r\n\r\n /ariadne/ariadne/contrib/tracing/apollotracing.py:96: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).\r\n \"end\": datetime.utcnow(),\r\n```\n", "before_files": [{"content": "from datetime import datetime\nfrom inspect import iscoroutinefunction\nfrom typing import Any, List, Optional, cast\n\nfrom graphql import GraphQLResolveInfo\nfrom graphql.pyutils import is_awaitable\n\nfrom ...types import ContextValue, Extension, Resolver\nfrom .utils import format_path, should_trace\n\ntry:\n from time import perf_counter_ns\nexcept ImportError:\n # Py 3.6 fallback\n from time import perf_counter\n\n NS_IN_SECOND = 1000000000\n\n def perf_counter_ns() -> int:\n return int(perf_counter() * NS_IN_SECOND)\n\n\nTIMESTAMP_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n\n\nclass ApolloTracingExtension(Extension):\n def __init__(self, trace_default_resolver: bool = False) -> None:\n self.trace_default_resolver = trace_default_resolver\n self.start_date: Optional[datetime] = None\n self.start_timestamp: int = 0\n self.resolvers: List[dict] = []\n\n self._totals = None\n\n def request_started(self, context: ContextValue):\n self.start_date = datetime.utcnow()\n self.start_timestamp = perf_counter_ns()\n\n def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs):\n if not should_trace(info, self.trace_default_resolver):\n return next_(obj, info, **kwargs)\n\n if iscoroutinefunction(next_):\n return self.resolve_async(next_, obj, info, **kwargs)\n\n return self.resolve_sync(next_, obj, info, **kwargs)\n\n async def resolve_async(\n self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs\n ):\n start_timestamp = perf_counter_ns()\n record = {\n \"path\": format_path(info.path),\n \"parentType\": str(info.parent_type),\n \"fieldName\": info.field_name,\n \"returnType\": str(info.return_type),\n \"startOffset\": start_timestamp - cast(int, self.start_timestamp),\n }\n self.resolvers.append(record)\n try:\n result = next_(obj, info, **kwargs)\n if is_awaitable(result):\n result = await result\n return result\n finally:\n end_timestamp = perf_counter_ns()\n record[\"duration\"] = end_timestamp - start_timestamp\n\n def resolve_sync(\n self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs\n ):\n start_timestamp = perf_counter_ns()\n record = {\n \"path\": format_path(info.path),\n \"parentType\": str(info.parent_type),\n \"fieldName\": info.field_name,\n \"returnType\": str(info.return_type),\n \"startOffset\": start_timestamp - cast(int, self.start_timestamp),\n }\n self.resolvers.append(record)\n try:\n result = next_(obj, info, **kwargs)\n return result\n finally:\n end_timestamp = perf_counter_ns()\n record[\"duration\"] = end_timestamp - start_timestamp\n\n def get_totals(self):\n if self._totals is None:\n self._totals = self._get_totals()\n return self._totals\n\n def _get_totals(self):\n return {\n \"start\": self.start_date,\n \"end\": datetime.utcnow(),\n \"duration\": perf_counter_ns() - self.start_timestamp,\n \"resolvers\": self.resolvers,\n }\n\n def format(self, context: ContextValue):\n totals = self.get_totals()\n\n return {\n \"tracing\": {\n \"version\": 1,\n \"startTime\": totals[\"start\"].strftime(TIMESTAMP_FORMAT),\n \"endTime\": totals[\"end\"].strftime(TIMESTAMP_FORMAT),\n \"duration\": totals[\"duration\"],\n \"execution\": {\"resolvers\": totals[\"resolvers\"]},\n }\n }\n", "path": "ariadne/contrib/tracing/apollotracing.py"}], "after_files": [{"content": "from inspect import iscoroutinefunction\nfrom typing import Any, List, Optional, cast\n\nfrom graphql import GraphQLResolveInfo\nfrom graphql.pyutils import is_awaitable\n\nfrom ...types import ContextValue, Extension, Resolver\nfrom .utils import format_path, should_trace\n\ntry:\n from time import perf_counter_ns\nexcept ImportError:\n # Py 3.6 fallback\n from time import perf_counter\n\n NS_IN_SECOND = 1000000000\n\n def perf_counter_ns() -> int:\n return int(perf_counter() * NS_IN_SECOND)\n\n\ntry:\n from datetime import UTC, datetime # type: ignore[attr-defined]\n\n def utc_now():\n return datetime.now(UTC)\n\nexcept ImportError:\n from datetime import datetime\n\n def utc_now():\n return datetime.utcnow()\n\n\nTIMESTAMP_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n\n\nclass ApolloTracingExtension(Extension):\n def __init__(self, trace_default_resolver: bool = False) -> None:\n self.trace_default_resolver = trace_default_resolver\n self.start_date: Optional[datetime] = None\n self.start_timestamp: int = 0\n self.resolvers: List[dict] = []\n\n self._totals = None\n\n def request_started(self, context: ContextValue):\n self.start_date = utc_now()\n self.start_timestamp = perf_counter_ns()\n\n def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs):\n if not should_trace(info, self.trace_default_resolver):\n return next_(obj, info, **kwargs)\n\n if iscoroutinefunction(next_):\n return self.resolve_async(next_, obj, info, **kwargs)\n\n return self.resolve_sync(next_, obj, info, **kwargs)\n\n async def resolve_async(\n self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs\n ):\n start_timestamp = perf_counter_ns()\n record = {\n \"path\": format_path(info.path),\n \"parentType\": str(info.parent_type),\n \"fieldName\": info.field_name,\n \"returnType\": str(info.return_type),\n \"startOffset\": start_timestamp - cast(int, self.start_timestamp),\n }\n self.resolvers.append(record)\n try:\n result = next_(obj, info, **kwargs)\n if is_awaitable(result):\n result = await result\n return result\n finally:\n end_timestamp = perf_counter_ns()\n record[\"duration\"] = end_timestamp - start_timestamp\n\n def resolve_sync(\n self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs\n ):\n start_timestamp = perf_counter_ns()\n record = {\n \"path\": format_path(info.path),\n \"parentType\": str(info.parent_type),\n \"fieldName\": info.field_name,\n \"returnType\": str(info.return_type),\n \"startOffset\": start_timestamp - cast(int, self.start_timestamp),\n }\n self.resolvers.append(record)\n try:\n result = next_(obj, info, **kwargs)\n return result\n finally:\n end_timestamp = perf_counter_ns()\n record[\"duration\"] = end_timestamp - start_timestamp\n\n def get_totals(self):\n if self._totals is None:\n self._totals = self._get_totals()\n return self._totals\n\n def _get_totals(self):\n return {\n \"start\": self.start_date,\n \"end\": utc_now(),\n \"duration\": perf_counter_ns() - self.start_timestamp,\n \"resolvers\": self.resolvers,\n }\n\n def format(self, context: ContextValue):\n totals = self.get_totals()\n\n return {\n \"tracing\": {\n \"version\": 1,\n \"startTime\": totals[\"start\"].strftime(TIMESTAMP_FORMAT),\n \"endTime\": totals[\"end\"].strftime(TIMESTAMP_FORMAT),\n \"duration\": totals[\"duration\"],\n \"execution\": {\"resolvers\": totals[\"resolvers\"]},\n }\n }\n", "path": "ariadne/contrib/tracing/apollotracing.py"}]}
1,499
355
gh_patches_debug_14538
rasdani/github-patches
git_diff
airctic__icevision-189
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- helper function for COCO parser ## 🚀 Feature **Is your feature request related to a problem? Please describe.** As described in #79, it's currently very verbose to create a COCO parser, the steps should be ideally be reduced to a single function call. **Dream API** ```python parser = datasets.coco.parser( annotations_file="path_to_annotations.json", img_dir="path_to_images_dir", ) ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mantisshrimp/datasets/coco/parsers.py` Content: ``` 1 __all__ = ["COCOImageInfoParser", "COCOAnnotationParser"] 2 3 from mantisshrimp.imports import * 4 from mantisshrimp.core import * 5 from mantisshrimp.parsers.defaults import * 6 from mantisshrimp.parsers.mixins import * 7 8 9 class COCOImageInfoParser(DefaultImageInfoParser): 10 def __init__(self, infos, img_dir): 11 super().__init__() 12 self.infos = infos 13 self.img_dir = img_dir 14 15 def __iter__(self): 16 yield from self.infos 17 18 def __len__(self): 19 return len(self.infos) 20 21 def imageid(self, o) -> int: 22 return o["id"] 23 24 def filepath(self, o) -> Union[str, Path]: 25 return self.img_dir / o["file_name"] 26 27 def height(self, o) -> int: 28 return o["height"] 29 30 def width(self, o) -> int: 31 return o["width"] 32 33 34 class COCOAnnotationParser(MaskRCNNParser, AreasParserMixin, IsCrowdsParserMixin): 35 def __init__(self, annotations: list): 36 self.annotations = annotations 37 38 def __iter__(self): 39 yield from self.annotations 40 41 def __len__(self): 42 return len(self.annotations) 43 44 def imageid(self, o) -> int: 45 return o["image_id"] 46 47 def labels(self, o) -> List[int]: 48 return [o["category_id"]] 49 50 def bboxes(self, o) -> List[BBox]: 51 return [BBox.from_xywh(*o["bbox"])] 52 53 def areas(self, o) -> List[float]: 54 return [o["area"]] 55 56 def masks(self, o) -> List[MaskArray]: 57 seg = o["segmentation"] 58 if o["iscrowd"]: 59 return [RLE.from_coco(seg["counts"])] 60 else: 61 return [Polygon(seg)] 62 63 def iscrowds(self, o) -> List[bool]: 64 return [o["iscrowd"]] 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/mantisshrimp/datasets/coco/parsers.py b/mantisshrimp/datasets/coco/parsers.py --- a/mantisshrimp/datasets/coco/parsers.py +++ b/mantisshrimp/datasets/coco/parsers.py @@ -1,9 +1,23 @@ -__all__ = ["COCOImageInfoParser", "COCOAnnotationParser"] +__all__ = ["parser", "COCOImageInfoParser", "COCOAnnotationParser"] from mantisshrimp.imports import * from mantisshrimp.core import * -from mantisshrimp.parsers.defaults import * -from mantisshrimp.parsers.mixins import * +from mantisshrimp.parsers import * + + +def parser( + annotations_file: Union[str, Path], img_dir: Union[str, Path] +) -> ParserInterface: + annotations_dict = json.loads(Path(annotations_file).read()) + + image_info_parser = COCOImageInfoParser( + infos=annotations_dict["images"], img_dir=img_dir + ) + annotations_parser = COCOAnnotationParser( + annotations=annotations_dict["annotations"] + ) + + return CombinedParser(image_info_parser, annotations_parser) class COCOImageInfoParser(DefaultImageInfoParser):
{"golden_diff": "diff --git a/mantisshrimp/datasets/coco/parsers.py b/mantisshrimp/datasets/coco/parsers.py\n--- a/mantisshrimp/datasets/coco/parsers.py\n+++ b/mantisshrimp/datasets/coco/parsers.py\n@@ -1,9 +1,23 @@\n-__all__ = [\"COCOImageInfoParser\", \"COCOAnnotationParser\"]\n+__all__ = [\"parser\", \"COCOImageInfoParser\", \"COCOAnnotationParser\"]\n \n from mantisshrimp.imports import *\n from mantisshrimp.core import *\n-from mantisshrimp.parsers.defaults import *\n-from mantisshrimp.parsers.mixins import *\n+from mantisshrimp.parsers import *\n+\n+\n+def parser(\n+ annotations_file: Union[str, Path], img_dir: Union[str, Path]\n+) -> ParserInterface:\n+ annotations_dict = json.loads(Path(annotations_file).read())\n+\n+ image_info_parser = COCOImageInfoParser(\n+ infos=annotations_dict[\"images\"], img_dir=img_dir\n+ )\n+ annotations_parser = COCOAnnotationParser(\n+ annotations=annotations_dict[\"annotations\"]\n+ )\n+\n+ return CombinedParser(image_info_parser, annotations_parser)\n \n \n class COCOImageInfoParser(DefaultImageInfoParser):\n", "issue": "helper function for COCO parser\n## \ud83d\ude80 Feature\r\n**Is your feature request related to a problem? Please describe.**\r\nAs described in #79, it's currently very verbose to create a COCO parser, the steps should be ideally be reduced to a single function call.\r\n\r\n**Dream API**\r\n```python\r\n parser = datasets.coco.parser(\r\n annotations_file=\"path_to_annotations.json\",\r\n img_dir=\"path_to_images_dir\",\r\n )\r\n```\r\n\n", "before_files": [{"content": "__all__ = [\"COCOImageInfoParser\", \"COCOAnnotationParser\"]\n\nfrom mantisshrimp.imports import *\nfrom mantisshrimp.core import *\nfrom mantisshrimp.parsers.defaults import *\nfrom mantisshrimp.parsers.mixins import *\n\n\nclass COCOImageInfoParser(DefaultImageInfoParser):\n def __init__(self, infos, img_dir):\n super().__init__()\n self.infos = infos\n self.img_dir = img_dir\n\n def __iter__(self):\n yield from self.infos\n\n def __len__(self):\n return len(self.infos)\n\n def imageid(self, o) -> int:\n return o[\"id\"]\n\n def filepath(self, o) -> Union[str, Path]:\n return self.img_dir / o[\"file_name\"]\n\n def height(self, o) -> int:\n return o[\"height\"]\n\n def width(self, o) -> int:\n return o[\"width\"]\n\n\nclass COCOAnnotationParser(MaskRCNNParser, AreasParserMixin, IsCrowdsParserMixin):\n def __init__(self, annotations: list):\n self.annotations = annotations\n\n def __iter__(self):\n yield from self.annotations\n\n def __len__(self):\n return len(self.annotations)\n\n def imageid(self, o) -> int:\n return o[\"image_id\"]\n\n def labels(self, o) -> List[int]:\n return [o[\"category_id\"]]\n\n def bboxes(self, o) -> List[BBox]:\n return [BBox.from_xywh(*o[\"bbox\"])]\n\n def areas(self, o) -> List[float]:\n return [o[\"area\"]]\n\n def masks(self, o) -> List[MaskArray]:\n seg = o[\"segmentation\"]\n if o[\"iscrowd\"]:\n return [RLE.from_coco(seg[\"counts\"])]\n else:\n return [Polygon(seg)]\n\n def iscrowds(self, o) -> List[bool]:\n return [o[\"iscrowd\"]]\n", "path": "mantisshrimp/datasets/coco/parsers.py"}], "after_files": [{"content": "__all__ = [\"parser\", \"COCOImageInfoParser\", \"COCOAnnotationParser\"]\n\nfrom mantisshrimp.imports import *\nfrom mantisshrimp.core import *\nfrom mantisshrimp.parsers import *\n\n\ndef parser(\n annotations_file: Union[str, Path], img_dir: Union[str, Path]\n) -> ParserInterface:\n annotations_dict = json.loads(Path(annotations_file).read())\n\n image_info_parser = COCOImageInfoParser(\n infos=annotations_dict[\"images\"], img_dir=img_dir\n )\n annotations_parser = COCOAnnotationParser(\n annotations=annotations_dict[\"annotations\"]\n )\n\n return CombinedParser(image_info_parser, annotations_parser)\n\n\nclass COCOImageInfoParser(DefaultImageInfoParser):\n def __init__(self, infos, img_dir):\n super().__init__()\n self.infos = infos\n self.img_dir = img_dir\n\n def __iter__(self):\n yield from self.infos\n\n def __len__(self):\n return len(self.infos)\n\n def imageid(self, o) -> int:\n return o[\"id\"]\n\n def filepath(self, o) -> Union[str, Path]:\n return self.img_dir / o[\"file_name\"]\n\n def height(self, o) -> int:\n return o[\"height\"]\n\n def width(self, o) -> int:\n return o[\"width\"]\n\n\nclass COCOAnnotationParser(MaskRCNNParser, AreasParserMixin, IsCrowdsParserMixin):\n def __init__(self, annotations: list):\n self.annotations = annotations\n\n def __iter__(self):\n yield from self.annotations\n\n def __len__(self):\n return len(self.annotations)\n\n def imageid(self, o) -> int:\n return o[\"image_id\"]\n\n def labels(self, o) -> List[int]:\n return [o[\"category_id\"]]\n\n def bboxes(self, o) -> List[BBox]:\n return [BBox.from_xywh(*o[\"bbox\"])]\n\n def areas(self, o) -> List[float]:\n return [o[\"area\"]]\n\n def masks(self, o) -> List[MaskArray]:\n seg = o[\"segmentation\"]\n if o[\"iscrowd\"]:\n return [RLE.from_coco(seg[\"counts\"])]\n else:\n return [Polygon(seg)]\n\n def iscrowds(self, o) -> List[bool]:\n return [o[\"iscrowd\"]]\n", "path": "mantisshrimp/datasets/coco/parsers.py"}]}
921
276
gh_patches_debug_17904
rasdani/github-patches
git_diff
sopel-irc__sopel-983
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [currency] Currency codes are needlessly case-sensitive There's no reason that the currency codes should have to be capitalized by the user, is there? ``` [06:03:23] <dgw> ;cur 1 USD in CAD [06:03:24] <Sopel> 1.0 USD (U.S. dollar) = 1.386001386 CAD (Canadian Dollar) [06:03:28] <dgw> ;cur 1 usd in CAD [06:03:29] <Sopel> 1.0 usd (U.S. dollar) = 1.386001386 CAD (Canadian Dollar) [06:03:33] <dgw> ;cur 1 USD in cad [06:03:34] <Sopel> dgw: Unknown currency: cad ``` If no reason not to do so arises, I'll PR this one myself in a couple 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: `sopel/modules/currency.py` Content: ``` 1 # coding=utf-8 2 # Copyright 2013 Elsie Powell, embolalia.com 3 # Licensed under the Eiffel Forum License 2 4 from __future__ import unicode_literals, absolute_import, print_function, division 5 6 import json 7 import xmltodict 8 import re 9 10 from sopel import web 11 from sopel.module import commands, example, NOLIMIT 12 13 # The Canadian central bank has better exchange rate data than the Fed, the 14 # Bank of England, or the European Central Bank. Who knew? 15 base_url = 'http://www.bankofcanada.ca/stats/assets/rates_rss/noon/en_{}.xml' 16 regex = re.compile(r''' 17 (\d+(?:\.\d+)?) # Decimal number 18 \s*([a-zA-Z]{3}) # 3-letter currency code 19 \s+(?:in|as|of|to)\s+ # preposition 20 ([a-zA-Z]{3}) # 3-letter currency code 21 ''', re.VERBOSE) 22 23 24 def get_rate(code): 25 if code.upper() == 'CAD': 26 return 1, 'Canadian Dollar' 27 elif code.upper() == 'BTC': 28 rates = json.loads(web.get('https://api.bitcoinaverage.com/ticker/all')) 29 return 1 / rates['CAD']['24h_avg'], 'Bitcoin—24hr average' 30 31 data, headers = web.get(base_url.format(code), dont_decode=True, return_headers=True) 32 if headers['_http_status'] == 404: 33 return False, False 34 namespaces = { 35 'http://www.cbwiki.net/wiki/index.php/Specification_1.1': 'cb', 36 'http://purl.org/rss/1.0/': None, 37 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf' } 38 xml = xmltodict.parse(data, process_namespaces=True, namespaces=namespaces).get('rdf:RDF') 39 namestring = xml.get('channel').get('title').get('#text') 40 name = namestring[len('Bank of Canada noon rate: '):] 41 name = re.sub(r'\s*\(noon\)\s*', '', name) 42 rate = xml.get('item').get('cb:statistics').get('cb:exchangeRate').get('cb:value').get('#text') 43 return float(rate), name 44 45 46 @commands('cur', 'currency', 'exchange') 47 @example('.cur 20 EUR in USD') 48 def exchange(bot, trigger): 49 """Show the exchange rate between two currencies""" 50 if not trigger.group(2): 51 return bot.reply("No search term. An example: .cur 20 EUR in USD") 52 match = regex.match(trigger.group(2)) 53 if not match: 54 # It's apologetic, because it's using Canadian data. 55 bot.reply("Sorry, I didn't understand the input.") 56 return NOLIMIT 57 58 amount, of, to = match.groups() 59 try: 60 amount = float(amount) 61 except: 62 bot.reply("Sorry, I didn't understand the input.") 63 display(bot, amount, of, to) 64 65 66 def display(bot, amount, of, to): 67 if not amount: 68 bot.reply("Zero is zero, no matter what country you're in.") 69 try: 70 of_rate, of_name = get_rate(of) 71 if not of_name: 72 bot.reply("Unknown currency: %s" % of) 73 return 74 to_rate, to_name = get_rate(to) 75 if not to_name: 76 bot.reply("Unknown currency: %s" % to) 77 return 78 except Exception as e: 79 raise 80 bot.reply("Something went wrong while I was getting the exchange rate.") 81 return NOLIMIT 82 83 result = amount / of_rate * to_rate 84 bot.say("{} {} ({}) = {} {} ({})".format(amount, of, of_name, 85 result, to, to_name)) 86 87 88 @commands('btc', 'bitcoin') 89 @example('.btc 20 EUR') 90 def bitcoin(bot, trigger): 91 #if 2 args, 1st is number and 2nd is currency. If 1 arg, it's either the number or the currency. 92 to = trigger.group(4) 93 amount = trigger.group(3) 94 if not to: 95 to = trigger.group(3) or 'USD' 96 amount = 1 97 98 try: 99 amount = float(amount) 100 except: 101 bot.reply("Sorry, I didn't understand the input.") 102 return NOLIMIT 103 104 display(bot, amount, 'BTC', to) 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/sopel/modules/currency.py b/sopel/modules/currency.py --- a/sopel/modules/currency.py +++ b/sopel/modules/currency.py @@ -26,9 +26,10 @@ def get_rate(code): - if code.upper() == 'CAD': + code = code.upper() + if code == 'CAD': return 1, 'Canadian Dollar' - elif code.upper() == 'BTC': + elif code == 'BTC': rates = json.loads(web.get('https://api.bitcoinaverage.com/ticker/all')) return 1 / rates['CAD']['24h_avg'], 'Bitcoin—24hr average' @@ -85,8 +86,8 @@ return NOLIMIT result = amount / of_rate * to_rate - bot.say("{} {} ({}) = {} {} ({})".format(amount, of, of_name, - result, to, to_name)) + bot.say("{} {} ({}) = {} {} ({})".format(amount, of.upper(), of_name, + result, to.upper(), to_name)) @commands('btc', 'bitcoin')
{"golden_diff": "diff --git a/sopel/modules/currency.py b/sopel/modules/currency.py\n--- a/sopel/modules/currency.py\n+++ b/sopel/modules/currency.py\n@@ -26,9 +26,10 @@\n \n \n def get_rate(code):\n- if code.upper() == 'CAD':\n+ code = code.upper()\n+ if code == 'CAD':\n return 1, 'Canadian Dollar'\n- elif code.upper() == 'BTC':\n+ elif code == 'BTC':\n rates = json.loads(web.get('https://api.bitcoinaverage.com/ticker/all'))\n return 1 / rates['CAD']['24h_avg'], 'Bitcoin\u201424hr average'\n \n@@ -85,8 +86,8 @@\n return NOLIMIT\n \n result = amount / of_rate * to_rate\n- bot.say(\"{} {} ({}) = {} {} ({})\".format(amount, of, of_name,\n- result, to, to_name))\n+ bot.say(\"{} {} ({}) = {} {} ({})\".format(amount, of.upper(), of_name,\n+ result, to.upper(), to_name))\n \n \n @commands('btc', 'bitcoin')\n", "issue": "[currency] Currency codes are needlessly case-sensitive\nThere's no reason that the currency codes should have to be capitalized by the user, is there?\n\n```\n[06:03:23] <dgw> ;cur 1 USD in CAD\n[06:03:24] <Sopel> 1.0 USD (U.S. dollar) = 1.386001386 CAD (Canadian Dollar)\n[06:03:28] <dgw> ;cur 1 usd in CAD\n[06:03:29] <Sopel> 1.0 usd (U.S. dollar) = 1.386001386 CAD (Canadian Dollar)\n[06:03:33] <dgw> ;cur 1 USD in cad\n[06:03:34] <Sopel> dgw: Unknown currency: cad\n```\n\nIf no reason not to do so arises, I'll PR this one myself in a couple days.\n\n", "before_files": [{"content": "# coding=utf-8\n# Copyright 2013 Elsie Powell, embolalia.com\n# Licensed under the Eiffel Forum License 2\nfrom __future__ import unicode_literals, absolute_import, print_function, division\n\nimport json\nimport xmltodict\nimport re\n\nfrom sopel import web\nfrom sopel.module import commands, example, NOLIMIT\n\n# The Canadian central bank has better exchange rate data than the Fed, the\n# Bank of England, or the European Central Bank. Who knew?\nbase_url = 'http://www.bankofcanada.ca/stats/assets/rates_rss/noon/en_{}.xml'\nregex = re.compile(r'''\n (\\d+(?:\\.\\d+)?) # Decimal number\n \\s*([a-zA-Z]{3}) # 3-letter currency code\n \\s+(?:in|as|of|to)\\s+ # preposition\n ([a-zA-Z]{3}) # 3-letter currency code\n ''', re.VERBOSE)\n\n\ndef get_rate(code):\n if code.upper() == 'CAD':\n return 1, 'Canadian Dollar'\n elif code.upper() == 'BTC':\n rates = json.loads(web.get('https://api.bitcoinaverage.com/ticker/all'))\n return 1 / rates['CAD']['24h_avg'], 'Bitcoin\u201424hr average'\n\n data, headers = web.get(base_url.format(code), dont_decode=True, return_headers=True)\n if headers['_http_status'] == 404:\n return False, False\n namespaces = {\n 'http://www.cbwiki.net/wiki/index.php/Specification_1.1': 'cb',\n 'http://purl.org/rss/1.0/': None,\n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf' }\n xml = xmltodict.parse(data, process_namespaces=True, namespaces=namespaces).get('rdf:RDF')\n namestring = xml.get('channel').get('title').get('#text')\n name = namestring[len('Bank of Canada noon rate: '):]\n name = re.sub(r'\\s*\\(noon\\)\\s*', '', name)\n rate = xml.get('item').get('cb:statistics').get('cb:exchangeRate').get('cb:value').get('#text')\n return float(rate), name\n\n\n@commands('cur', 'currency', 'exchange')\n@example('.cur 20 EUR in USD')\ndef exchange(bot, trigger):\n \"\"\"Show the exchange rate between two currencies\"\"\"\n if not trigger.group(2):\n return bot.reply(\"No search term. An example: .cur 20 EUR in USD\")\n match = regex.match(trigger.group(2))\n if not match:\n # It's apologetic, because it's using Canadian data.\n bot.reply(\"Sorry, I didn't understand the input.\")\n return NOLIMIT\n\n amount, of, to = match.groups()\n try:\n amount = float(amount)\n except:\n bot.reply(\"Sorry, I didn't understand the input.\")\n display(bot, amount, of, to)\n\n\ndef display(bot, amount, of, to):\n if not amount:\n bot.reply(\"Zero is zero, no matter what country you're in.\")\n try:\n of_rate, of_name = get_rate(of)\n if not of_name:\n bot.reply(\"Unknown currency: %s\" % of)\n return\n to_rate, to_name = get_rate(to)\n if not to_name:\n bot.reply(\"Unknown currency: %s\" % to)\n return\n except Exception as e:\n raise\n bot.reply(\"Something went wrong while I was getting the exchange rate.\")\n return NOLIMIT\n\n result = amount / of_rate * to_rate\n bot.say(\"{} {} ({}) = {} {} ({})\".format(amount, of, of_name,\n result, to, to_name))\n\n\n@commands('btc', 'bitcoin')\n@example('.btc 20 EUR')\ndef bitcoin(bot, trigger):\n #if 2 args, 1st is number and 2nd is currency. If 1 arg, it's either the number or the currency.\n to = trigger.group(4)\n amount = trigger.group(3)\n if not to:\n to = trigger.group(3) or 'USD'\n amount = 1\n\n try:\n amount = float(amount)\n except:\n bot.reply(\"Sorry, I didn't understand the input.\")\n return NOLIMIT\n\n display(bot, amount, 'BTC', to)\n", "path": "sopel/modules/currency.py"}], "after_files": [{"content": "# coding=utf-8\n\"\"\"currency.py - Sopel Exchange Rate Module\nCopyright 2013 Edward Powell, embolalia.com\nLicensed under the Eiffel Forum License 2\n\nhttp://sopel.chat\n\"\"\"\nfrom __future__ import unicode_literals, absolute_import, print_function, division\n\nimport json\nimport xmltodict\nimport re\n\nfrom sopel import web\nfrom sopel.module import commands, example, NOLIMIT\n\n# The Canadian central bank has better exchange rate data than the Fed, the\n# Bank of England, or the European Central Bank. Who knew?\nbase_url = 'http://www.bankofcanada.ca/stats/assets/rates_rss/noon/en_{}.xml'\nregex = re.compile(r'''\n (\\d+(?:\\.\\d+)?) # Decimal number\n \\s*([a-zA-Z]{3}) # 3-letter currency code\n \\s+(?:in|as|of|to)\\s+ # preposition\n ([a-zA-Z]{3}) # 3-letter currency code\n ''', re.VERBOSE)\n\n\ndef get_rate(code):\n code = code.upper()\n if code == 'CAD':\n return 1, 'Canadian Dollar'\n elif code == 'BTC':\n rates = json.loads(web.get('https://api.bitcoinaverage.com/ticker/all'))\n return 1 / rates['CAD']['24h_avg'], 'Bitcoin\u201424hr average'\n\n data, headers = web.get(base_url.format(code), dont_decode=True, return_headers=True)\n if headers['_http_status'] == 404:\n return False, False\n namespaces = {\n 'http://www.cbwiki.net/wiki/index.php/Specification_1.1': 'cb', \n 'http://purl.org/rss/1.0/': None, \n 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf' }\n xml = xmltodict.parse(data, process_namespaces=True, namespaces=namespaces).get('rdf:RDF')\n namestring = xml.get('channel').get('title').get('#text')\n name = namestring[len('Bank of Canada noon rate: '):]\n name = re.sub(r'\\s*\\(noon\\)\\s*', '', name)\n rate = xml.get('item').get('cb:statistics').get('cb:exchangeRate').get('cb:value').get('#text')\n return float(rate), name\n\n\n@commands('cur', 'currency', 'exchange')\n@example('.cur 20 EUR in USD')\ndef exchange(bot, trigger):\n \"\"\"Show the exchange rate between two currencies\"\"\"\n if not trigger.group(2):\n return bot.reply(\"No search term. An example: .cur 20 EUR in USD\")\n match = regex.match(trigger.group(2))\n if not match:\n # It's apologetic, because it's using Canadian data.\n bot.reply(\"Sorry, I didn't understand the input.\")\n return NOLIMIT\n\n amount, of, to = match.groups()\n try:\n amount = float(amount)\n except:\n bot.reply(\"Sorry, I didn't understand the input.\")\n display(bot, amount, of, to)\n\n\ndef display(bot, amount, of, to):\n if not amount:\n bot.reply(\"Zero is zero, no matter what country you're in.\")\n try:\n of_rate, of_name = get_rate(of)\n if not of_name:\n bot.reply(\"Unknown currency: %s\" % of)\n return\n to_rate, to_name = get_rate(to)\n if not to_name:\n bot.reply(\"Unknown currency: %s\" % to)\n return\n except Exception as e:\n raise\n bot.reply(\"Something went wrong while I was getting the exchange rate.\")\n return NOLIMIT\n\n result = amount / of_rate * to_rate\n bot.say(\"{} {} ({}) = {} {} ({})\".format(amount, of.upper(), of_name,\n result, to.upper(), to_name))\n\n\n@commands('btc', 'bitcoin')\n@example('.btc 20 EUR')\ndef bitcoin(bot, trigger):\n #if 2 args, 1st is number and 2nd is currency. If 1 arg, it's either the number or the currency.\n to = trigger.group(4)\n amount = trigger.group(3)\n if not to:\n to = trigger.group(3) or 'USD'\n amount = 1\n\n try:\n amount = float(amount)\n except:\n bot.reply(\"Sorry, I didn't understand the input.\")\n return NOLIMIT\n\n display(bot, amount, 'BTC', to)\n", "path": "sopel/modules/currency.py"}]}
1,701
255
gh_patches_debug_9215
rasdani/github-patches
git_diff
meltano__meltano-6321
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `meltano --help` fails on Windows in some environments Running any Meltano command in my fresh Windows VM results in the following error: ![image](https://user-images.githubusercontent.com/11428666/176504379-a9489721-09b5-4a2d-ad83-c2f5a37adfb0.png) Sorry for the image of text - I forgot to enable the shared clipboard for the VM. The failure is happening here: ```python freedesktop_data = ( platform.freedesktop_os_release() if safe_hasattr(platform, "freedesktop_os_release") else defaultdict(type(None)) ) ``` This might be because I'm running under git bash instead of Powershell. We had assumed that if `freedesktop_os_release` is present, it will work. This is apparently only sometimes true. To prevent problems for Windows users we should put the call to `platform.freedesktop_os_release` in a try-except block. Doing so will also mean we no longer need to call `hasattr`. --- 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/core/tracking/contexts/environment.py` Content: ``` 1 """Environment context for the Snowplow tracker.""" 2 3 from __future__ import annotations 4 5 import os 6 import platform 7 import uuid 8 from collections import defaultdict 9 from datetime import datetime 10 from pathlib import Path 11 from typing import Any 12 13 import psutil 14 from cached_property import cached_property 15 from snowplow_tracker import SelfDescribingJson 16 from structlog.stdlib import get_logger 17 18 import meltano 19 from meltano.core.tracking.schemas import EnvironmentContextSchema 20 from meltano.core.utils import hash_sha256, safe_hasattr 21 22 logger = get_logger(__name__) 23 24 # This file is only ever created in CI when building a release 25 release_marker_path = Path(__file__).parent / ".release_marker" 26 27 28 class EnvironmentContext(SelfDescribingJson): 29 """Environment context for the Snowplow tracker.""" 30 31 def __init__(self): 32 """Initialize the environment context.""" 33 ci_markers = ("GITHUB_ACTIONS", "CI") 34 super().__init__( 35 EnvironmentContextSchema.url, 36 { 37 "context_uuid": str(uuid.uuid4()), 38 "meltano_version": meltano.__version__, 39 "is_dev_build": not release_marker_path.exists(), 40 "is_ci_environment": any( 41 # True if 'true', 'TRUE', 'True', or '1' 42 os.environ.get(marker, "").lower()[:1] in {"1", "t"} 43 for marker in ci_markers 44 ), 45 "python_version": platform.python_version(), 46 "python_implementation": platform.python_implementation(), 47 **self.system_info, 48 **self.process_info, 49 }, 50 ) 51 52 @cached_property 53 def system_info(self) -> dict[str, Any]: 54 """Get system information. 55 56 Returns: 57 A dictionary containing system information. 58 """ 59 freedesktop_data = ( 60 platform.freedesktop_os_release() 61 if safe_hasattr(platform, "freedesktop_os_release") 62 else defaultdict(type(None)) 63 ) 64 65 return { 66 "system_name": platform.system() or None, 67 "system_release": platform.release() or None, 68 "system_version": platform.version() or None, 69 "machine": platform.machine() or None, 70 "windows_edition": platform.win32_edition() 71 if safe_hasattr(platform, "win32_edition") 72 else None, 73 "freedesktop_id": freedesktop_data["ID"], 74 "freedesktop_id_like": freedesktop_data.get("ID_LIKE", None), 75 "freedesktop_version_id": freedesktop_data.get("VERSION_ID", None), 76 } 77 78 @staticmethod 79 def get_process_timestamp(process: psutil.Process) -> str: 80 """Obtain the creation time of a process as a ISO 8601 timestamp. 81 82 Args: 83 process: The process to obtain the creation time from. 84 85 Returns: 86 A ISO 8601 timestamp formatted string. 87 """ 88 return f"{datetime.utcfromtimestamp(process.create_time()).isoformat()}Z" 89 90 @cached_property 91 def process_info(self) -> dict[str, Any]: 92 """Obtain the process information for the current process. 93 94 Returns: 95 A dictionary containing the process information. Such as the hashed process name, pid, core counts, etc 96 """ 97 process = psutil.Process() 98 with process.oneshot(): 99 return { 100 "num_cpu_cores": psutil.cpu_count(), 101 "num_cpu_cores_available": self.num_available_cores, 102 "process_hierarchy": [ 103 { 104 "process_name_hash": hash_sha256(proc.name()), 105 "process_creation_timestamp": self.get_process_timestamp(proc), 106 } 107 for proc in (process, *process.parents()) 108 ], 109 } 110 111 @cached_property 112 def num_available_cores(self) -> int: 113 """Obtain the number of available CPU cores. 114 115 Uses sched_getaffinity where available, otherwise falls back to cpu_count(). 116 117 Returns: 118 int: The number of available CPU cores. 119 """ 120 if safe_hasattr(os, "sched_getaffinity"): 121 return len(os.sched_getaffinity(0)) 122 return os.cpu_count() 123 124 125 environment_context = EnvironmentContext() 126 ``` --- 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/core/tracking/contexts/environment.py b/src/meltano/core/tracking/contexts/environment.py --- a/src/meltano/core/tracking/contexts/environment.py +++ b/src/meltano/core/tracking/contexts/environment.py @@ -56,11 +56,10 @@ Returns: A dictionary containing system information. """ - freedesktop_data = ( - platform.freedesktop_os_release() - if safe_hasattr(platform, "freedesktop_os_release") - else defaultdict(type(None)) - ) + try: + freedesktop_data = platform.freedesktop_os_release() + except Exception: + freedesktop_data = defaultdict(type(None)) return { "system_name": platform.system() or None,
{"golden_diff": "diff --git a/src/meltano/core/tracking/contexts/environment.py b/src/meltano/core/tracking/contexts/environment.py\n--- a/src/meltano/core/tracking/contexts/environment.py\n+++ b/src/meltano/core/tracking/contexts/environment.py\n@@ -56,11 +56,10 @@\n Returns:\n A dictionary containing system information.\n \"\"\"\n- freedesktop_data = (\n- platform.freedesktop_os_release()\n- if safe_hasattr(platform, \"freedesktop_os_release\")\n- else defaultdict(type(None))\n- )\n+ try:\n+ freedesktop_data = platform.freedesktop_os_release()\n+ except Exception:\n+ freedesktop_data = defaultdict(type(None))\n \n return {\n \"system_name\": platform.system() or None,\n", "issue": "`meltano --help` fails on Windows in some environments\nRunning any Meltano command in my fresh Windows VM results in the following error:\r\n\r\n![image](https://user-images.githubusercontent.com/11428666/176504379-a9489721-09b5-4a2d-ad83-c2f5a37adfb0.png)\r\n\r\nSorry for the image of text - I forgot to enable the shared clipboard for the VM.\r\n\r\nThe failure is happening here:\r\n\r\n```python\r\n freedesktop_data = (\r\n platform.freedesktop_os_release()\r\n if safe_hasattr(platform, \"freedesktop_os_release\")\r\n else defaultdict(type(None))\r\n )\r\n```\r\n\r\nThis might be because I'm running under git bash instead of Powershell.\r\n\r\nWe had assumed that if `freedesktop_os_release` is present, it will work. This is apparently only sometimes true. To prevent problems for Windows users we should put the call to `platform.freedesktop_os_release` in a try-except block. Doing so will also mean we no longer need to call `hasattr`.\n", "before_files": [{"content": "\"\"\"Environment context for the Snowplow tracker.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport platform\nimport uuid\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Any\n\nimport psutil\nfrom cached_property import cached_property\nfrom snowplow_tracker import SelfDescribingJson\nfrom structlog.stdlib import get_logger\n\nimport meltano\nfrom meltano.core.tracking.schemas import EnvironmentContextSchema\nfrom meltano.core.utils import hash_sha256, safe_hasattr\n\nlogger = get_logger(__name__)\n\n# This file is only ever created in CI when building a release\nrelease_marker_path = Path(__file__).parent / \".release_marker\"\n\n\nclass EnvironmentContext(SelfDescribingJson):\n \"\"\"Environment context for the Snowplow tracker.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the environment context.\"\"\"\n ci_markers = (\"GITHUB_ACTIONS\", \"CI\")\n super().__init__(\n EnvironmentContextSchema.url,\n {\n \"context_uuid\": str(uuid.uuid4()),\n \"meltano_version\": meltano.__version__,\n \"is_dev_build\": not release_marker_path.exists(),\n \"is_ci_environment\": any(\n # True if 'true', 'TRUE', 'True', or '1'\n os.environ.get(marker, \"\").lower()[:1] in {\"1\", \"t\"}\n for marker in ci_markers\n ),\n \"python_version\": platform.python_version(),\n \"python_implementation\": platform.python_implementation(),\n **self.system_info,\n **self.process_info,\n },\n )\n\n @cached_property\n def system_info(self) -> dict[str, Any]:\n \"\"\"Get system information.\n\n Returns:\n A dictionary containing system information.\n \"\"\"\n freedesktop_data = (\n platform.freedesktop_os_release()\n if safe_hasattr(platform, \"freedesktop_os_release\")\n else defaultdict(type(None))\n )\n\n return {\n \"system_name\": platform.system() or None,\n \"system_release\": platform.release() or None,\n \"system_version\": platform.version() or None,\n \"machine\": platform.machine() or None,\n \"windows_edition\": platform.win32_edition()\n if safe_hasattr(platform, \"win32_edition\")\n else None,\n \"freedesktop_id\": freedesktop_data[\"ID\"],\n \"freedesktop_id_like\": freedesktop_data.get(\"ID_LIKE\", None),\n \"freedesktop_version_id\": freedesktop_data.get(\"VERSION_ID\", None),\n }\n\n @staticmethod\n def get_process_timestamp(process: psutil.Process) -> str:\n \"\"\"Obtain the creation time of a process as a ISO 8601 timestamp.\n\n Args:\n process: The process to obtain the creation time from.\n\n Returns:\n A ISO 8601 timestamp formatted string.\n \"\"\"\n return f\"{datetime.utcfromtimestamp(process.create_time()).isoformat()}Z\"\n\n @cached_property\n def process_info(self) -> dict[str, Any]:\n \"\"\"Obtain the process information for the current process.\n\n Returns:\n A dictionary containing the process information. Such as the hashed process name, pid, core counts, etc\n \"\"\"\n process = psutil.Process()\n with process.oneshot():\n return {\n \"num_cpu_cores\": psutil.cpu_count(),\n \"num_cpu_cores_available\": self.num_available_cores,\n \"process_hierarchy\": [\n {\n \"process_name_hash\": hash_sha256(proc.name()),\n \"process_creation_timestamp\": self.get_process_timestamp(proc),\n }\n for proc in (process, *process.parents())\n ],\n }\n\n @cached_property\n def num_available_cores(self) -> int:\n \"\"\"Obtain the number of available CPU cores.\n\n Uses sched_getaffinity where available, otherwise falls back to cpu_count().\n\n Returns:\n int: The number of available CPU cores.\n \"\"\"\n if safe_hasattr(os, \"sched_getaffinity\"):\n return len(os.sched_getaffinity(0))\n return os.cpu_count()\n\n\nenvironment_context = EnvironmentContext()\n", "path": "src/meltano/core/tracking/contexts/environment.py"}], "after_files": [{"content": "\"\"\"Environment context for the Snowplow tracker.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport platform\nimport uuid\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Any\n\nimport psutil\nfrom cached_property import cached_property\nfrom snowplow_tracker import SelfDescribingJson\nfrom structlog.stdlib import get_logger\n\nimport meltano\nfrom meltano.core.tracking.schemas import EnvironmentContextSchema\nfrom meltano.core.utils import hash_sha256, safe_hasattr\n\nlogger = get_logger(__name__)\n\n# This file is only ever created in CI when building a release\nrelease_marker_path = Path(__file__).parent / \".release_marker\"\n\n\nclass EnvironmentContext(SelfDescribingJson):\n \"\"\"Environment context for the Snowplow tracker.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the environment context.\"\"\"\n ci_markers = (\"GITHUB_ACTIONS\", \"CI\")\n super().__init__(\n EnvironmentContextSchema.url,\n {\n \"context_uuid\": str(uuid.uuid4()),\n \"meltano_version\": meltano.__version__,\n \"is_dev_build\": not release_marker_path.exists(),\n \"is_ci_environment\": any(\n # True if 'true', 'TRUE', 'True', or '1'\n os.environ.get(marker, \"\").lower()[:1] in {\"1\", \"t\"}\n for marker in ci_markers\n ),\n \"python_version\": platform.python_version(),\n \"python_implementation\": platform.python_implementation(),\n **self.system_info,\n **self.process_info,\n },\n )\n\n @cached_property\n def system_info(self) -> dict[str, Any]:\n \"\"\"Get system information.\n\n Returns:\n A dictionary containing system information.\n \"\"\"\n try:\n freedesktop_data = platform.freedesktop_os_release()\n except Exception:\n freedesktop_data = defaultdict(type(None))\n\n return {\n \"system_name\": platform.system() or None,\n \"system_release\": platform.release() or None,\n \"system_version\": platform.version() or None,\n \"machine\": platform.machine() or None,\n \"windows_edition\": platform.win32_edition()\n if safe_hasattr(platform, \"win32_edition\")\n else None,\n \"freedesktop_id\": freedesktop_data[\"ID\"],\n \"freedesktop_id_like\": freedesktop_data.get(\"ID_LIKE\", None),\n \"freedesktop_version_id\": freedesktop_data.get(\"VERSION_ID\", None),\n }\n\n @staticmethod\n def get_process_timestamp(process: psutil.Process) -> str:\n \"\"\"Obtain the creation time of a process as a ISO 8601 timestamp.\n\n Args:\n process: The process to obtain the creation time from.\n\n Returns:\n A ISO 8601 timestamp formatted string.\n \"\"\"\n return f\"{datetime.utcfromtimestamp(process.create_time()).isoformat()}Z\"\n\n @cached_property\n def process_info(self) -> dict[str, Any]:\n \"\"\"Obtain the process information for the current process.\n\n Returns:\n A dictionary containing the process information. Such as the hashed process name, pid, core counts, etc\n \"\"\"\n process = psutil.Process()\n with process.oneshot():\n return {\n \"num_cpu_cores\": psutil.cpu_count(),\n \"num_cpu_cores_available\": self.num_available_cores,\n \"process_hierarchy\": [\n {\n \"process_name_hash\": hash_sha256(proc.name()),\n \"process_creation_timestamp\": self.get_process_timestamp(proc),\n }\n for proc in (process, *process.parents())\n ],\n }\n\n @cached_property\n def num_available_cores(self) -> int:\n \"\"\"Obtain the number of available CPU cores.\n\n Uses sched_getaffinity where available, otherwise falls back to cpu_count().\n\n Returns:\n int: The number of available CPU cores.\n \"\"\"\n if safe_hasattr(os, \"sched_getaffinity\"):\n return len(os.sched_getaffinity(0))\n return os.cpu_count()\n\n\nenvironment_context = EnvironmentContext()\n", "path": "src/meltano/core/tracking/contexts/environment.py"}]}
1,650
170
gh_patches_debug_23649
rasdani/github-patches
git_diff
alltheplaces__alltheplaces-5403
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- enterprise car hire spider missing ~6k outlets In the latest run of the enterprise.py spider from 2023-05-15, there are around 6000 fewer results than in the previous run from 2023-04-15. I think the cause is that the search API that ATP uses is no longer returning results for some major countries. For example, the following still work: * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/IT * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/BE * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/MX but the following do not: * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/GB * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/US * https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/FR I'm not sure why the API has stopped returning for certain countries, or if there's anything we can do about it. If we want to look at alternative means, then it's possible that the "Airport Locations" and "Neighbourhood Locations" lists at https://www.enterprise.co.uk/en/car-hire/locations/uk.html are complete for GB. (Together they have 427 locations, compared with the 425 I extracted for my Chain Reaction tool from a previous ATP dataset.) But then you'd need to parse each branch page, and that's a lot more HTTP fetches. I haven't looked what other localised sites do in terms of location lists. --- 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/enterprise.py` Content: ``` 1 import geonamescache 2 from scrapy import Spider 3 from scrapy.http import JsonRequest 4 5 from locations.dict_parser import DictParser 6 7 8 class EnterpriseSpider(Spider): 9 name = "enterprise" 10 item_attributes = {"brand": "Enterprise Rent-A-Car", "brand_wikidata": "Q17085454"} 11 allowed_domains = ["prd.location.enterprise.com"] 12 13 def start_requests(self): 14 gc = geonamescache.GeonamesCache() 15 countries = gc.get_countries() 16 for country_code in countries.keys(): 17 yield JsonRequest( 18 url=f"https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}" 19 ) 20 21 def parse(self, response): 22 for location in response.json(): 23 if location["closed"] or not location["physicalLocation"]: 24 continue 25 item = DictParser.parse(location) 26 item["ref"] = location["stationId"] 27 item["name"] = location["locationNameTranslation"] 28 item["street_address"] = ", ".join(filter(None, location["addressLines"])) 29 item["phone"] = location["formattedPhone"] 30 yield item 31 ``` --- 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/enterprise.py b/locations/spiders/enterprise.py --- a/locations/spiders/enterprise.py +++ b/locations/spiders/enterprise.py @@ -8,15 +8,20 @@ class EnterpriseSpider(Spider): name = "enterprise" item_attributes = {"brand": "Enterprise Rent-A-Car", "brand_wikidata": "Q17085454"} - allowed_domains = ["prd.location.enterprise.com"] + allowed_domains = ["prd.location.enterprise.com", "int1.location.enterprise.com"] def start_requests(self): gc = geonamescache.GeonamesCache() countries = gc.get_countries() for country_code in countries.keys(): - yield JsonRequest( - url=f"https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}" - ) + # It appears that countries are sharded between two + # servers. Other servers are int2, xqa1, xqa2, xqa3 + # but search of these servers reveals no additional + # locations on top of just prd and int1. + for subdomain in ["prd", "int1"]: + yield JsonRequest( + url=f"https://{subdomain}.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}" + ) def parse(self, response): for location in response.json():
{"golden_diff": "diff --git a/locations/spiders/enterprise.py b/locations/spiders/enterprise.py\n--- a/locations/spiders/enterprise.py\n+++ b/locations/spiders/enterprise.py\n@@ -8,15 +8,20 @@\n class EnterpriseSpider(Spider):\n name = \"enterprise\"\n item_attributes = {\"brand\": \"Enterprise Rent-A-Car\", \"brand_wikidata\": \"Q17085454\"}\n- allowed_domains = [\"prd.location.enterprise.com\"]\n+ allowed_domains = [\"prd.location.enterprise.com\", \"int1.location.enterprise.com\"]\n \n def start_requests(self):\n gc = geonamescache.GeonamesCache()\n countries = gc.get_countries()\n for country_code in countries.keys():\n- yield JsonRequest(\n- url=f\"https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}\"\n- )\n+ # It appears that countries are sharded between two\n+ # servers. Other servers are int2, xqa1, xqa2, xqa3\n+ # but search of these servers reveals no additional\n+ # locations on top of just prd and int1.\n+ for subdomain in [\"prd\", \"int1\"]:\n+ yield JsonRequest(\n+ url=f\"https://{subdomain}.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}\"\n+ )\n \n def parse(self, response):\n for location in response.json():\n", "issue": "enterprise car hire spider missing ~6k outlets\nIn the latest run of the enterprise.py spider from 2023-05-15, there are around 6000 fewer results than in the previous run from 2023-04-15.\r\n\r\nI think the cause is that the search API that ATP uses is no longer returning results for some major countries. For example, the following still work:\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/IT\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/BE\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/MX\r\n\r\nbut the following do not:\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/GB\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/US\r\n* https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/FR\r\n\r\nI'm not sure why the API has stopped returning for certain countries, or if there's anything we can do about it.\r\n\r\nIf we want to look at alternative means, then it's possible that the \"Airport Locations\" and \"Neighbourhood Locations\" lists at https://www.enterprise.co.uk/en/car-hire/locations/uk.html are complete for GB. (Together they have 427 locations, compared with the 425 I extracted for my Chain Reaction tool from a previous ATP dataset.) But then you'd need to parse each branch page, and that's a lot more HTTP fetches. I haven't looked what other localised sites do in terms of location lists.\n", "before_files": [{"content": "import geonamescache\nfrom scrapy import Spider\nfrom scrapy.http import JsonRequest\n\nfrom locations.dict_parser import DictParser\n\n\nclass EnterpriseSpider(Spider):\n name = \"enterprise\"\n item_attributes = {\"brand\": \"Enterprise Rent-A-Car\", \"brand_wikidata\": \"Q17085454\"}\n allowed_domains = [\"prd.location.enterprise.com\"]\n\n def start_requests(self):\n gc = geonamescache.GeonamesCache()\n countries = gc.get_countries()\n for country_code in countries.keys():\n yield JsonRequest(\n url=f\"https://prd.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}\"\n )\n\n def parse(self, response):\n for location in response.json():\n if location[\"closed\"] or not location[\"physicalLocation\"]:\n continue\n item = DictParser.parse(location)\n item[\"ref\"] = location[\"stationId\"]\n item[\"name\"] = location[\"locationNameTranslation\"]\n item[\"street_address\"] = \", \".join(filter(None, location[\"addressLines\"]))\n item[\"phone\"] = location[\"formattedPhone\"]\n yield item\n", "path": "locations/spiders/enterprise.py"}], "after_files": [{"content": "import geonamescache\nfrom scrapy import Spider\nfrom scrapy.http import JsonRequest\n\nfrom locations.dict_parser import DictParser\n\n\nclass EnterpriseSpider(Spider):\n name = \"enterprise\"\n item_attributes = {\"brand\": \"Enterprise Rent-A-Car\", \"brand_wikidata\": \"Q17085454\"}\n allowed_domains = [\"prd.location.enterprise.com\", \"int1.location.enterprise.com\"]\n\n def start_requests(self):\n gc = geonamescache.GeonamesCache()\n countries = gc.get_countries()\n for country_code in countries.keys():\n # It appears that countries are sharded between two\n # servers. Other servers are int2, xqa1, xqa2, xqa3\n # but search of these servers reveals no additional\n # locations on top of just prd and int1.\n for subdomain in [\"prd\", \"int1\"]:\n yield JsonRequest(\n url=f\"https://{subdomain}.location.enterprise.com/enterprise-sls/search/location/enterprise/web/country/{country_code}\"\n )\n\n def parse(self, response):\n for location in response.json():\n if location[\"closed\"] or not location[\"physicalLocation\"]:\n continue\n item = DictParser.parse(location)\n item[\"ref\"] = location[\"stationId\"]\n item[\"name\"] = location[\"locationNameTranslation\"]\n item[\"street_address\"] = \", \".join(filter(None, location[\"addressLines\"]))\n item[\"phone\"] = location[\"formattedPhone\"]\n yield item\n", "path": "locations/spiders/enterprise.py"}]}
916
317
gh_patches_debug_6733
rasdani/github-patches
git_diff
mitmproxy__mitmproxy-5894
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- "raw" view is not raw, adds extra backslash #### Problem Description I just noticed during https://github.com/mitmproxy/mitmproxy/issues/5469#issuecomment-1191343747 #### Steps to reproduce the behavior: http.txt ``` HTTP/1.1 200 OK Content-Type: text/plain Content-Length: 1 \ ``` 1. `ncat -l 1337 < http.txt` 2. `mitmproxy` 3. `curl --proxy localhost:8080 http://127.0.0.1:1337` raw is `\\`: ![image](https://user-images.githubusercontent.com/679144/180199838-07c02668-5dab-4210-b5b6-aea78066e0fd.png) hex: ![image](https://user-images.githubusercontent.com/679144/180199860-2cdd9455-7846-4921-b67c-6b9c3669b268.png) #### System Information ``` Mitmproxy: 8.1.1 binary Python: 3.10.5 OpenSSL: OpenSSL 3.0.3 3 May 2022 Platform: Linux-5.15.0-41-generic-x86_64-with-glibc2.35 ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mitmproxy/contentviews/raw.py` Content: ``` 1 from . import base 2 from mitmproxy.utils import strutils 3 4 5 class ViewRaw(base.View): 6 name = "Raw" 7 8 def __call__(self, data, **metadata): 9 return "Raw", base.format_text(strutils.bytes_to_escaped_str(data, True)) 10 11 def render_priority(self, data: bytes, **metadata) -> float: 12 return 0.1 * float(bool(data)) 13 ``` --- 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/mitmproxy/contentviews/raw.py b/mitmproxy/contentviews/raw.py --- a/mitmproxy/contentviews/raw.py +++ b/mitmproxy/contentviews/raw.py @@ -1,12 +1,11 @@ from . import base -from mitmproxy.utils import strutils class ViewRaw(base.View): name = "Raw" def __call__(self, data, **metadata): - return "Raw", base.format_text(strutils.bytes_to_escaped_str(data, True)) + return "Raw", base.format_text(data) def render_priority(self, data: bytes, **metadata) -> float: return 0.1 * float(bool(data))
{"golden_diff": "diff --git a/mitmproxy/contentviews/raw.py b/mitmproxy/contentviews/raw.py\n--- a/mitmproxy/contentviews/raw.py\n+++ b/mitmproxy/contentviews/raw.py\n@@ -1,12 +1,11 @@\n from . import base\n-from mitmproxy.utils import strutils\n \n \n class ViewRaw(base.View):\n name = \"Raw\"\n \n def __call__(self, data, **metadata):\n- return \"Raw\", base.format_text(strutils.bytes_to_escaped_str(data, True))\n+ return \"Raw\", base.format_text(data)\n \n def render_priority(self, data: bytes, **metadata) -> float:\n return 0.1 * float(bool(data))\n", "issue": "\"raw\" view is not raw, adds extra backslash\n#### Problem Description\r\n\r\nI just noticed during https://github.com/mitmproxy/mitmproxy/issues/5469#issuecomment-1191343747\r\n\r\n#### Steps to reproduce the behavior:\r\n\r\nhttp.txt\r\n\r\n```\r\nHTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 1\r\n\r\n\\\r\n```\r\n\r\n1. `ncat -l 1337 < http.txt`\r\n2. `mitmproxy`\r\n3. `curl --proxy localhost:8080 http://127.0.0.1:1337`\r\n\r\nraw is `\\\\`:\r\n\r\n![image](https://user-images.githubusercontent.com/679144/180199838-07c02668-5dab-4210-b5b6-aea78066e0fd.png)\r\n\r\nhex:\r\n\r\n![image](https://user-images.githubusercontent.com/679144/180199860-2cdd9455-7846-4921-b67c-6b9c3669b268.png)\r\n\r\n#### System Information\r\n\r\n```\r\nMitmproxy: 8.1.1 binary\r\nPython: 3.10.5\r\nOpenSSL: OpenSSL 3.0.3 3 May 2022\r\nPlatform: Linux-5.15.0-41-generic-x86_64-with-glibc2.35\r\n```\r\n\n", "before_files": [{"content": "from . import base\nfrom mitmproxy.utils import strutils\n\n\nclass ViewRaw(base.View):\n name = \"Raw\"\n\n def __call__(self, data, **metadata):\n return \"Raw\", base.format_text(strutils.bytes_to_escaped_str(data, True))\n\n def render_priority(self, data: bytes, **metadata) -> float:\n return 0.1 * float(bool(data))\n", "path": "mitmproxy/contentviews/raw.py"}], "after_files": [{"content": "from . import base\n\n\nclass ViewRaw(base.View):\n name = \"Raw\"\n\n def __call__(self, data, **metadata):\n return \"Raw\", base.format_text(data)\n\n def render_priority(self, data: bytes, **metadata) -> float:\n return 0.1 * float(bool(data))\n", "path": "mitmproxy/contentviews/raw.py"}]}
721
151
gh_patches_debug_10976
rasdani/github-patches
git_diff
sagemath__sage-36488
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- `func_persist` fails with Python 3.11 ```sage @func_persist def test(n): return n*n ``` fails with ```python AttributeError Traceback (most recent call last) Cell In[1], line 1 ----> 1 @func_persist 2 def test(n): 3 return n*n File /usr/lib/python3.11/site-packages/sage/misc/func_persist.py:60, in func_persist.__init__(self, f, dir) 56 self.__dir = dir 57 os.makedirs(dir, exist_ok=True) 58 self.__doc__ = '%s%s%s' % ( 59 f.__name__, ---> 60 inspect.formatargspec(*inspect.getargs(f.__code__)), 61 f.__doc__) AttributeError: module 'inspect' has no attribute 'formatargspec' ``` This is because `inspect.formatargspec` has been [deprecated in Python 3.5 and removed in 3.11](https://docs.python.org/3/whatsnew/3.11.html#removed). Probably related to #33842. --- 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/sage/misc/func_persist.py` Content: ``` 1 r""" 2 Support for persistent functions in .sage files 3 4 Persistent functions are functions whose values are stored on disk 5 so they do not have to be recomputed. 6 7 The inputs to the function must be hashable (so lists are not 8 allowed). Though a hash is used, in the incredibly unlikely event 9 that a hash collision occurs, your function will not return an 10 incorrect result because of this (though the cache might not be 11 used either). 12 13 This is meant to be used from ``.sage`` files, not from 14 library ``.py`` files. 15 16 To use this disk caching mechanism, just put 17 ``@func_persist`` right before your function 18 definition. For example, 19 20 :: 21 22 @func_persist 23 def bern(n): 24 "Return the n-th Bernoulli number, caching the result to disk." 25 return bernoulli(n) 26 27 You can then use the function ``bern`` as usual, except 28 it will almost instantly return values that have already been 29 computed, even if you quit and restart. 30 31 The disk cache files are stored by default in the subdirectory 32 ``func_persist`` of the current working directory, 33 with one file for each evaluation of the function. 34 """ 35 ######################################################################## 36 # Copyright (C) 2006 William Stein <[email protected]> 37 # 38 # Distributed under the terms of the GNU General Public License (GPL) 39 # 40 # https://www.gnu.org/licenses/ 41 ######################################################################## 42 43 import inspect 44 import os 45 46 from . import persist 47 48 49 class func_persist: 50 r""" 51 Put ``@func_persist`` right before your function 52 definition to cache values it computes to disk. 53 """ 54 def __init__(self, f, dir='func_persist'): 55 self.__func = f 56 self.__dir = dir 57 os.makedirs(dir, exist_ok=True) 58 self.__doc__ = '%s%s%s' % ( 59 f.__name__, 60 inspect.formatargspec(*inspect.getargs(f.__code__)), 61 f.__doc__) 62 63 def __call__(self, *args, **kwds): 64 key = (tuple(args), tuple(kwds.items())) 65 h = hash(key) 66 name = '%s/%s_%s.sobj' % (self.__dir, self.__func.__name__, h) 67 68 if os.path.exists(name): 69 key2, val = persist.load(name) 70 if key == key2: 71 # We save and test equality of keys to avoid 72 # the (extremely remote) possibility of a hash 73 # collision. Correctness is crucial in mathematics. 74 return val 75 76 val = self.__func(*args, **kwds) 77 persist.save((key, val), name) 78 return val 79 ``` --- 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/sage/misc/func_persist.py b/src/sage/misc/func_persist.py --- a/src/sage/misc/func_persist.py +++ b/src/sage/misc/func_persist.py @@ -45,7 +45,6 @@ from . import persist - class func_persist: r""" Put ``@func_persist`` right before your function @@ -57,7 +56,7 @@ os.makedirs(dir, exist_ok=True) self.__doc__ = '%s%s%s' % ( f.__name__, - inspect.formatargspec(*inspect.getargs(f.__code__)), + inspect.signature(f), f.__doc__) def __call__(self, *args, **kwds):
{"golden_diff": "diff --git a/src/sage/misc/func_persist.py b/src/sage/misc/func_persist.py\n--- a/src/sage/misc/func_persist.py\n+++ b/src/sage/misc/func_persist.py\n@@ -45,7 +45,6 @@\n \n from . import persist\n \n-\n class func_persist:\n r\"\"\"\n Put ``@func_persist`` right before your function\n@@ -57,7 +56,7 @@\n os.makedirs(dir, exist_ok=True)\n self.__doc__ = '%s%s%s' % (\n f.__name__,\n- inspect.formatargspec(*inspect.getargs(f.__code__)),\n+ inspect.signature(f),\n f.__doc__)\n \n def __call__(self, *args, **kwds):\n", "issue": "`func_persist` fails with Python 3.11\n```sage\n@func_persist\ndef test(n):\n return n*n\n```\n\nfails with\n\n```python\nAttributeError Traceback (most recent call last)\nCell In[1], line 1\n----> 1 @func_persist\n 2 def test(n):\n 3 return n*n\n\nFile /usr/lib/python3.11/site-packages/sage/misc/func_persist.py:60, in func_persist.__init__(self, f, dir)\n 56 self.__dir = dir\n 57 os.makedirs(dir, exist_ok=True)\n 58 self.__doc__ = '%s%s%s' % (\n 59 f.__name__,\n---> 60 inspect.formatargspec(*inspect.getargs(f.__code__)),\n 61 f.__doc__)\n\nAttributeError: module 'inspect' has no attribute 'formatargspec'\n```\n\nThis is because `inspect.formatargspec` has been [deprecated in Python 3.5 and removed in 3.11](https://docs.python.org/3/whatsnew/3.11.html#removed). Probably related to #33842.\n\n", "before_files": [{"content": "r\"\"\"\nSupport for persistent functions in .sage files\n\nPersistent functions are functions whose values are stored on disk\nso they do not have to be recomputed.\n\nThe inputs to the function must be hashable (so lists are not\nallowed). Though a hash is used, in the incredibly unlikely event\nthat a hash collision occurs, your function will not return an\nincorrect result because of this (though the cache might not be\nused either).\n\nThis is meant to be used from ``.sage`` files, not from\nlibrary ``.py`` files.\n\nTo use this disk caching mechanism, just put\n``@func_persist`` right before your function\ndefinition. For example,\n\n::\n\n @func_persist\n def bern(n):\n \"Return the n-th Bernoulli number, caching the result to disk.\"\n return bernoulli(n)\n\nYou can then use the function ``bern`` as usual, except\nit will almost instantly return values that have already been\ncomputed, even if you quit and restart.\n\nThe disk cache files are stored by default in the subdirectory\n``func_persist`` of the current working directory,\nwith one file for each evaluation of the function.\n\"\"\"\n########################################################################\n# Copyright (C) 2006 William Stein <[email protected]>\n#\n# Distributed under the terms of the GNU General Public License (GPL)\n#\n# https://www.gnu.org/licenses/\n########################################################################\n\nimport inspect\nimport os\n\nfrom . import persist\n\n\nclass func_persist:\n r\"\"\"\n Put ``@func_persist`` right before your function\n definition to cache values it computes to disk.\n \"\"\"\n def __init__(self, f, dir='func_persist'):\n self.__func = f\n self.__dir = dir\n os.makedirs(dir, exist_ok=True)\n self.__doc__ = '%s%s%s' % (\n f.__name__,\n inspect.formatargspec(*inspect.getargs(f.__code__)),\n f.__doc__)\n\n def __call__(self, *args, **kwds):\n key = (tuple(args), tuple(kwds.items()))\n h = hash(key)\n name = '%s/%s_%s.sobj' % (self.__dir, self.__func.__name__, h)\n\n if os.path.exists(name):\n key2, val = persist.load(name)\n if key == key2:\n # We save and test equality of keys to avoid\n # the (extremely remote) possibility of a hash\n # collision. Correctness is crucial in mathematics.\n return val\n\n val = self.__func(*args, **kwds)\n persist.save((key, val), name)\n return val\n", "path": "src/sage/misc/func_persist.py"}], "after_files": [{"content": "r\"\"\"\nSupport for persistent functions in .sage files\n\nPersistent functions are functions whose values are stored on disk\nso they do not have to be recomputed.\n\nThe inputs to the function must be hashable (so lists are not\nallowed). Though a hash is used, in the incredibly unlikely event\nthat a hash collision occurs, your function will not return an\nincorrect result because of this (though the cache might not be\nused either).\n\nThis is meant to be used from ``.sage`` files, not from\nlibrary ``.py`` files.\n\nTo use this disk caching mechanism, just put\n``@func_persist`` right before your function\ndefinition. For example,\n\n::\n\n @func_persist\n def bern(n):\n \"Return the n-th Bernoulli number, caching the result to disk.\"\n return bernoulli(n)\n\nYou can then use the function ``bern`` as usual, except\nit will almost instantly return values that have already been\ncomputed, even if you quit and restart.\n\nThe disk cache files are stored by default in the subdirectory\n``func_persist`` of the current working directory,\nwith one file for each evaluation of the function.\n\"\"\"\n########################################################################\n# Copyright (C) 2006 William Stein <[email protected]>\n#\n# Distributed under the terms of the GNU General Public License (GPL)\n#\n# https://www.gnu.org/licenses/\n########################################################################\n\nimport inspect\nimport os\n\nfrom . import persist\n\nclass func_persist:\n r\"\"\"\n Put ``@func_persist`` right before your function\n definition to cache values it computes to disk.\n \"\"\"\n def __init__(self, f, dir='func_persist'):\n self.__func = f\n self.__dir = dir\n os.makedirs(dir, exist_ok=True)\n self.__doc__ = '%s%s%s' % (\n f.__name__,\n inspect.signature(f),\n f.__doc__)\n\n def __call__(self, *args, **kwds):\n key = (tuple(args), tuple(kwds.items()))\n h = hash(key)\n name = '%s/%s_%s.sobj' % (self.__dir, self.__func.__name__, h)\n\n if os.path.exists(name):\n key2, val = persist.load(name)\n if key == key2:\n # We save and test equality of keys to avoid\n # the (extremely remote) possibility of a hash\n # collision. Correctness is crucial in mathematics.\n return val\n\n val = self.__func(*args, **kwds)\n persist.save((key, val), name)\n return val\n", "path": "src/sage/misc/func_persist.py"}]}
1,262
168
gh_patches_debug_30376
rasdani/github-patches
git_diff
mathesar-foundation__mathesar-230
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Implement filters for schema list API **Problem** <!-- Please provide a clear and concise description of the problem that this feature request is designed to solve.--> Users should be able to: - get schemas associated with a given database key from the schema list API. - filter schemas by name. **Proposed solution** <!-- A clear and concise description of your proposed solution or feature. --> Schema list API should take name and database filter parameters. **Additional context** <!-- Add any other context or screenshots about the feature request here.--> We should use `django-filter` 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: `mathesar/views/api.py` Content: ``` 1 from rest_framework import status, viewsets 2 from rest_framework.exceptions import NotFound, ValidationError 3 from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin 4 from rest_framework.response import Response 5 from django_filters import rest_framework as filters 6 7 from mathesar.database.utils import get_non_default_database_keys 8 from mathesar.models import Table, Schema, DataFile 9 from mathesar.pagination import DefaultLimitOffsetPagination, TableLimitOffsetPagination 10 from mathesar.serializers import TableSerializer, SchemaSerializer, RecordSerializer, DataFileSerializer 11 from mathesar.utils.schemas import create_schema_and_object 12 from mathesar.utils.api import create_table_from_datafile 13 from mathesar.filters import TableFilter 14 15 16 class SchemaViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin): 17 queryset = Schema.objects.all().order_by('-created_at') 18 serializer_class = SchemaSerializer 19 pagination_class = DefaultLimitOffsetPagination 20 21 def create(self, request): 22 schema = create_schema_and_object(request.data['name'], request.data['database']) 23 serializer = SchemaSerializer(schema) 24 return Response(serializer.data, status=status.HTTP_201_CREATED) 25 26 27 class TableViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin, 28 CreateModelMixin): 29 queryset = Table.objects.all().order_by('-created_at') 30 serializer_class = TableSerializer 31 pagination_class = DefaultLimitOffsetPagination 32 filter_backends = (filters.DjangoFilterBackend,) 33 filterset_class = TableFilter 34 35 def create(self, request): 36 serializer = TableSerializer(data=request.data, 37 context={'request': request}) 38 if serializer.is_valid(): 39 return create_table_from_datafile(request, serializer.data) 40 else: 41 raise ValidationError(serializer.errors) 42 43 44 class RecordViewSet(viewsets.ViewSet): 45 # There is no "update" method. 46 # We're not supporting PUT requests because there aren't a lot of use cases 47 # where the entire record needs to be replaced, PATCH suffices for updates. 48 queryset = Table.objects.all().order_by('-created_at') 49 50 def list(self, request, table_pk=None): 51 paginator = TableLimitOffsetPagination() 52 records = paginator.paginate_queryset(self.queryset, request, table_pk) 53 serializer = RecordSerializer(records, many=True) 54 return paginator.get_paginated_response(serializer.data) 55 56 def retrieve(self, request, pk=None, table_pk=None): 57 table = Table.objects.get(id=table_pk) 58 record = table.get_record(pk) 59 if not record: 60 raise NotFound 61 serializer = RecordSerializer(record) 62 return Response(serializer.data) 63 64 def create(self, request, table_pk=None): 65 table = Table.objects.get(id=table_pk) 66 # We only support adding a single record through the API. 67 assert isinstance((request.data), dict) 68 record = table.create_record_or_records(request.data) 69 serializer = RecordSerializer(record) 70 return Response(serializer.data, status=status.HTTP_201_CREATED) 71 72 def partial_update(self, request, pk=None, table_pk=None): 73 table = Table.objects.get(id=table_pk) 74 record = table.update_record(pk, request.data) 75 serializer = RecordSerializer(record) 76 return Response(serializer.data) 77 78 def destroy(self, request, pk=None, table_pk=None): 79 table = Table.objects.get(id=table_pk) 80 table.delete_record(pk) 81 return Response(status=status.HTTP_204_NO_CONTENT) 82 83 84 class DatabaseKeyViewSet(viewsets.ViewSet): 85 def list(self, request): 86 return Response(get_non_default_database_keys()) 87 88 89 class DataFileViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin, CreateModelMixin): 90 queryset = DataFile.objects.all().order_by('-created_at') 91 serializer_class = DataFileSerializer 92 pagination_class = DefaultLimitOffsetPagination 93 ``` Path: `mathesar/filters.py` Content: ``` 1 from django_filters import rest_framework as filters 2 3 from mathesar.models import Table 4 5 6 class CharInFilter(filters.BaseInFilter, filters.CharFilter): 7 pass 8 9 10 class TableFilter(filters.FilterSet): 11 name = CharInFilter(field_name='name', lookup_expr='in') 12 13 class Meta: 14 model = Table 15 fields = ['name'] 16 ``` --- 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/mathesar/filters.py b/mathesar/filters.py --- a/mathesar/filters.py +++ b/mathesar/filters.py @@ -1,12 +1,21 @@ from django_filters import rest_framework as filters -from mathesar.models import Table +from mathesar.models import Schema, Table class CharInFilter(filters.BaseInFilter, filters.CharFilter): pass +class SchemaFilter(filters.FilterSet): + name = CharInFilter(field_name='name', lookup_expr='in') + database = CharInFilter(field_name='database', lookup_expr='in') + + class Meta: + model = Schema + fields = ['name', 'database'] + + class TableFilter(filters.FilterSet): name = CharInFilter(field_name='name', lookup_expr='in') diff --git a/mathesar/views/api.py b/mathesar/views/api.py --- a/mathesar/views/api.py +++ b/mathesar/views/api.py @@ -10,13 +10,15 @@ from mathesar.serializers import TableSerializer, SchemaSerializer, RecordSerializer, DataFileSerializer from mathesar.utils.schemas import create_schema_and_object from mathesar.utils.api import create_table_from_datafile -from mathesar.filters import TableFilter +from mathesar.filters import SchemaFilter, TableFilter class SchemaViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin): queryset = Schema.objects.all().order_by('-created_at') serializer_class = SchemaSerializer pagination_class = DefaultLimitOffsetPagination + filter_backends = (filters.DjangoFilterBackend,) + filterset_class = SchemaFilter def create(self, request): schema = create_schema_and_object(request.data['name'], request.data['database'])
{"golden_diff": "diff --git a/mathesar/filters.py b/mathesar/filters.py\n--- a/mathesar/filters.py\n+++ b/mathesar/filters.py\n@@ -1,12 +1,21 @@\n from django_filters import rest_framework as filters\n \n-from mathesar.models import Table\n+from mathesar.models import Schema, Table\n \n \n class CharInFilter(filters.BaseInFilter, filters.CharFilter):\n pass\n \n \n+class SchemaFilter(filters.FilterSet):\n+ name = CharInFilter(field_name='name', lookup_expr='in')\n+ database = CharInFilter(field_name='database', lookup_expr='in')\n+\n+ class Meta:\n+ model = Schema\n+ fields = ['name', 'database']\n+\n+\n class TableFilter(filters.FilterSet):\n name = CharInFilter(field_name='name', lookup_expr='in')\n \ndiff --git a/mathesar/views/api.py b/mathesar/views/api.py\n--- a/mathesar/views/api.py\n+++ b/mathesar/views/api.py\n@@ -10,13 +10,15 @@\n from mathesar.serializers import TableSerializer, SchemaSerializer, RecordSerializer, DataFileSerializer\n from mathesar.utils.schemas import create_schema_and_object\n from mathesar.utils.api import create_table_from_datafile\n-from mathesar.filters import TableFilter\n+from mathesar.filters import SchemaFilter, TableFilter\n \n \n class SchemaViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin):\n queryset = Schema.objects.all().order_by('-created_at')\n serializer_class = SchemaSerializer\n pagination_class = DefaultLimitOffsetPagination\n+ filter_backends = (filters.DjangoFilterBackend,)\n+ filterset_class = SchemaFilter\n \n def create(self, request):\n schema = create_schema_and_object(request.data['name'], request.data['database'])\n", "issue": "Implement filters for schema list API\n**Problem**\r\n<!-- Please provide a clear and concise description of the problem that this feature request is designed to solve.-->\r\nUsers should be able to:\r\n- get schemas associated with a given database key from the schema list API.\r\n- filter schemas by name.\r\n\r\n**Proposed solution**\r\n<!-- A clear and concise description of your proposed solution or feature. -->\r\nSchema list API should take name and database filter parameters.\r\n\r\n**Additional context**\r\n<!-- Add any other context or screenshots about the feature request here.-->\r\nWe should use `django-filter` for this.\n", "before_files": [{"content": "from rest_framework import status, viewsets\nfrom rest_framework.exceptions import NotFound, ValidationError\nfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin\nfrom rest_framework.response import Response\nfrom django_filters import rest_framework as filters\n\nfrom mathesar.database.utils import get_non_default_database_keys\nfrom mathesar.models import Table, Schema, DataFile\nfrom mathesar.pagination import DefaultLimitOffsetPagination, TableLimitOffsetPagination\nfrom mathesar.serializers import TableSerializer, SchemaSerializer, RecordSerializer, DataFileSerializer\nfrom mathesar.utils.schemas import create_schema_and_object\nfrom mathesar.utils.api import create_table_from_datafile\nfrom mathesar.filters import TableFilter\n\n\nclass SchemaViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin):\n queryset = Schema.objects.all().order_by('-created_at')\n serializer_class = SchemaSerializer\n pagination_class = DefaultLimitOffsetPagination\n\n def create(self, request):\n schema = create_schema_and_object(request.data['name'], request.data['database'])\n serializer = SchemaSerializer(schema)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass TableViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin,\n CreateModelMixin):\n queryset = Table.objects.all().order_by('-created_at')\n serializer_class = TableSerializer\n pagination_class = DefaultLimitOffsetPagination\n filter_backends = (filters.DjangoFilterBackend,)\n filterset_class = TableFilter\n\n def create(self, request):\n serializer = TableSerializer(data=request.data,\n context={'request': request})\n if serializer.is_valid():\n return create_table_from_datafile(request, serializer.data)\n else:\n raise ValidationError(serializer.errors)\n\n\nclass RecordViewSet(viewsets.ViewSet):\n # There is no \"update\" method.\n # We're not supporting PUT requests because there aren't a lot of use cases\n # where the entire record needs to be replaced, PATCH suffices for updates.\n queryset = Table.objects.all().order_by('-created_at')\n\n def list(self, request, table_pk=None):\n paginator = TableLimitOffsetPagination()\n records = paginator.paginate_queryset(self.queryset, request, table_pk)\n serializer = RecordSerializer(records, many=True)\n return paginator.get_paginated_response(serializer.data)\n\n def retrieve(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n record = table.get_record(pk)\n if not record:\n raise NotFound\n serializer = RecordSerializer(record)\n return Response(serializer.data)\n\n def create(self, request, table_pk=None):\n table = Table.objects.get(id=table_pk)\n # We only support adding a single record through the API.\n assert isinstance((request.data), dict)\n record = table.create_record_or_records(request.data)\n serializer = RecordSerializer(record)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def partial_update(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n record = table.update_record(pk, request.data)\n serializer = RecordSerializer(record)\n return Response(serializer.data)\n\n def destroy(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n table.delete_record(pk)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass DatabaseKeyViewSet(viewsets.ViewSet):\n def list(self, request):\n return Response(get_non_default_database_keys())\n\n\nclass DataFileViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin, CreateModelMixin):\n queryset = DataFile.objects.all().order_by('-created_at')\n serializer_class = DataFileSerializer\n pagination_class = DefaultLimitOffsetPagination\n", "path": "mathesar/views/api.py"}, {"content": "from django_filters import rest_framework as filters\n\nfrom mathesar.models import Table\n\n\nclass CharInFilter(filters.BaseInFilter, filters.CharFilter):\n pass\n\n\nclass TableFilter(filters.FilterSet):\n name = CharInFilter(field_name='name', lookup_expr='in')\n\n class Meta:\n model = Table\n fields = ['name']\n", "path": "mathesar/filters.py"}], "after_files": [{"content": "from rest_framework import status, viewsets\nfrom rest_framework.exceptions import NotFound, ValidationError\nfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin\nfrom rest_framework.response import Response\nfrom django_filters import rest_framework as filters\n\nfrom mathesar.database.utils import get_non_default_database_keys\nfrom mathesar.models import Table, Schema, DataFile\nfrom mathesar.pagination import DefaultLimitOffsetPagination, TableLimitOffsetPagination\nfrom mathesar.serializers import TableSerializer, SchemaSerializer, RecordSerializer, DataFileSerializer\nfrom mathesar.utils.schemas import create_schema_and_object\nfrom mathesar.utils.api import create_table_from_datafile\nfrom mathesar.filters import SchemaFilter, TableFilter\n\n\nclass SchemaViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin):\n queryset = Schema.objects.all().order_by('-created_at')\n serializer_class = SchemaSerializer\n pagination_class = DefaultLimitOffsetPagination\n filter_backends = (filters.DjangoFilterBackend,)\n filterset_class = SchemaFilter\n\n def create(self, request):\n schema = create_schema_and_object(request.data['name'], request.data['database'])\n serializer = SchemaSerializer(schema)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass TableViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin,\n CreateModelMixin):\n queryset = Table.objects.all().order_by('-created_at')\n serializer_class = TableSerializer\n pagination_class = DefaultLimitOffsetPagination\n filter_backends = (filters.DjangoFilterBackend,)\n filterset_class = TableFilter\n\n def create(self, request):\n serializer = TableSerializer(data=request.data,\n context={'request': request})\n if serializer.is_valid():\n return create_table_from_datafile(request, serializer.data)\n else:\n raise ValidationError(serializer.errors)\n\n\nclass RecordViewSet(viewsets.ViewSet):\n # There is no \"update\" method.\n # We're not supporting PUT requests because there aren't a lot of use cases\n # where the entire record needs to be replaced, PATCH suffices for updates.\n queryset = Table.objects.all().order_by('-created_at')\n\n def list(self, request, table_pk=None):\n paginator = TableLimitOffsetPagination()\n records = paginator.paginate_queryset(self.queryset, request, table_pk)\n serializer = RecordSerializer(records, many=True)\n return paginator.get_paginated_response(serializer.data)\n\n def retrieve(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n record = table.get_record(pk)\n if not record:\n raise NotFound\n serializer = RecordSerializer(record)\n return Response(serializer.data)\n\n def create(self, request, table_pk=None):\n table = Table.objects.get(id=table_pk)\n # We only support adding a single record through the API.\n assert isinstance((request.data), dict)\n record = table.create_record_or_records(request.data)\n serializer = RecordSerializer(record)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def partial_update(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n record = table.update_record(pk, request.data)\n serializer = RecordSerializer(record)\n return Response(serializer.data)\n\n def destroy(self, request, pk=None, table_pk=None):\n table = Table.objects.get(id=table_pk)\n table.delete_record(pk)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass DatabaseKeyViewSet(viewsets.ViewSet):\n def list(self, request):\n return Response(get_non_default_database_keys())\n\n\nclass DataFileViewSet(viewsets.GenericViewSet, ListModelMixin, RetrieveModelMixin, CreateModelMixin):\n queryset = DataFile.objects.all().order_by('-created_at')\n serializer_class = DataFileSerializer\n pagination_class = DefaultLimitOffsetPagination\n", "path": "mathesar/views/api.py"}, {"content": "from django_filters import rest_framework as filters\n\nfrom mathesar.models import Schema, Table\n\n\nclass CharInFilter(filters.BaseInFilter, filters.CharFilter):\n pass\n\n\nclass SchemaFilter(filters.FilterSet):\n name = CharInFilter(field_name='name', lookup_expr='in')\n database = CharInFilter(field_name='database', lookup_expr='in')\n\n class Meta:\n model = Schema\n fields = ['name', 'database']\n\n\nclass TableFilter(filters.FilterSet):\n name = CharInFilter(field_name='name', lookup_expr='in')\n\n class Meta:\n model = Table\n fields = ['name']\n", "path": "mathesar/filters.py"}]}
1,462
379
gh_patches_debug_21093
rasdani/github-patches
git_diff
liqd__adhocracy4-294
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- IntegrityError in ratings See: - https://sentry.liqd.net/sentry/debattenportalspdde/issues/84/ - https://sentry.liqd.net/sentry/meinberlin-prod/issues/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: `adhocracy4/ratings/api.py` Content: ``` 1 from django.conf import settings 2 3 from django_filters import rest_framework as filters 4 from rest_framework import mixins, viewsets 5 from rest_framework.response import Response 6 7 from adhocracy4.api.mixins import ContentTypeMixin 8 from adhocracy4.api.permissions import ViewSetRulesPermission 9 10 from .models import Rating 11 from .serializers import RatingSerializer 12 13 14 class RatingViewSet(mixins.CreateModelMixin, 15 mixins.UpdateModelMixin, 16 ContentTypeMixin, 17 viewsets.GenericViewSet): 18 19 queryset = Rating.objects.all() 20 serializer_class = RatingSerializer 21 permission_classes = (ViewSetRulesPermission,) 22 filter_backends = (filters.DjangoFilterBackend,) 23 filter_fields = ('object_pk', 'content_type') 24 content_type_filter = settings.A4_RATEABLES 25 26 def perform_create(self, serializer): 27 serializer.save( 28 content_object=self.content_object, 29 creator=self.request.user 30 ) 31 32 def get_permission_object(self): 33 return self.content_object 34 35 @property 36 def rules_method_map(self): 37 return ViewSetRulesPermission.default_rules_method_map._replace( 38 POST='{app_label}.rate_{model}'.format( 39 app_label=self.content_type.app_label, 40 model=self.content_type.model 41 ) 42 ) 43 44 def destroy(self, request, content_type, object_pk, pk=None): 45 """ 46 Sets value to zero 47 NOTE: Rating is NOT deleted. 48 """ 49 rating = self.get_object() 50 rating.update(0) 51 serializer = self.get_serializer(rating) 52 return Response(serializer.data) 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/adhocracy4/ratings/api.py b/adhocracy4/ratings/api.py --- a/adhocracy4/ratings/api.py +++ b/adhocracy4/ratings/api.py @@ -3,6 +3,7 @@ from django_filters import rest_framework as filters from rest_framework import mixins, viewsets from rest_framework.response import Response +from rest_framework.serializers import ValidationError from adhocracy4.api.mixins import ContentTypeMixin from adhocracy4.api.permissions import ViewSetRulesPermission @@ -24,6 +25,11 @@ content_type_filter = settings.A4_RATEABLES def perform_create(self, serializer): + queryset = Rating.objects.filter(content_type_id=self.content_type.pk, + creator=self.request.user, + object_pk=self.content_object.pk) + if queryset.exists(): + raise ValidationError(queryset[0].pk) serializer.save( content_object=self.content_object, creator=self.request.user
{"golden_diff": "diff --git a/adhocracy4/ratings/api.py b/adhocracy4/ratings/api.py\n--- a/adhocracy4/ratings/api.py\n+++ b/adhocracy4/ratings/api.py\n@@ -3,6 +3,7 @@\n from django_filters import rest_framework as filters\n from rest_framework import mixins, viewsets\n from rest_framework.response import Response\n+from rest_framework.serializers import ValidationError\n \n from adhocracy4.api.mixins import ContentTypeMixin\n from adhocracy4.api.permissions import ViewSetRulesPermission\n@@ -24,6 +25,11 @@\n content_type_filter = settings.A4_RATEABLES\n \n def perform_create(self, serializer):\n+ queryset = Rating.objects.filter(content_type_id=self.content_type.pk,\n+ creator=self.request.user,\n+ object_pk=self.content_object.pk)\n+ if queryset.exists():\n+ raise ValidationError(queryset[0].pk)\n serializer.save(\n content_object=self.content_object,\n creator=self.request.user\n", "issue": "IntegrityError in ratings\nSee:\r\n- https://sentry.liqd.net/sentry/debattenportalspdde/issues/84/\r\n- https://sentry.liqd.net/sentry/meinberlin-prod/issues/5/\n", "before_files": [{"content": "from django.conf import settings\n\nfrom django_filters import rest_framework as filters\nfrom rest_framework import mixins, viewsets\nfrom rest_framework.response import Response\n\nfrom adhocracy4.api.mixins import ContentTypeMixin\nfrom adhocracy4.api.permissions import ViewSetRulesPermission\n\nfrom .models import Rating\nfrom .serializers import RatingSerializer\n\n\nclass RatingViewSet(mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n ContentTypeMixin,\n viewsets.GenericViewSet):\n\n queryset = Rating.objects.all()\n serializer_class = RatingSerializer\n permission_classes = (ViewSetRulesPermission,)\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('object_pk', 'content_type')\n content_type_filter = settings.A4_RATEABLES\n\n def perform_create(self, serializer):\n serializer.save(\n content_object=self.content_object,\n creator=self.request.user\n )\n\n def get_permission_object(self):\n return self.content_object\n\n @property\n def rules_method_map(self):\n return ViewSetRulesPermission.default_rules_method_map._replace(\n POST='{app_label}.rate_{model}'.format(\n app_label=self.content_type.app_label,\n model=self.content_type.model\n )\n )\n\n def destroy(self, request, content_type, object_pk, pk=None):\n \"\"\"\n Sets value to zero\n NOTE: Rating is NOT deleted.\n \"\"\"\n rating = self.get_object()\n rating.update(0)\n serializer = self.get_serializer(rating)\n return Response(serializer.data)\n", "path": "adhocracy4/ratings/api.py"}], "after_files": [{"content": "from django.conf import settings\n\nfrom django_filters import rest_framework as filters\nfrom rest_framework import mixins, viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import ValidationError\n\nfrom adhocracy4.api.mixins import ContentTypeMixin\nfrom adhocracy4.api.permissions import ViewSetRulesPermission\n\nfrom .models import Rating\nfrom .serializers import RatingSerializer\n\n\nclass RatingViewSet(mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n ContentTypeMixin,\n viewsets.GenericViewSet):\n\n queryset = Rating.objects.all()\n serializer_class = RatingSerializer\n permission_classes = (ViewSetRulesPermission,)\n filter_backends = (filters.DjangoFilterBackend,)\n filter_fields = ('object_pk', 'content_type')\n content_type_filter = settings.A4_RATEABLES\n\n def perform_create(self, serializer):\n queryset = Rating.objects.filter(content_type_id=self.content_type.pk,\n creator=self.request.user,\n object_pk=self.content_object.pk)\n if queryset.exists():\n raise ValidationError(queryset[0].pk)\n serializer.save(\n content_object=self.content_object,\n creator=self.request.user\n )\n\n def get_permission_object(self):\n return self.content_object\n\n @property\n def rules_method_map(self):\n return ViewSetRulesPermission.default_rules_method_map._replace(\n POST='{app_label}.rate_{model}'.format(\n app_label=self.content_type.app_label,\n model=self.content_type.model\n )\n )\n\n def destroy(self, request, content_type, object_pk, pk=None):\n \"\"\"\n Sets value to zero\n NOTE: Rating is NOT deleted.\n \"\"\"\n rating = self.get_object()\n rating.update(0)\n serializer = self.get_serializer(rating)\n return Response(serializer.data)\n", "path": "adhocracy4/ratings/api.py"}]}
731
211
gh_patches_debug_24915
rasdani/github-patches
git_diff
saleor__saleor-3848
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- GraphQL error: Expected a value of type "WeightUnitsEnum" but received: kg ### Steps to reproduce the problem 1. Change the default language in the storefront to Portuguese. 2. Go to Dashboard 2.0. The homepage runs a query which fetches `defaultWeightUnit` field. This GraphQL request returns this error: `GraphQL error: Expected a value of type "WeightUnitsEnum" but received: kg` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `saleor/core/weight.py` Content: ``` 1 """In Saleor we are using 'weight' instead of a 'mass'. 2 3 For those of us who are earth-bound, weight is what we usually experience. 4 Mass is a theoretical construct. 5 Unless we are dealing with inertia and momentum, we are encountering 6 the attractive force between ourselves and the earth, 7 the isolated effects of mass alone being a little more esoteric. 8 9 So even though mass is more fundamental, most people think 10 in terms of weight. 11 12 In the end, it does not really matter unless you travel between 13 different planets. 14 """ 15 from decimal import Decimal 16 from enum import Enum 17 18 from django import forms 19 from django.contrib.sites.models import Site 20 from django.core.validators import MinValueValidator 21 from django.template.loader import render_to_string 22 from django.utils.translation import pgettext_lazy 23 from measurement.measures import Weight 24 25 26 class WeightUnits: 27 KILOGRAM = 'kg' 28 POUND = 'lb' 29 OUNCE = 'oz' 30 GRAM = 'g' 31 32 CHOICES = [ 33 (KILOGRAM, pgettext_lazy('Kilogram weight unit symbol', 'kg')), 34 (POUND, pgettext_lazy('Pound weight unit symbol', 'lb')), 35 (OUNCE, pgettext_lazy('Ounce weight unit symbol', 'oz')), 36 (GRAM, pgettext_lazy('Gram weight unit symbol', 'g'))] 37 38 39 WeightUnitsEnum = Enum( 40 'WeightUnitsEnum', 41 {unit: unit for unit in WeightUnits.CHOICES}) 42 43 44 def zero_weight(): 45 """Represent the zero weight value.""" 46 return Weight(kg=0) 47 48 49 def convert_weight(weight, unit): 50 # Weight amount from the Weight instance can be retrived in serveral units 51 # via its properties. eg. Weight(lb=10).kg 52 converted_weight = getattr(weight, unit) 53 return Weight(**{unit: converted_weight}) 54 55 56 def get_default_weight_unit(): 57 site = Site.objects.get_current() 58 return site.settings.default_weight_unit 59 60 61 class WeightInput(forms.TextInput): 62 template = 'dashboard/shipping/weight_widget.html' 63 input_type = 'number' 64 65 def format_value(self, value): 66 if isinstance(value, Weight): 67 unit = get_default_weight_unit() 68 if value.unit != unit: 69 value = convert_weight(value, unit) 70 return value.value 71 return value 72 73 def render(self, name, value, attrs=None, renderer=None): 74 widget = super().render(name, value, attrs=attrs, renderer=renderer) 75 unit = get_default_weight_unit() 76 translated_unit = dict(WeightUnits.CHOICES)[unit] 77 return render_to_string( 78 self.template, 79 {'widget': widget, 'value': value, 'unit': translated_unit}) 80 81 82 class WeightField(forms.FloatField): 83 def __init__(self, *args, widget=WeightInput, min_value=0, **kwargs): 84 if isinstance(widget, type): 85 widget = widget(attrs={'type': 'number', 'step': 'any'}) 86 super().__init__(*args, widget=widget, **kwargs) 87 if min_value is not None: 88 self.validators.append(MinValueValidator(min_value)) 89 90 def to_python(self, value): 91 value = super().to_python(value) 92 if value is None: 93 return value 94 unit = get_default_weight_unit() 95 return Weight(**{unit: value}) 96 97 def validate(self, weight): 98 if weight is None or weight in self.empty_values: 99 super().validate(weight) 100 else: 101 unit = get_default_weight_unit() 102 if not isinstance(weight, Weight): 103 raise Exception( 104 '%r is not a valid weight.' % (weight,)) 105 if weight.unit != unit: 106 raise forms.ValidationError( 107 'Invalid unit: %r (expected %r).' % ( 108 weight.unit, unit)) 109 super().validate(weight.value) 110 111 def clean(self, value): 112 value = value_to_be_validated = self.to_python(value) 113 self.validate(value_to_be_validated) 114 if isinstance(value, Weight): 115 value_to_be_validated = Decimal(value.value) 116 # default decimal validators can be used for Weight's value only 117 self.run_validators(value_to_be_validated) 118 return value 119 ``` Path: `saleor/graphql/core/enums.py` Content: ``` 1 import graphene 2 3 from ...core import TaxRateType as CoreTaxRateType, weight 4 from ...core.permissions import MODELS_PERMISSIONS 5 from .utils import str_to_enum 6 7 8 class ReportingPeriod(graphene.Enum): 9 TODAY = 'TODAY' 10 THIS_MONTH = 'THIS_MONTH' 11 12 13 TaxRateType = graphene.Enum( 14 'TaxRateType', 15 [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES]) 16 17 18 PermissionEnum = graphene.Enum( 19 'PermissionEnum', [ 20 (str_to_enum(codename.split('.')[1]), codename) 21 for codename in MODELS_PERMISSIONS]) 22 23 24 WeightUnitsEnum = graphene.Enum.from_enum(weight.WeightUnitsEnum) 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/saleor/core/weight.py b/saleor/core/weight.py --- a/saleor/core/weight.py +++ b/saleor/core/weight.py @@ -13,7 +13,6 @@ different planets. """ from decimal import Decimal -from enum import Enum from django import forms from django.contrib.sites.models import Site @@ -36,11 +35,6 @@ (GRAM, pgettext_lazy('Gram weight unit symbol', 'g'))] -WeightUnitsEnum = Enum( - 'WeightUnitsEnum', - {unit: unit for unit in WeightUnits.CHOICES}) - - def zero_weight(): """Represent the zero weight value.""" return Weight(kg=0) diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py --- a/saleor/graphql/core/enums.py +++ b/saleor/graphql/core/enums.py @@ -1,6 +1,7 @@ import graphene -from ...core import TaxRateType as CoreTaxRateType, weight +from ...core import TaxRateType as CoreTaxRateType +from ...core.weight import WeightUnits from ...core.permissions import MODELS_PERMISSIONS from .utils import str_to_enum @@ -21,4 +22,6 @@ for codename in MODELS_PERMISSIONS]) -WeightUnitsEnum = graphene.Enum.from_enum(weight.WeightUnitsEnum) +WeightUnitsEnum = graphene.Enum( + 'WeightUnitsEnum', + [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES])
{"golden_diff": "diff --git a/saleor/core/weight.py b/saleor/core/weight.py\n--- a/saleor/core/weight.py\n+++ b/saleor/core/weight.py\n@@ -13,7 +13,6 @@\n different planets.\n \"\"\"\n from decimal import Decimal\n-from enum import Enum\n \n from django import forms\n from django.contrib.sites.models import Site\n@@ -36,11 +35,6 @@\n (GRAM, pgettext_lazy('Gram weight unit symbol', 'g'))]\n \n \n-WeightUnitsEnum = Enum(\n- 'WeightUnitsEnum',\n- {unit: unit for unit in WeightUnits.CHOICES})\n-\n-\n def zero_weight():\n \"\"\"Represent the zero weight value.\"\"\"\n return Weight(kg=0)\ndiff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py\n--- a/saleor/graphql/core/enums.py\n+++ b/saleor/graphql/core/enums.py\n@@ -1,6 +1,7 @@\n import graphene\n \n-from ...core import TaxRateType as CoreTaxRateType, weight\n+from ...core import TaxRateType as CoreTaxRateType\n+from ...core.weight import WeightUnits\n from ...core.permissions import MODELS_PERMISSIONS\n from .utils import str_to_enum\n \n@@ -21,4 +22,6 @@\n for codename in MODELS_PERMISSIONS])\n \n \n-WeightUnitsEnum = graphene.Enum.from_enum(weight.WeightUnitsEnum)\n+WeightUnitsEnum = graphene.Enum(\n+ 'WeightUnitsEnum',\n+ [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES])\n", "issue": "GraphQL error: Expected a value of type \"WeightUnitsEnum\" but received: kg\n### Steps to reproduce the problem\r\n1. Change the default language in the storefront to Portuguese.\r\n2. Go to Dashboard 2.0. The homepage runs a query which fetches `defaultWeightUnit` field.\r\nThis GraphQL request returns this error: `GraphQL error: Expected a value of type \"WeightUnitsEnum\" but received: kg`\r\n\n", "before_files": [{"content": "\"\"\"In Saleor we are using 'weight' instead of a 'mass'.\n\nFor those of us who are earth-bound, weight is what we usually experience.\nMass is a theoretical construct.\nUnless we are dealing with inertia and momentum, we are encountering\nthe attractive force between ourselves and the earth,\nthe isolated effects of mass alone being a little more esoteric.\n\nSo even though mass is more fundamental, most people think\nin terms of weight.\n\nIn the end, it does not really matter unless you travel between\ndifferent planets.\n\"\"\"\nfrom decimal import Decimal\nfrom enum import Enum\n\nfrom django import forms\nfrom django.contrib.sites.models import Site\nfrom django.core.validators import MinValueValidator\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import pgettext_lazy\nfrom measurement.measures import Weight\n\n\nclass WeightUnits:\n KILOGRAM = 'kg'\n POUND = 'lb'\n OUNCE = 'oz'\n GRAM = 'g'\n\n CHOICES = [\n (KILOGRAM, pgettext_lazy('Kilogram weight unit symbol', 'kg')),\n (POUND, pgettext_lazy('Pound weight unit symbol', 'lb')),\n (OUNCE, pgettext_lazy('Ounce weight unit symbol', 'oz')),\n (GRAM, pgettext_lazy('Gram weight unit symbol', 'g'))]\n\n\nWeightUnitsEnum = Enum(\n 'WeightUnitsEnum',\n {unit: unit for unit in WeightUnits.CHOICES})\n\n\ndef zero_weight():\n \"\"\"Represent the zero weight value.\"\"\"\n return Weight(kg=0)\n\n\ndef convert_weight(weight, unit):\n # Weight amount from the Weight instance can be retrived in serveral units\n # via its properties. eg. Weight(lb=10).kg\n converted_weight = getattr(weight, unit)\n return Weight(**{unit: converted_weight})\n\n\ndef get_default_weight_unit():\n site = Site.objects.get_current()\n return site.settings.default_weight_unit\n\n\nclass WeightInput(forms.TextInput):\n template = 'dashboard/shipping/weight_widget.html'\n input_type = 'number'\n\n def format_value(self, value):\n if isinstance(value, Weight):\n unit = get_default_weight_unit()\n if value.unit != unit:\n value = convert_weight(value, unit)\n return value.value\n return value\n\n def render(self, name, value, attrs=None, renderer=None):\n widget = super().render(name, value, attrs=attrs, renderer=renderer)\n unit = get_default_weight_unit()\n translated_unit = dict(WeightUnits.CHOICES)[unit]\n return render_to_string(\n self.template,\n {'widget': widget, 'value': value, 'unit': translated_unit})\n\n\nclass WeightField(forms.FloatField):\n def __init__(self, *args, widget=WeightInput, min_value=0, **kwargs):\n if isinstance(widget, type):\n widget = widget(attrs={'type': 'number', 'step': 'any'})\n super().__init__(*args, widget=widget, **kwargs)\n if min_value is not None:\n self.validators.append(MinValueValidator(min_value))\n\n def to_python(self, value):\n value = super().to_python(value)\n if value is None:\n return value\n unit = get_default_weight_unit()\n return Weight(**{unit: value})\n\n def validate(self, weight):\n if weight is None or weight in self.empty_values:\n super().validate(weight)\n else:\n unit = get_default_weight_unit()\n if not isinstance(weight, Weight):\n raise Exception(\n '%r is not a valid weight.' % (weight,))\n if weight.unit != unit:\n raise forms.ValidationError(\n 'Invalid unit: %r (expected %r).' % (\n weight.unit, unit))\n super().validate(weight.value)\n\n def clean(self, value):\n value = value_to_be_validated = self.to_python(value)\n self.validate(value_to_be_validated)\n if isinstance(value, Weight):\n value_to_be_validated = Decimal(value.value)\n # default decimal validators can be used for Weight's value only\n self.run_validators(value_to_be_validated)\n return value\n", "path": "saleor/core/weight.py"}, {"content": "import graphene\n\nfrom ...core import TaxRateType as CoreTaxRateType, weight\nfrom ...core.permissions import MODELS_PERMISSIONS\nfrom .utils import str_to_enum\n\n\nclass ReportingPeriod(graphene.Enum):\n TODAY = 'TODAY'\n THIS_MONTH = 'THIS_MONTH'\n\n\nTaxRateType = graphene.Enum(\n 'TaxRateType',\n [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES])\n\n\nPermissionEnum = graphene.Enum(\n 'PermissionEnum', [\n (str_to_enum(codename.split('.')[1]), codename)\n for codename in MODELS_PERMISSIONS])\n\n\nWeightUnitsEnum = graphene.Enum.from_enum(weight.WeightUnitsEnum)\n", "path": "saleor/graphql/core/enums.py"}], "after_files": [{"content": "\"\"\"In Saleor we are using 'weight' instead of a 'mass'.\n\nFor those of us who are earth-bound, weight is what we usually experience.\nMass is a theoretical construct.\nUnless we are dealing with inertia and momentum, we are encountering\nthe attractive force between ourselves and the earth,\nthe isolated effects of mass alone being a little more esoteric.\n\nSo even though mass is more fundamental, most people think\nin terms of weight.\n\nIn the end, it does not really matter unless you travel between\ndifferent planets.\n\"\"\"\nfrom decimal import Decimal\n\nfrom django import forms\nfrom django.contrib.sites.models import Site\nfrom django.core.validators import MinValueValidator\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import pgettext_lazy\nfrom measurement.measures import Weight\n\n\nclass WeightUnits:\n KILOGRAM = 'kg'\n POUND = 'lb'\n OUNCE = 'oz'\n GRAM = 'g'\n\n CHOICES = [\n (KILOGRAM, pgettext_lazy('Kilogram weight unit symbol', 'kg')),\n (POUND, pgettext_lazy('Pound weight unit symbol', 'lb')),\n (OUNCE, pgettext_lazy('Ounce weight unit symbol', 'oz')),\n (GRAM, pgettext_lazy('Gram weight unit symbol', 'g'))]\n\n\ndef zero_weight():\n \"\"\"Represent the zero weight value.\"\"\"\n return Weight(kg=0)\n\n\ndef convert_weight(weight, unit):\n # Weight amount from the Weight instance can be retrived in serveral units\n # via its properties. eg. Weight(lb=10).kg\n converted_weight = getattr(weight, unit)\n return Weight(**{unit: converted_weight})\n\n\ndef get_default_weight_unit():\n site = Site.objects.get_current()\n return site.settings.default_weight_unit\n\n\nclass WeightInput(forms.TextInput):\n template = 'dashboard/shipping/weight_widget.html'\n input_type = 'number'\n\n def format_value(self, value):\n if isinstance(value, Weight):\n unit = get_default_weight_unit()\n if value.unit != unit:\n value = convert_weight(value, unit)\n return value.value\n return value\n\n def render(self, name, value, attrs=None, renderer=None):\n widget = super().render(name, value, attrs=attrs, renderer=renderer)\n unit = get_default_weight_unit()\n translated_unit = dict(WeightUnits.CHOICES)[unit]\n return render_to_string(\n self.template,\n {'widget': widget, 'value': value, 'unit': translated_unit})\n\n\nclass WeightField(forms.FloatField):\n def __init__(self, *args, widget=WeightInput, min_value=0, **kwargs):\n if isinstance(widget, type):\n widget = widget(attrs={'type': 'number', 'step': 'any'})\n super().__init__(*args, widget=widget, **kwargs)\n if min_value is not None:\n self.validators.append(MinValueValidator(min_value))\n\n def to_python(self, value):\n value = super().to_python(value)\n if value is None:\n return value\n unit = get_default_weight_unit()\n return Weight(**{unit: value})\n\n def validate(self, weight):\n if weight is None or weight in self.empty_values:\n super().validate(weight)\n else:\n unit = get_default_weight_unit()\n if not isinstance(weight, Weight):\n raise Exception(\n '%r is not a valid weight.' % (weight,))\n if weight.unit != unit:\n raise forms.ValidationError(\n 'Invalid unit: %r (expected %r).' % (\n weight.unit, unit))\n super().validate(weight.value)\n\n def clean(self, value):\n value = value_to_be_validated = self.to_python(value)\n self.validate(value_to_be_validated)\n if isinstance(value, Weight):\n value_to_be_validated = Decimal(value.value)\n # default decimal validators can be used for Weight's value only\n self.run_validators(value_to_be_validated)\n return value\n", "path": "saleor/core/weight.py"}, {"content": "import graphene\n\nfrom ...core import TaxRateType as CoreTaxRateType\nfrom ...core.weight import WeightUnits\nfrom ...core.permissions import MODELS_PERMISSIONS\nfrom .utils import str_to_enum\n\n\nclass ReportingPeriod(graphene.Enum):\n TODAY = 'TODAY'\n THIS_MONTH = 'THIS_MONTH'\n\n\nTaxRateType = graphene.Enum(\n 'TaxRateType',\n [(str_to_enum(rate[0]), rate[0]) for rate in CoreTaxRateType.CHOICES])\n\n\nPermissionEnum = graphene.Enum(\n 'PermissionEnum', [\n (str_to_enum(codename.split('.')[1]), codename)\n for codename in MODELS_PERMISSIONS])\n\n\nWeightUnitsEnum = graphene.Enum(\n 'WeightUnitsEnum',\n [(str_to_enum(unit[0]), unit[0]) for unit in WeightUnits.CHOICES])\n", "path": "saleor/graphql/core/enums.py"}]}
1,705
350
gh_patches_debug_6778
rasdani/github-patches
git_diff
flairNLP__flair-160
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Flair depends on AWS CLI (boto library etc) --- should be removed/optional I assume that the usual Flair user does not need any AWS dependency, therefore the hard AWS CLI dependency (defined in `setup.py`) should be removed or at least made optional. --- 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 setup( 4 name='flair', 5 version='0.3.0', 6 description='A very simple framework for state-of-the-art NLP', 7 long_description=open("README.md", encoding='utf-8').read(), 8 long_description_content_type="text/markdown", 9 author='Alan Akbik', 10 author_email='[email protected]', 11 url='https://github.com/zalandoresearch/flair', 12 packages=find_packages(exclude='test'), # same as name 13 license='MIT', 14 install_requires=[ 15 'torch==0.4.1', 16 'awscli==1.14.32', 17 'gensim==3.4.0', 18 'typing==3.6.4', 19 'tqdm==4.23.4', 20 'segtok==1.5.6', 21 'matplotlib==3.0.0', 22 'mpld3==0.3', 23 'jinja2==2.10', 24 'sklearn', 25 'sqlitedict==1.6.0', 26 ], 27 include_package_data=True, 28 python_requires='>=3.6', 29 ) 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/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -13,14 +13,12 @@ license='MIT', install_requires=[ 'torch==0.4.1', - 'awscli==1.14.32', 'gensim==3.4.0', 'typing==3.6.4', 'tqdm==4.23.4', 'segtok==1.5.6', 'matplotlib==3.0.0', 'mpld3==0.3', - 'jinja2==2.10', 'sklearn', 'sqlitedict==1.6.0', ],
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -13,14 +13,12 @@\n license='MIT',\n install_requires=[\n 'torch==0.4.1',\n- 'awscli==1.14.32',\n 'gensim==3.4.0',\n 'typing==3.6.4',\n 'tqdm==4.23.4',\n 'segtok==1.5.6',\n 'matplotlib==3.0.0',\n 'mpld3==0.3',\n- 'jinja2==2.10',\n 'sklearn',\n 'sqlitedict==1.6.0',\n ],\n", "issue": "Flair depends on AWS CLI (boto library etc) --- should be removed/optional\nI assume that the usual Flair user does not need any AWS dependency, therefore the hard AWS CLI dependency (defined in `setup.py`) should be removed or at least made optional.\n", "before_files": [{"content": "from setuptools import setup, find_packages\n\nsetup(\n name='flair',\n version='0.3.0',\n description='A very simple framework for state-of-the-art NLP',\n long_description=open(\"README.md\", encoding='utf-8').read(),\n long_description_content_type=\"text/markdown\",\n author='Alan Akbik',\n author_email='[email protected]',\n url='https://github.com/zalandoresearch/flair',\n packages=find_packages(exclude='test'), # same as name\n license='MIT',\n install_requires=[\n 'torch==0.4.1',\n 'awscli==1.14.32',\n 'gensim==3.4.0',\n 'typing==3.6.4',\n 'tqdm==4.23.4',\n 'segtok==1.5.6',\n 'matplotlib==3.0.0',\n 'mpld3==0.3',\n 'jinja2==2.10',\n 'sklearn',\n 'sqlitedict==1.6.0',\n ],\n include_package_data=True,\n python_requires='>=3.6',\n)\n", "path": "setup.py"}], "after_files": [{"content": "from setuptools import setup, find_packages\n\nsetup(\n name='flair',\n version='0.3.0',\n description='A very simple framework for state-of-the-art NLP',\n long_description=open(\"README.md\", encoding='utf-8').read(),\n long_description_content_type=\"text/markdown\",\n author='Alan Akbik',\n author_email='[email protected]',\n url='https://github.com/zalandoresearch/flair',\n packages=find_packages(exclude='test'), # same as name\n license='MIT',\n install_requires=[\n 'torch==0.4.1',\n 'gensim==3.4.0',\n 'typing==3.6.4',\n 'tqdm==4.23.4',\n 'segtok==1.5.6',\n 'matplotlib==3.0.0',\n 'mpld3==0.3',\n 'sklearn',\n 'sqlitedict==1.6.0',\n ],\n include_package_data=True,\n python_requires='>=3.6',\n)\n", "path": "setup.py"}]}
625
164
gh_patches_debug_25887
rasdani/github-patches
git_diff
opendatacube__datacube-core-362
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Drop Support for Python 2 I'd like to propose that future development on Data Cube Core stop supporting Python 2 after the beginning of February 2018. We can continue to support Python 2 for bug fix releases of version 1.5.x, but beyond that it is an ongoing drain on the limited developer resources. --- 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 import versioneer 4 from setuptools import setup, find_packages 5 6 tests_require = [ 7 'compliance-checker', 8 'hypothesis', 9 'mock', 10 'objgraph', 11 'pycodestyle', 12 'pylint', 13 'pytest', 14 'pytest-cov', 15 'pytest-timeout', 16 ] 17 18 extras_require = { 19 'performance': ['ciso8601', 'bottleneck'], 20 'interactive': ['matplotlib', 'fiona'], 21 'distributed': ['distributed', 'dask[distributed]'], 22 'analytics': ['scipy', 'pyparsing', 'numexpr'], 23 'doc': ['Sphinx', 'setuptools'], 24 'replicas': ['paramiko', 'sshtunnel', 'tqdm'], 25 'celery': ['celery>=4', 'redis'], 26 's3': ['boto3==1.4.3', 'SharedArray', 'pathos', 'zstandard'], 27 'test': tests_require, 28 } 29 # An 'all' option, following ipython naming conventions. 30 extras_require['all'] = sorted(set(sum(extras_require.values(), []))) 31 32 setup( 33 name='datacube', 34 version=versioneer.get_version(), 35 cmdclass=versioneer.get_cmdclass(), 36 37 url='https://github.com/opendatacube/datacube-core', 38 author='AGDC Collaboration', 39 maintainer='AGDC Collaboration', 40 maintainer_email='', 41 description='An analysis environment for satellite and other earth observation data', 42 long_description=open('README.rst').read(), 43 license='Apache License 2.0', 44 classifiers=[ 45 "Development Status :: 4 - Beta", 46 "Intended Audience :: Developers", 47 "Intended Audience :: Science/Research", 48 "License :: OSI Approved :: Apache Software License", 49 "Natural Language :: English", 50 "Operating System :: MacOS :: MacOS X", 51 "Operating System :: POSIX", 52 "Operating System :: POSIX :: BSD", 53 "Operating System :: POSIX :: Linux", 54 "Operating System :: Microsoft :: Windows", 55 "Programming Language :: Python", 56 "Programming Language :: Python :: 2", 57 "Programming Language :: Python :: 2.7", 58 "Programming Language :: Python :: 3", 59 "Programming Language :: Python :: 3.5", 60 "Topic :: Scientific/Engineering :: GIS", 61 "Topic :: Scientific/Engineering :: Information Analysis", 62 ], 63 64 packages=find_packages( 65 exclude=('tests', 'tests.*', 66 'integration_tests', 'integration_tests.*') 67 ), 68 package_data={ 69 '': ['*.yaml', '*/*.yaml'], 70 }, 71 scripts=[ 72 'datacube_apps/scripts/pbs_helpers.sh' 73 ], 74 setup_requires=[ 75 'pytest-runner' 76 ], 77 install_requires=[ 78 'affine', 79 'cachetools', 80 'click>=5.0', 81 'cloudpickle>=0.4', 82 'dask[array]', 83 'gdal>=1.9', 84 'jsonschema', 85 'netcdf4', 86 'numpy', 87 'pathlib;python_version<"3"', 88 'psycopg2', 89 'pypeg2', 90 'python-dateutil', 91 'pyyaml', 92 'rasterio>=0.9a10', # required for zip reading, 0.9 gets around 1.0a ordering problems 93 'singledispatch', 94 'sqlalchemy', 95 'xarray>=0.9', # >0.9 fixes most problems with `crs` attributes being lost 96 ], 97 extras_require=extras_require, 98 tests_require=tests_require, 99 100 entry_points={ 101 'console_scripts': [ 102 'datacube = datacube.scripts.cli_app:cli', 103 'datacube-search = datacube.scripts.search_tool:cli', 104 'datacube-stacker = datacube_apps.stacker:main', 105 'datacube-worker = datacube.execution.worker:main', 106 'datacube-fixer = datacube_apps.stacker:fixer_main', 107 'datacube-ncml = datacube_apps.ncml:ncml_app', 108 'pixeldrill = datacube_apps.pixeldrill:main [interactive]', 109 'movie_generator = datacube_apps.movie_generator:main', 110 'datacube-simple-replica = datacube_apps.simple_replica:replicate [replicas]' 111 ], 112 'datacube.plugins.io.read': [ 113 'netcdf = datacube.drivers.netcdf.driver:reader_driver_init', 114 's3aio = datacube.drivers.s3.driver:reader_driver_init', 115 's3aio_test = datacube.drivers.s3.driver:reader_test_driver_init' 116 ], 117 'datacube.plugins.io.write': [ 118 'netcdf = datacube.drivers.netcdf.driver:writer_driver_init', 119 's3aio = datacube.drivers.s3.driver:writer_driver_init', 120 's3aio_test = datacube.drivers.s3.driver:writer_test_driver_init', 121 ], 122 'datacube.plugins.index': [ 123 'default = datacube.index.index:index_driver_init', 124 's3aio_index = datacube.drivers.s3aio_index:index_driver_init', 125 ], 126 }, 127 ) 128 ``` --- 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 @@ -33,6 +33,7 @@ name='datacube', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), + python_requires='>3.5.2', url='https://github.com/opendatacube/datacube-core', author='AGDC Collaboration', @@ -53,10 +54,9 @@ "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering :: GIS", "Topic :: Scientific/Engineering :: Information Analysis", ], @@ -84,7 +84,6 @@ 'jsonschema', 'netcdf4', 'numpy', - 'pathlib;python_version<"3"', 'psycopg2', 'pypeg2', 'python-dateutil',
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -33,6 +33,7 @@\n name='datacube',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n+ python_requires='>3.5.2',\n \n url='https://github.com/opendatacube/datacube-core',\n author='AGDC Collaboration',\n@@ -53,10 +54,9 @@\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: Microsoft :: Windows\",\n \"Programming Language :: Python\",\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 \"Topic :: Scientific/Engineering :: GIS\",\n \"Topic :: Scientific/Engineering :: Information Analysis\",\n ],\n@@ -84,7 +84,6 @@\n 'jsonschema',\n 'netcdf4',\n 'numpy',\n- 'pathlib;python_version<\"3\"',\n 'psycopg2',\n 'pypeg2',\n 'python-dateutil',\n", "issue": "Drop Support for Python 2\nI'd like to propose that future development on Data Cube Core stop supporting Python 2 after the beginning of February 2018.\r\n\r\nWe can continue to support Python 2 for bug fix releases of version 1.5.x, but beyond that it is an ongoing drain on the limited developer resources.\n", "before_files": [{"content": "#!/usr/bin/env python\n\nimport versioneer\nfrom setuptools import setup, find_packages\n\ntests_require = [\n 'compliance-checker',\n 'hypothesis',\n 'mock',\n 'objgraph',\n 'pycodestyle',\n 'pylint',\n 'pytest',\n 'pytest-cov',\n 'pytest-timeout',\n]\n\nextras_require = {\n 'performance': ['ciso8601', 'bottleneck'],\n 'interactive': ['matplotlib', 'fiona'],\n 'distributed': ['distributed', 'dask[distributed]'],\n 'analytics': ['scipy', 'pyparsing', 'numexpr'],\n 'doc': ['Sphinx', 'setuptools'],\n 'replicas': ['paramiko', 'sshtunnel', 'tqdm'],\n 'celery': ['celery>=4', 'redis'],\n 's3': ['boto3==1.4.3', 'SharedArray', 'pathos', 'zstandard'],\n 'test': tests_require,\n}\n# An 'all' option, following ipython naming conventions.\nextras_require['all'] = sorted(set(sum(extras_require.values(), [])))\n\nsetup(\n name='datacube',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n\n url='https://github.com/opendatacube/datacube-core',\n author='AGDC Collaboration',\n maintainer='AGDC Collaboration',\n maintainer_email='',\n description='An analysis environment for satellite and other earth observation data',\n long_description=open('README.rst').read(),\n license='Apache License 2.0',\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Natural Language :: English\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: POSIX\",\n \"Operating System :: POSIX :: BSD\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: Microsoft :: Windows\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Topic :: Scientific/Engineering :: GIS\",\n \"Topic :: Scientific/Engineering :: Information Analysis\",\n ],\n\n packages=find_packages(\n exclude=('tests', 'tests.*',\n 'integration_tests', 'integration_tests.*')\n ),\n package_data={\n '': ['*.yaml', '*/*.yaml'],\n },\n scripts=[\n 'datacube_apps/scripts/pbs_helpers.sh'\n ],\n setup_requires=[\n 'pytest-runner'\n ],\n install_requires=[\n 'affine',\n 'cachetools',\n 'click>=5.0',\n 'cloudpickle>=0.4',\n 'dask[array]',\n 'gdal>=1.9',\n 'jsonschema',\n 'netcdf4',\n 'numpy',\n 'pathlib;python_version<\"3\"',\n 'psycopg2',\n 'pypeg2',\n 'python-dateutil',\n 'pyyaml',\n 'rasterio>=0.9a10', # required for zip reading, 0.9 gets around 1.0a ordering problems\n 'singledispatch',\n 'sqlalchemy',\n 'xarray>=0.9', # >0.9 fixes most problems with `crs` attributes being lost\n ],\n extras_require=extras_require,\n tests_require=tests_require,\n\n entry_points={\n 'console_scripts': [\n 'datacube = datacube.scripts.cli_app:cli',\n 'datacube-search = datacube.scripts.search_tool:cli',\n 'datacube-stacker = datacube_apps.stacker:main',\n 'datacube-worker = datacube.execution.worker:main',\n 'datacube-fixer = datacube_apps.stacker:fixer_main',\n 'datacube-ncml = datacube_apps.ncml:ncml_app',\n 'pixeldrill = datacube_apps.pixeldrill:main [interactive]',\n 'movie_generator = datacube_apps.movie_generator:main',\n 'datacube-simple-replica = datacube_apps.simple_replica:replicate [replicas]'\n ],\n 'datacube.plugins.io.read': [\n 'netcdf = datacube.drivers.netcdf.driver:reader_driver_init',\n 's3aio = datacube.drivers.s3.driver:reader_driver_init',\n 's3aio_test = datacube.drivers.s3.driver:reader_test_driver_init'\n ],\n 'datacube.plugins.io.write': [\n 'netcdf = datacube.drivers.netcdf.driver:writer_driver_init',\n 's3aio = datacube.drivers.s3.driver:writer_driver_init',\n 's3aio_test = datacube.drivers.s3.driver:writer_test_driver_init',\n ],\n 'datacube.plugins.index': [\n 'default = datacube.index.index:index_driver_init',\n 's3aio_index = datacube.drivers.s3aio_index:index_driver_init',\n ],\n },\n)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\nimport versioneer\nfrom setuptools import setup, find_packages\n\ntests_require = [\n 'compliance-checker',\n 'hypothesis',\n 'mock',\n 'objgraph',\n 'pycodestyle',\n 'pylint',\n 'pytest',\n 'pytest-cov',\n 'pytest-timeout',\n]\n\nextras_require = {\n 'performance': ['ciso8601', 'bottleneck'],\n 'interactive': ['matplotlib', 'fiona'],\n 'distributed': ['distributed', 'dask[distributed]'],\n 'analytics': ['scipy', 'pyparsing', 'numexpr'],\n 'doc': ['Sphinx', 'setuptools'],\n 'replicas': ['paramiko', 'sshtunnel', 'tqdm'],\n 'celery': ['celery>=4', 'redis'],\n 's3': ['boto3==1.4.3', 'SharedArray', 'pathos', 'zstandard'],\n 'test': tests_require,\n}\n# An 'all' option, following ipython naming conventions.\nextras_require['all'] = sorted(set(sum(extras_require.values(), [])))\n\nsetup(\n name='datacube',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n python_requires='>3.5.2',\n\n url='https://github.com/opendatacube/datacube-core',\n author='AGDC Collaboration',\n maintainer='AGDC Collaboration',\n maintainer_email='',\n description='An analysis environment for satellite and other earth observation data',\n long_description=open('README.rst').read(),\n license='Apache License 2.0',\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Natural Language :: English\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: POSIX\",\n \"Operating System :: POSIX :: BSD\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: Microsoft :: Windows\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Scientific/Engineering :: GIS\",\n \"Topic :: Scientific/Engineering :: Information Analysis\",\n ],\n\n packages=find_packages(\n exclude=('tests', 'tests.*',\n 'integration_tests', 'integration_tests.*')\n ),\n package_data={\n '': ['*.yaml', '*/*.yaml'],\n },\n scripts=[\n 'datacube_apps/scripts/pbs_helpers.sh'\n ],\n setup_requires=[\n 'pytest-runner'\n ],\n install_requires=[\n 'affine',\n 'cachetools',\n 'click>=5.0',\n 'cloudpickle>=0.4',\n 'dask[array]',\n 'gdal>=1.9',\n 'jsonschema',\n 'netcdf4',\n 'numpy',\n 'psycopg2',\n 'pypeg2',\n 'python-dateutil',\n 'pyyaml',\n 'rasterio>=0.9a10', # required for zip reading, 0.9 gets around 1.0a ordering problems\n 'singledispatch',\n 'sqlalchemy',\n 'xarray>=0.9', # >0.9 fixes most problems with `crs` attributes being lost\n ],\n extras_require=extras_require,\n tests_require=tests_require,\n\n entry_points={\n 'console_scripts': [\n 'datacube = datacube.scripts.cli_app:cli',\n 'datacube-search = datacube.scripts.search_tool:cli',\n 'datacube-stacker = datacube_apps.stacker:main',\n 'datacube-worker = datacube.execution.worker:main',\n 'datacube-fixer = datacube_apps.stacker:fixer_main',\n 'datacube-ncml = datacube_apps.ncml:ncml_app',\n 'pixeldrill = datacube_apps.pixeldrill:main [interactive]',\n 'movie_generator = datacube_apps.movie_generator:main',\n 'datacube-simple-replica = datacube_apps.simple_replica:replicate [replicas]'\n ],\n 'datacube.plugins.io.read': [\n 'netcdf = datacube.drivers.netcdf.driver:reader_driver_init',\n 's3aio = datacube.drivers.s3.driver:reader_driver_init',\n 's3aio_test = datacube.drivers.s3.driver:reader_test_driver_init'\n ],\n 'datacube.plugins.io.write': [\n 'netcdf = datacube.drivers.netcdf.driver:writer_driver_init',\n 's3aio = datacube.drivers.s3.driver:writer_driver_init',\n 's3aio_test = datacube.drivers.s3.driver:writer_test_driver_init',\n ],\n 'datacube.plugins.index': [\n 'default = datacube.index.index:index_driver_init',\n 's3aio_index = datacube.drivers.s3aio_index:index_driver_init',\n ],\n },\n)\n", "path": "setup.py"}]}
1,713
268
gh_patches_debug_32556
rasdani/github-patches
git_diff
streamlink__streamlink-121
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Plugin LivecodingTV fails to load on Python 3.6.0b2 on Windows 10 x64 Just running streamlink raises the following error on my system with a fresh install: ``` C:\WINDOWS\system32>streamlink Failed to load plugin livecodingtv: File "c:\program files\python36\lib\imp.py", line 234, in load_module return load_source(name, filename, file) File "c:\program files\python36\lib\imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 675, in _load File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 677, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "c:\program files\python36\lib\site-packages\streamlink\plugins\livecodingtv.py", line 9, in <module> _url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') File "c:\program files\python36\lib\re.py", line 233, in compile return _compile(pattern, flags) File "c:\program files\python36\lib\re.py", line 301, in _compile p = sre_compile.compile(pattern, flags) File "c:\program files\python36\lib\sre_compile.py", line 562, in compile p = sre_parse.parse(p, flags) File "c:\program files\python36\lib\sre_parse.py", line 856, in parse p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False) File "c:\program files\python36\lib\sre_parse.py", line 415, in _parse_sub itemsappend(_parse(source, state, verbose)) File "c:\program files\python36\lib\sre_parse.py", line 501, in _parse code = _escape(source, this, state) File "c:\program files\python36\lib\sre_parse.py", line 401, in _escape raise source.error("bad escape %s" % escape, len(escape)) sre_constants.error: bad escape \l at position 20 usage: streamlink [OPTIONS] [URL] [STREAM] Use -h/--help to see the available options or read the manual at http://docs.streamlink.io/ C:\WINDOWS\system32>python --version Python 3.6.0b2 ``` --- 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/livecodingtv.py` Content: ``` 1 import re 2 from streamlink.plugin import Plugin 3 from streamlink.stream import RTMPStream, HTTPStream 4 from streamlink.plugin.api import http 5 6 7 _vod_re = re.compile('\"(http(s)?://.*\.mp4\?t=.*)\"') 8 _rtmp_re = re.compile('rtmp://[^"]+/(?P<channel>\w+)+[^/"]+') 9 _url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') 10 11 12 class LivecodingTV(Plugin): 13 @classmethod 14 def can_handle_url(cls, url): 15 return _url_re.match(url) 16 17 def _get_streams(self): 18 res = http.get(self.url) 19 match = _rtmp_re.search(res.content.decode('utf-8')) 20 if match: 21 params = { 22 "rtmp": match.group(0), 23 "pageUrl": self.url, 24 "live": True, 25 } 26 yield 'live', RTMPStream(self.session, params) 27 return 28 29 match = _vod_re.search(res.content.decode('utf-8')) 30 if match: 31 yield 'vod', HTTPStream(self.session, match.group(1)) 32 33 __plugin__ = LivecodingTV 34 ``` --- 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/livecodingtv.py b/src/streamlink/plugins/livecodingtv.py --- a/src/streamlink/plugins/livecodingtv.py +++ b/src/streamlink/plugins/livecodingtv.py @@ -1,12 +1,20 @@ import re from streamlink.plugin import Plugin +from streamlink.stream import HLSStream from streamlink.stream import RTMPStream, HTTPStream from streamlink.plugin.api import http -_vod_re = re.compile('\"(http(s)?://.*\.mp4\?t=.*)\"') -_rtmp_re = re.compile('rtmp://[^"]+/(?P<channel>\w+)+[^/"]+') -_url_re = re.compile('http(s)?://(?:\w+.)?\livecoding\.tv') +_streams_re = re.compile(r""" + src:\s+"( + rtmp://.*?\?t=.*?| # RTMP stream + https?://.*?playlist.m3u8.*?\?t=.*?| # HLS stream + https?://.*?manifest.mpd.*?\?t=.*?| # DASH stream + https?://.*?.mp4\?t=.*? # HTTP stream + )".*? + type:\s+"(.*?)" # which stream type it is + """, re.M | re.DOTALL | re.VERBOSE) +_url_re = re.compile(r"http(s)?://(?:\w+\.)?livecoding\.tv") class LivecodingTV(Plugin): @@ -16,18 +24,19 @@ def _get_streams(self): res = http.get(self.url) - match = _rtmp_re.search(res.content.decode('utf-8')) - if match: - params = { - "rtmp": match.group(0), - "pageUrl": self.url, - "live": True, - } - yield 'live', RTMPStream(self.session, params) - return - - match = _vod_re.search(res.content.decode('utf-8')) - if match: - yield 'vod', HTTPStream(self.session, match.group(1)) + match = _streams_re.findall(res.content.decode('utf-8')) + for url, stream_type in match: + if stream_type == "rtmp/mp4" and RTMPStream.is_usable(self.session): + params = { + "rtmp": url, + "pageUrl": self.url, + "live": True, + } + yield 'live', RTMPStream(self.session, params) + elif stream_type == "application/x-mpegURL": + for s in HLSStream.parse_variant_playlist(self.session, url).items(): + yield s + elif stream_type == "video/mp4": + yield 'vod', HTTPStream(self.session, url) __plugin__ = LivecodingTV
{"golden_diff": "diff --git a/src/streamlink/plugins/livecodingtv.py b/src/streamlink/plugins/livecodingtv.py\n--- a/src/streamlink/plugins/livecodingtv.py\n+++ b/src/streamlink/plugins/livecodingtv.py\n@@ -1,12 +1,20 @@\n import re\n from streamlink.plugin import Plugin\n+from streamlink.stream import HLSStream\n from streamlink.stream import RTMPStream, HTTPStream\n from streamlink.plugin.api import http\n \n \n-_vod_re = re.compile('\\\"(http(s)?://.*\\.mp4\\?t=.*)\\\"')\n-_rtmp_re = re.compile('rtmp://[^\"]+/(?P<channel>\\w+)+[^/\"]+')\n-_url_re = re.compile('http(s)?://(?:\\w+.)?\\livecoding\\.tv')\n+_streams_re = re.compile(r\"\"\"\n+ src:\\s+\"(\n+ rtmp://.*?\\?t=.*?| # RTMP stream\n+ https?://.*?playlist.m3u8.*?\\?t=.*?| # HLS stream\n+ https?://.*?manifest.mpd.*?\\?t=.*?| # DASH stream\n+ https?://.*?.mp4\\?t=.*? # HTTP stream\n+ )\".*?\n+ type:\\s+\"(.*?)\" # which stream type it is\n+ \"\"\", re.M | re.DOTALL | re.VERBOSE)\n+_url_re = re.compile(r\"http(s)?://(?:\\w+\\.)?livecoding\\.tv\")\n \n \n class LivecodingTV(Plugin):\n@@ -16,18 +24,19 @@\n \n def _get_streams(self):\n res = http.get(self.url)\n- match = _rtmp_re.search(res.content.decode('utf-8'))\n- if match:\n- params = {\n- \"rtmp\": match.group(0),\n- \"pageUrl\": self.url,\n- \"live\": True,\n- }\n- yield 'live', RTMPStream(self.session, params)\n- return\n-\n- match = _vod_re.search(res.content.decode('utf-8'))\n- if match:\n- yield 'vod', HTTPStream(self.session, match.group(1))\n+ match = _streams_re.findall(res.content.decode('utf-8'))\n+ for url, stream_type in match:\n+ if stream_type == \"rtmp/mp4\" and RTMPStream.is_usable(self.session):\n+ params = {\n+ \"rtmp\": url,\n+ \"pageUrl\": self.url,\n+ \"live\": True,\n+ }\n+ yield 'live', RTMPStream(self.session, params)\n+ elif stream_type == \"application/x-mpegURL\":\n+ for s in HLSStream.parse_variant_playlist(self.session, url).items():\n+ yield s\n+ elif stream_type == \"video/mp4\":\n+ yield 'vod', HTTPStream(self.session, url)\n \n __plugin__ = LivecodingTV\n", "issue": "Plugin LivecodingTV fails to load on Python 3.6.0b2 on Windows 10 x64\nJust running streamlink raises the following error on my system with a fresh install:\n\n```\nC:\\WINDOWS\\system32>streamlink\nFailed to load plugin livecodingtv:\n File \"c:\\program files\\python36\\lib\\imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n File \"c:\\program files\\python36\\lib\\imp.py\", line 172, in load_source\n module = _load(spec)\n File \"<frozen importlib._bootstrap>\", line 675, in _load\n File \"<frozen importlib._bootstrap>\", line 655, in _load_unlocked\n File \"<frozen importlib._bootstrap_external>\", line 677, in exec_module\n File \"<frozen importlib._bootstrap>\", line 205, in _call_with_frames_removed\n File \"c:\\program files\\python36\\lib\\site-packages\\streamlink\\plugins\\livecodingtv.py\", line 9, in <module>\n _url_re = re.compile('http(s)?://(?:\\w+.)?\\livecoding\\.tv')\n File \"c:\\program files\\python36\\lib\\re.py\", line 233, in compile\n return _compile(pattern, flags)\n File \"c:\\program files\\python36\\lib\\re.py\", line 301, in _compile\n p = sre_compile.compile(pattern, flags)\n File \"c:\\program files\\python36\\lib\\sre_compile.py\", line 562, in compile\n p = sre_parse.parse(p, flags)\n File \"c:\\program files\\python36\\lib\\sre_parse.py\", line 856, in parse\n p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)\n File \"c:\\program files\\python36\\lib\\sre_parse.py\", line 415, in _parse_sub\n itemsappend(_parse(source, state, verbose))\n File \"c:\\program files\\python36\\lib\\sre_parse.py\", line 501, in _parse\n code = _escape(source, this, state)\n File \"c:\\program files\\python36\\lib\\sre_parse.py\", line 401, in _escape\n raise source.error(\"bad escape %s\" % escape, len(escape))\nsre_constants.error: bad escape \\l at position 20\n\nusage: streamlink [OPTIONS] [URL] [STREAM]\n\nUse -h/--help to see the available options or read the manual at http://docs.streamlink.io/\n\nC:\\WINDOWS\\system32>python --version\nPython 3.6.0b2\n```\n\n", "before_files": [{"content": "import re\nfrom streamlink.plugin import Plugin\nfrom streamlink.stream import RTMPStream, HTTPStream\nfrom streamlink.plugin.api import http\n\n\n_vod_re = re.compile('\\\"(http(s)?://.*\\.mp4\\?t=.*)\\\"')\n_rtmp_re = re.compile('rtmp://[^\"]+/(?P<channel>\\w+)+[^/\"]+')\n_url_re = re.compile('http(s)?://(?:\\w+.)?\\livecoding\\.tv')\n\n\nclass LivecodingTV(Plugin):\n @classmethod\n def can_handle_url(cls, url):\n return _url_re.match(url)\n\n def _get_streams(self):\n res = http.get(self.url)\n match = _rtmp_re.search(res.content.decode('utf-8'))\n if match:\n params = {\n \"rtmp\": match.group(0),\n \"pageUrl\": self.url,\n \"live\": True,\n }\n yield 'live', RTMPStream(self.session, params)\n return\n\n match = _vod_re.search(res.content.decode('utf-8'))\n if match:\n yield 'vod', HTTPStream(self.session, match.group(1))\n\n__plugin__ = LivecodingTV\n", "path": "src/streamlink/plugins/livecodingtv.py"}], "after_files": [{"content": "import re\nfrom streamlink.plugin import Plugin\nfrom streamlink.stream import HLSStream\nfrom streamlink.stream import RTMPStream, HTTPStream\nfrom streamlink.plugin.api import http\n\n\n_streams_re = re.compile(r\"\"\"\n src:\\s+\"(\n rtmp://.*?\\?t=.*?| # RTMP stream\n https?://.*?playlist.m3u8.*?\\?t=.*?| # HLS stream\n https?://.*?manifest.mpd.*?\\?t=.*?| # DASH stream\n https?://.*?.mp4\\?t=.*? # HTTP stream\n )\".*?\n type:\\s+\"(.*?)\" # which stream type it is\n \"\"\", re.M | re.DOTALL | re.VERBOSE)\n_url_re = re.compile(r\"http(s)?://(?:\\w+\\.)?livecoding\\.tv\")\n\n\nclass LivecodingTV(Plugin):\n @classmethod\n def can_handle_url(cls, url):\n return _url_re.match(url)\n\n def _get_streams(self):\n res = http.get(self.url)\n match = _streams_re.findall(res.content.decode('utf-8'))\n for url, stream_type in match:\n if stream_type == \"rtmp/mp4\" and RTMPStream.is_usable(self.session):\n params = {\n \"rtmp\": url,\n \"pageUrl\": self.url,\n \"live\": True,\n }\n yield 'live', RTMPStream(self.session, params)\n elif stream_type == \"application/x-mpegURL\":\n for s in HLSStream.parse_variant_playlist(self.session, url).items():\n yield s\n elif stream_type == \"video/mp4\":\n yield 'vod', HTTPStream(self.session, url)\n\n__plugin__ = LivecodingTV\n", "path": "src/streamlink/plugins/livecodingtv.py"}]}
1,212
647
gh_patches_debug_651
rasdani/github-patches
git_diff
DataDog__integrations-extras-1031
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Collect clock_time_seconds metric from cert-manager cert-manager v1.5+ exposes a `clock_time` metric which reports the current seconds since the Unix Epoch See: https://github.com/jetstack/cert-manager/pull/4105 It would be useful to collect this metric in DataDog so we can alert on seconds until a given certificate expires --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `cert_manager/datadog_checks/cert_manager/metrics.py` Content: ``` 1 # (C) Datadog, Inc. 2019-present 2 # All rights reserved 3 # Licensed under a 3-clause BSD style license (see LICENSE) 4 5 CERT_METRICS = { 6 'certmanager_certificate_ready_status': 'certificate.ready_status', 7 'certmanager_certificate_expiration_timestamp_seconds': 'certificate.expiration_timestamp', 8 } 9 10 CONTROLLER_METRICS = { 11 'certmanager_controller_sync_call_count': 'controller.sync_call.count', 12 } 13 14 ACME_METRICS = { 15 'certmanager_http_acme_client_request_count': 'http_acme_client.request.count', 16 'certmanager_http_acme_client_request_duration_seconds': 'http_acme_client.request.duration', 17 } 18 ``` --- 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/cert_manager/datadog_checks/cert_manager/metrics.py b/cert_manager/datadog_checks/cert_manager/metrics.py --- a/cert_manager/datadog_checks/cert_manager/metrics.py +++ b/cert_manager/datadog_checks/cert_manager/metrics.py @@ -8,6 +8,7 @@ } CONTROLLER_METRICS = { + 'certmanager_clock_time_seconds': 'clock_time', 'certmanager_controller_sync_call_count': 'controller.sync_call.count', }
{"golden_diff": "diff --git a/cert_manager/datadog_checks/cert_manager/metrics.py b/cert_manager/datadog_checks/cert_manager/metrics.py\n--- a/cert_manager/datadog_checks/cert_manager/metrics.py\n+++ b/cert_manager/datadog_checks/cert_manager/metrics.py\n@@ -8,6 +8,7 @@\n }\n \n CONTROLLER_METRICS = {\n+ 'certmanager_clock_time_seconds': 'clock_time',\n 'certmanager_controller_sync_call_count': 'controller.sync_call.count',\n }\n", "issue": "Collect clock_time_seconds metric from cert-manager\ncert-manager v1.5+ exposes a `clock_time` metric which reports the current seconds since the Unix Epoch\r\nSee: https://github.com/jetstack/cert-manager/pull/4105\r\n\r\nIt would be useful to collect this metric in DataDog so we can alert on seconds until a given certificate expires\r\n\n", "before_files": [{"content": "# (C) Datadog, Inc. 2019-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\n\nCERT_METRICS = {\n 'certmanager_certificate_ready_status': 'certificate.ready_status',\n 'certmanager_certificate_expiration_timestamp_seconds': 'certificate.expiration_timestamp',\n}\n\nCONTROLLER_METRICS = {\n 'certmanager_controller_sync_call_count': 'controller.sync_call.count',\n}\n\nACME_METRICS = {\n 'certmanager_http_acme_client_request_count': 'http_acme_client.request.count',\n 'certmanager_http_acme_client_request_duration_seconds': 'http_acme_client.request.duration',\n}\n", "path": "cert_manager/datadog_checks/cert_manager/metrics.py"}], "after_files": [{"content": "# (C) Datadog, Inc. 2019-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\n\nCERT_METRICS = {\n 'certmanager_certificate_ready_status': 'certificate.ready_status',\n 'certmanager_certificate_expiration_timestamp_seconds': 'certificate.expiration_timestamp',\n}\n\nCONTROLLER_METRICS = {\n 'certmanager_clock_time_seconds': 'clock_time',\n 'certmanager_controller_sync_call_count': 'controller.sync_call.count',\n}\n\nACME_METRICS = {\n 'certmanager_http_acme_client_request_count': 'http_acme_client.request.count',\n 'certmanager_http_acme_client_request_duration_seconds': 'http_acme_client.request.duration',\n}\n", "path": "cert_manager/datadog_checks/cert_manager/metrics.py"}]}
513
111
gh_patches_debug_3393
rasdani/github-patches
git_diff
aio-libs__aiohttp-2794
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Chat demo not working in aiohttp 3 ## Long story short Want to learn websockets with example code. There's a lack of simple and runnable example code on the net demonstrating websockets in python. ## Expected behaviour Server runs and page loads ## Actual behaviour Server runs but page fails to load with following error: ``` ~/work/aiohttp/demos/chat$ ~/venv3/bin/python aiohttpdemo_chat/main.py DEBUG:asyncio:Using selector: EpollSelector ======== Running on http://0.0.0.0:8080 ======== (Press CTRL+C to quit) ERROR:aiohttp.server:Error handling request Traceback (most recent call last): File "/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_protocol.py", line 381, in start resp = await self._request_handler(request) File "/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_app.py", line 310, in _handle resp = await handler(request) File "/home/robin/venv3/lib/python3.6/site-packages/aiohttpdemo_chat-0.0.1-py3.6.egg/aiohttpdemo_chat/views.py", line 15, in index ok, protocol = resp.can_start(request) AttributeError: 'WebSocketResponse' object has no attribute 'can_start' ``` ## Steps to reproduce Just run `aiohttpdemo_chat/main.py` ## Your environment archlinux, aiohttp 3.0.5 server? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `demos/chat/aiohttpdemo_chat/views.py` Content: ``` 1 import json 2 import logging 3 import random 4 import string 5 6 import aiohttp_jinja2 7 from aiohttp import web 8 9 10 log = logging.getLogger(__name__) 11 12 13 async def index(request): 14 resp = web.WebSocketResponse() 15 ok, protocol = resp.can_start(request) 16 if not ok: 17 return aiohttp_jinja2.render_template('index.html', request, {}) 18 19 await resp.prepare(request) 20 name = (random.choice(string.ascii_uppercase) + 21 ''.join(random.sample(string.ascii_lowercase*10, 10))) 22 log.info('%s joined.', name) 23 await resp.send_str(json.dumps({'action': 'connect', 24 'name': name})) 25 for ws in request.app['sockets'].values(): 26 await ws.send_str(json.dumps({'action': 'join', 27 'name': name})) 28 request.app['sockets'][name] = resp 29 30 while True: 31 msg = await resp.receive() 32 33 if msg.type == web.MsgType.text: 34 for ws in request.app['sockets'].values(): 35 if ws is not resp: 36 await ws.send_str(json.dumps({'action': 'sent', 37 'name': name, 38 'text': msg.data})) 39 else: 40 break 41 42 del request.app['sockets'][name] 43 log.info('%s disconnected.', name) 44 for ws in request.app['sockets'].values(): 45 await ws.send_str(json.dumps({'action': 'disconnect', 46 'name': name})) 47 return resp 48 49 50 def setup(app): 51 app.router.add_get('/', index) 52 ``` --- 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/demos/chat/aiohttpdemo_chat/views.py b/demos/chat/aiohttpdemo_chat/views.py --- a/demos/chat/aiohttpdemo_chat/views.py +++ b/demos/chat/aiohttpdemo_chat/views.py @@ -12,8 +12,8 @@ async def index(request): resp = web.WebSocketResponse() - ok, protocol = resp.can_start(request) - if not ok: + is_ws = resp.can_prepare(request) + if not is_ws: return aiohttp_jinja2.render_template('index.html', request, {}) await resp.prepare(request)
{"golden_diff": "diff --git a/demos/chat/aiohttpdemo_chat/views.py b/demos/chat/aiohttpdemo_chat/views.py\n--- a/demos/chat/aiohttpdemo_chat/views.py\n+++ b/demos/chat/aiohttpdemo_chat/views.py\n@@ -12,8 +12,8 @@\n \n async def index(request):\n resp = web.WebSocketResponse()\n- ok, protocol = resp.can_start(request)\n- if not ok:\n+ is_ws = resp.can_prepare(request)\n+ if not is_ws:\n return aiohttp_jinja2.render_template('index.html', request, {})\n \n await resp.prepare(request)\n", "issue": "Chat demo not working in aiohttp 3\n## Long story short\r\n\r\nWant to learn websockets with example code. There's a lack of simple and runnable example code on the net demonstrating websockets in python.\r\n\r\n## Expected behaviour\r\n\r\nServer runs and page loads\r\n\r\n## Actual behaviour\r\n\r\nServer runs but page fails to load with following error:\r\n```\r\n~/work/aiohttp/demos/chat$ ~/venv3/bin/python aiohttpdemo_chat/main.py \r\nDEBUG:asyncio:Using selector: EpollSelector\r\n======== Running on http://0.0.0.0:8080 ========\r\n(Press CTRL+C to quit)\r\nERROR:aiohttp.server:Error handling request\r\nTraceback (most recent call last):\r\n File \"/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_protocol.py\", line 381, in start\r\n resp = await self._request_handler(request)\r\n File \"/home/robin/venv3/lib/python3.6/site-packages/aiohttp/web_app.py\", line 310, in _handle\r\n resp = await handler(request)\r\n File \"/home/robin/venv3/lib/python3.6/site-packages/aiohttpdemo_chat-0.0.1-py3.6.egg/aiohttpdemo_chat/views.py\", line 15, in index\r\n ok, protocol = resp.can_start(request)\r\nAttributeError: 'WebSocketResponse' object has no attribute 'can_start'\r\n```\r\n\r\n## Steps to reproduce\r\n\r\nJust run `aiohttpdemo_chat/main.py`\r\n\r\n## Your environment\r\n\r\narchlinux, aiohttp 3.0.5 server?\r\n\n", "before_files": [{"content": "import json\nimport logging\nimport random\nimport string\n\nimport aiohttp_jinja2\nfrom aiohttp import web\n\n\nlog = logging.getLogger(__name__)\n\n\nasync def index(request):\n resp = web.WebSocketResponse()\n ok, protocol = resp.can_start(request)\n if not ok:\n return aiohttp_jinja2.render_template('index.html', request, {})\n\n await resp.prepare(request)\n name = (random.choice(string.ascii_uppercase) +\n ''.join(random.sample(string.ascii_lowercase*10, 10)))\n log.info('%s joined.', name)\n await resp.send_str(json.dumps({'action': 'connect',\n 'name': name}))\n for ws in request.app['sockets'].values():\n await ws.send_str(json.dumps({'action': 'join',\n 'name': name}))\n request.app['sockets'][name] = resp\n\n while True:\n msg = await resp.receive()\n\n if msg.type == web.MsgType.text:\n for ws in request.app['sockets'].values():\n if ws is not resp:\n await ws.send_str(json.dumps({'action': 'sent',\n 'name': name,\n 'text': msg.data}))\n else:\n break\n\n del request.app['sockets'][name]\n log.info('%s disconnected.', name)\n for ws in request.app['sockets'].values():\n await ws.send_str(json.dumps({'action': 'disconnect',\n 'name': name}))\n return resp\n\n\ndef setup(app):\n app.router.add_get('/', index)\n", "path": "demos/chat/aiohttpdemo_chat/views.py"}], "after_files": [{"content": "import json\nimport logging\nimport random\nimport string\n\nimport aiohttp_jinja2\nfrom aiohttp import web\n\n\nlog = logging.getLogger(__name__)\n\n\nasync def index(request):\n resp = web.WebSocketResponse()\n is_ws = resp.can_prepare(request)\n if not is_ws:\n return aiohttp_jinja2.render_template('index.html', request, {})\n\n await resp.prepare(request)\n name = (random.choice(string.ascii_uppercase) +\n ''.join(random.sample(string.ascii_lowercase*10, 10)))\n log.info('%s joined.', name)\n await resp.send_str(json.dumps({'action': 'connect',\n 'name': name}))\n for ws in request.app['sockets'].values():\n await ws.send_str(json.dumps({'action': 'join',\n 'name': name}))\n request.app['sockets'][name] = resp\n\n while True:\n msg = await resp.receive()\n\n if msg.type == web.MsgType.text:\n for ws in request.app['sockets'].values():\n if ws is not resp:\n await ws.send_str(json.dumps({'action': 'sent',\n 'name': name,\n 'text': msg.data}))\n else:\n break\n\n del request.app['sockets'][name]\n log.info('%s disconnected.', name)\n for ws in request.app['sockets'].values():\n await ws.send_str(json.dumps({'action': 'disconnect',\n 'name': name}))\n return resp\n\n\ndef setup(app):\n app.router.add_get('/', index)\n", "path": "demos/chat/aiohttpdemo_chat/views.py"}]}
1,033
135
gh_patches_debug_69
rasdani/github-patches
git_diff
d2l-ai__d2l-en-2256
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- ModuleNotFoundError when running the official pytorch colab notebook ![image](https://user-images.githubusercontent.com/33608782/184685789-951935c7-1725-4a23-944d-8d48b32bf76c.png) I can replicate the error at multiple official pytorch colab notebooks, e.g. https://colab.research.google.com/github/d2l-ai/d2l-pytorch-colab/blob/master/chapter_linear-classification/image-classification-dataset.ipynb#scrollTo=ee445cce --- 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 import d2l 3 4 requirements = [ 5 'jupyter', 6 'numpy', 7 'matplotlib', 8 'requests', 9 'pandas', 10 'gym' 11 ] 12 13 setup( 14 name='d2l', 15 version=d2l.__version__, 16 python_requires='>=3.5', 17 author='D2L Developers', 18 author_email='[email protected]', 19 url='https://d2l.ai', 20 description='Dive into Deep Learning', 21 license='MIT-0', 22 packages=find_packages(), 23 zip_safe=True, 24 install_requires=requirements, 25 ) 26 ``` --- 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 @@ -2,6 +2,7 @@ import d2l requirements = [ + 'ipython>=7.23', 'jupyter', 'numpy', 'matplotlib',
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -2,6 +2,7 @@\n import d2l\n \n requirements = [\n+ 'ipython>=7.23',\n 'jupyter',\n 'numpy',\n 'matplotlib',\n", "issue": "ModuleNotFoundError when running the official pytorch colab notebook\n![image](https://user-images.githubusercontent.com/33608782/184685789-951935c7-1725-4a23-944d-8d48b32bf76c.png)\r\n\r\nI can replicate the error at multiple official pytorch colab notebooks, e.g. \r\n\r\nhttps://colab.research.google.com/github/d2l-ai/d2l-pytorch-colab/blob/master/chapter_linear-classification/image-classification-dataset.ipynb#scrollTo=ee445cce\r\n\r\n\r\n\n", "before_files": [{"content": "from setuptools import setup, find_packages\nimport d2l\n\nrequirements = [\n 'jupyter',\n 'numpy',\n 'matplotlib',\n 'requests',\n 'pandas',\n 'gym'\n]\n\nsetup(\n name='d2l',\n version=d2l.__version__,\n python_requires='>=3.5',\n author='D2L Developers',\n author_email='[email protected]',\n url='https://d2l.ai',\n description='Dive into Deep Learning',\n license='MIT-0',\n packages=find_packages(),\n zip_safe=True,\n install_requires=requirements,\n)\n", "path": "setup.py"}], "after_files": [{"content": "from setuptools import setup, find_packages\nimport d2l\n\nrequirements = [\n 'ipython>=7.23',\n 'jupyter',\n 'numpy',\n 'matplotlib',\n 'requests',\n 'pandas'\n]\n\nsetup(\n name='d2l',\n version=d2l.__version__,\n python_requires='>=3.5',\n author='D2L Developers',\n author_email='[email protected]',\n url='https://d2l.ai',\n description='Dive into Deep Learning',\n license='MIT-0',\n packages=find_packages(),\n zip_safe=True,\n install_requires=requirements,\n)\n", "path": "setup.py"}]}
579
62
gh_patches_debug_49036
rasdani/github-patches
git_diff
facebookresearch__hydra-1960
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [CI] `mypy` fails for optuna sweeper on main Turns out it was caused by a newly released version of `alembic` and it has been fixed in optuna https://github.com/optuna/optuna/pull/2887 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `plugins/hydra_optuna_sweeper/setup.py` Content: ``` 1 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 # type: ignore 3 from pathlib import Path 4 5 from read_version import read_version 6 from setuptools import find_namespace_packages, setup 7 8 setup( 9 name="hydra-optuna-sweeper", 10 version=read_version("hydra_plugins/hydra_optuna_sweeper", "__init__.py"), 11 author="Toshihiko Yanase, Hiroyuki Vincent Yamazaki", 12 author_email="[email protected], [email protected]", 13 description="Hydra Optuna Sweeper plugin", 14 long_description=(Path(__file__).parent / "README.md").read_text(), 15 long_description_content_type="text/markdown", 16 url="https://github.com/facebookresearch/hydra/", 17 packages=find_namespace_packages(include=["hydra_plugins.*"]), 18 classifiers=[ 19 "License :: OSI Approved :: MIT License", 20 "Programming Language :: Python :: 3.6", 21 "Programming Language :: Python :: 3.7", 22 "Programming Language :: Python :: 3.8", 23 "Programming Language :: Python :: 3.9", 24 "Operating System :: POSIX :: Linux", 25 "Operating System :: MacOS", 26 "Development Status :: 4 - Beta", 27 ], 28 install_requires=[ 29 "hydra-core>=1.1.0.dev7", 30 "optuna>=2.5.0", 31 "alembic<1.7.0", # https://github.com/facebookresearch/hydra/issues/1806 32 ], 33 include_package_data=True, 34 ) 35 ``` --- 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/plugins/hydra_optuna_sweeper/setup.py b/plugins/hydra_optuna_sweeper/setup.py --- a/plugins/hydra_optuna_sweeper/setup.py +++ b/plugins/hydra_optuna_sweeper/setup.py @@ -27,8 +27,7 @@ ], install_requires=[ "hydra-core>=1.1.0.dev7", - "optuna>=2.5.0", - "alembic<1.7.0", # https://github.com/facebookresearch/hydra/issues/1806 + "optuna>=2.10.0", ], include_package_data=True, )
{"golden_diff": "diff --git a/plugins/hydra_optuna_sweeper/setup.py b/plugins/hydra_optuna_sweeper/setup.py\n--- a/plugins/hydra_optuna_sweeper/setup.py\n+++ b/plugins/hydra_optuna_sweeper/setup.py\n@@ -27,8 +27,7 @@\n ],\n install_requires=[\n \"hydra-core>=1.1.0.dev7\",\n- \"optuna>=2.5.0\",\n- \"alembic<1.7.0\", # https://github.com/facebookresearch/hydra/issues/1806\n+ \"optuna>=2.10.0\",\n ],\n include_package_data=True,\n )\n", "issue": "[CI] `mypy` fails for optuna sweeper on main\nTurns out it was caused by a newly released version of `alembic` and it has been fixed in optuna https://github.com/optuna/optuna/pull/2887\r\n\n", "before_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n# type: ignore\nfrom pathlib import Path\n\nfrom read_version import read_version\nfrom setuptools import find_namespace_packages, setup\n\nsetup(\n name=\"hydra-optuna-sweeper\",\n version=read_version(\"hydra_plugins/hydra_optuna_sweeper\", \"__init__.py\"),\n author=\"Toshihiko Yanase, Hiroyuki Vincent Yamazaki\",\n author_email=\"[email protected], [email protected]\",\n description=\"Hydra Optuna Sweeper plugin\",\n long_description=(Path(__file__).parent / \"README.md\").read_text(),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/facebookresearch/hydra/\",\n packages=find_namespace_packages(include=[\"hydra_plugins.*\"]),\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\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 \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS\",\n \"Development Status :: 4 - Beta\",\n ],\n install_requires=[\n \"hydra-core>=1.1.0.dev7\",\n \"optuna>=2.5.0\",\n \"alembic<1.7.0\", # https://github.com/facebookresearch/hydra/issues/1806\n ],\n include_package_data=True,\n)\n", "path": "plugins/hydra_optuna_sweeper/setup.py"}], "after_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n# type: ignore\nfrom pathlib import Path\n\nfrom read_version import read_version\nfrom setuptools import find_namespace_packages, setup\n\nsetup(\n name=\"hydra-optuna-sweeper\",\n version=read_version(\"hydra_plugins/hydra_optuna_sweeper\", \"__init__.py\"),\n author=\"Toshihiko Yanase, Hiroyuki Vincent Yamazaki\",\n author_email=\"[email protected], [email protected]\",\n description=\"Hydra Optuna Sweeper plugin\",\n long_description=(Path(__file__).parent / \"README.md\").read_text(),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/facebookresearch/hydra/\",\n packages=find_namespace_packages(include=[\"hydra_plugins.*\"]),\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\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 \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS\",\n \"Development Status :: 4 - Beta\",\n ],\n install_requires=[\n \"hydra-core>=1.1.0.dev7\",\n \"optuna>=2.10.0\",\n ],\n include_package_data=True,\n)\n", "path": "plugins/hydra_optuna_sweeper/setup.py"}]}
729
153
gh_patches_debug_14477
rasdani/github-patches
git_diff
Kinto__kinto-891
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add user principals to hello view Along `user` info, show the list of user principals (for groups notably) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `kinto/core/views/hello.py` Content: ``` 1 from pyramid.security import NO_PERMISSION_REQUIRED, Authenticated 2 3 from kinto.core import Service 4 5 hello = Service(name="hello", path='/', description="Welcome") 6 7 8 @hello.get(permission=NO_PERMISSION_REQUIRED) 9 def get_hello(request): 10 """Return information regarding the current instance.""" 11 settings = request.registry.settings 12 project_name = settings['project_name'] 13 project_version = settings['project_version'] 14 data = dict( 15 project_name=project_name, 16 project_version=project_version, 17 http_api_version=settings['http_api_version'], 18 project_docs=settings['project_docs'], 19 url=request.route_url(hello.name) 20 ) 21 22 eos = get_eos(request) 23 if eos: 24 data['eos'] = eos 25 26 data['settings'] = {} 27 public_settings = request.registry.public_settings 28 for setting in list(public_settings): 29 data['settings'][setting] = settings[setting] 30 31 # If current user is authenticated, add user info: 32 # (Note: this will call authenticated_userid() with multiauth+groupfinder) 33 if Authenticated in request.effective_principals: 34 data['user'] = request.get_user_info() 35 36 # Application can register and expose arbitrary capabilities. 37 data['capabilities'] = request.registry.api_capabilities 38 39 return data 40 41 42 def get_eos(request): 43 return request.registry.settings['eos'] 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/kinto/core/views/hello.py b/kinto/core/views/hello.py --- a/kinto/core/views/hello.py +++ b/kinto/core/views/hello.py @@ -32,6 +32,12 @@ # (Note: this will call authenticated_userid() with multiauth+groupfinder) if Authenticated in request.effective_principals: data['user'] = request.get_user_info() + principals = request.effective_principals + [request.prefixed_userid] + prefix, user_id = request.prefixed_userid.split(':', 1) + # Remove unprefixed user id on effective_principals to avoid conflicts. + if user_id in principals: + principals.remove(user_id) + data['user']['principals'] = principals # Application can register and expose arbitrary capabilities. data['capabilities'] = request.registry.api_capabilities
{"golden_diff": "diff --git a/kinto/core/views/hello.py b/kinto/core/views/hello.py\n--- a/kinto/core/views/hello.py\n+++ b/kinto/core/views/hello.py\n@@ -32,6 +32,12 @@\n # (Note: this will call authenticated_userid() with multiauth+groupfinder)\n if Authenticated in request.effective_principals:\n data['user'] = request.get_user_info()\n+ principals = request.effective_principals + [request.prefixed_userid]\n+ prefix, user_id = request.prefixed_userid.split(':', 1)\n+ # Remove unprefixed user id on effective_principals to avoid conflicts.\n+ if user_id in principals:\n+ principals.remove(user_id)\n+ data['user']['principals'] = principals\n \n # Application can register and expose arbitrary capabilities.\n data['capabilities'] = request.registry.api_capabilities\n", "issue": "Add user principals to hello view\nAlong `user` info, show the list of user principals (for groups notably)\n\n", "before_files": [{"content": "from pyramid.security import NO_PERMISSION_REQUIRED, Authenticated\n\nfrom kinto.core import Service\n\nhello = Service(name=\"hello\", path='/', description=\"Welcome\")\n\n\[email protected](permission=NO_PERMISSION_REQUIRED)\ndef get_hello(request):\n \"\"\"Return information regarding the current instance.\"\"\"\n settings = request.registry.settings\n project_name = settings['project_name']\n project_version = settings['project_version']\n data = dict(\n project_name=project_name,\n project_version=project_version,\n http_api_version=settings['http_api_version'],\n project_docs=settings['project_docs'],\n url=request.route_url(hello.name)\n )\n\n eos = get_eos(request)\n if eos:\n data['eos'] = eos\n\n data['settings'] = {}\n public_settings = request.registry.public_settings\n for setting in list(public_settings):\n data['settings'][setting] = settings[setting]\n\n # If current user is authenticated, add user info:\n # (Note: this will call authenticated_userid() with multiauth+groupfinder)\n if Authenticated in request.effective_principals:\n data['user'] = request.get_user_info()\n\n # Application can register and expose arbitrary capabilities.\n data['capabilities'] = request.registry.api_capabilities\n\n return data\n\n\ndef get_eos(request):\n return request.registry.settings['eos']\n", "path": "kinto/core/views/hello.py"}], "after_files": [{"content": "from pyramid.security import NO_PERMISSION_REQUIRED, Authenticated\n\nfrom kinto.core import Service\n\nhello = Service(name=\"hello\", path='/', description=\"Welcome\")\n\n\[email protected](permission=NO_PERMISSION_REQUIRED)\ndef get_hello(request):\n \"\"\"Return information regarding the current instance.\"\"\"\n settings = request.registry.settings\n project_name = settings['project_name']\n project_version = settings['project_version']\n data = dict(\n project_name=project_name,\n project_version=project_version,\n http_api_version=settings['http_api_version'],\n project_docs=settings['project_docs'],\n url=request.route_url(hello.name)\n )\n\n eos = get_eos(request)\n if eos:\n data['eos'] = eos\n\n data['settings'] = {}\n public_settings = request.registry.public_settings\n for setting in list(public_settings):\n data['settings'][setting] = settings[setting]\n\n # If current user is authenticated, add user info:\n # (Note: this will call authenticated_userid() with multiauth+groupfinder)\n if Authenticated in request.effective_principals:\n data['user'] = request.get_user_info()\n principals = request.effective_principals + [request.prefixed_userid]\n prefix, user_id = request.prefixed_userid.split(':', 1)\n # Remove unprefixed user id on effective_principals to avoid conflicts.\n if user_id in principals:\n principals.remove(user_id)\n data['user']['principals'] = principals\n\n # Application can register and expose arbitrary capabilities.\n data['capabilities'] = request.registry.api_capabilities\n\n return data\n\n\ndef get_eos(request):\n return request.registry.settings['eos']\n", "path": "kinto/core/views/hello.py"}]}
652
195
gh_patches_debug_16034
rasdani/github-patches
git_diff
dask__distributed-636
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Cannot serialize datetime64/timedelta64 numpy arrays ``` distributed.core - INFO - Unserializable Message: {'finalize-c29ed21fd1e79d8eb6b3ff89cf2ae354': <Serialize: ['2010-01-01T00:00:00.000000000' '2010-01-02T00:00:00.000000000' '2010-01-03T00:00:00.000000000']>} distributed.core - ERROR - cannot include dtype 'M' in a buffer Traceback (most recent call last): File "/Users/shoyer/dev/distributed/distributed/core.py", line 228, in write frames = protocol.dumps(msg) File "/Users/shoyer/dev/distributed/distributed/protocol/core.py", line 43, in dumps for key, value in data.items() File "/Users/shoyer/dev/distributed/distributed/protocol/core.py", line 44, in <dictcomp> if type(value) is Serialize} File "/Users/shoyer/dev/distributed/distributed/protocol/serialize.py", line 103, in serialize header, frames = serializers[name](x) File "/Users/shoyer/dev/distributed/distributed/protocol/numpy.py", line 58, in serialize_numpy_ndarray frames = [x.data] ValueError: cannot include dtype 'M' in a buffer ``` The buffer protocol fails on these (sigh). You can view as int64, but then you'll need to keep track of the original type (including time units) separately. This came up in some of my integration tests with xarray. --- 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/protocol/numpy.py` Content: ``` 1 from __future__ import print_function, division, absolute_import 2 3 import sys 4 5 import numpy as np 6 7 try: 8 import blosc 9 n = blosc.set_nthreads(2) 10 except ImportError: 11 blosc = False 12 13 from .utils import frame_split_size 14 from .serialize import register_serialization 15 from . import pickle 16 17 from ..utils import log_errors, ensure_bytes 18 19 20 def itemsize(dt): 21 """ Itemsize of dtype 22 23 Try to return the itemsize of the base element, return 8 as a fallback 24 """ 25 result = dt.base.itemsize 26 if result > 255: 27 result = 8 28 return result 29 30 31 def serialize_numpy_ndarray(x): 32 if x.dtype.hasobject: 33 header = {'pickle': True} 34 frames = [pickle.dumps(x)] 35 return header, frames 36 37 size = itemsize(x.dtype) 38 39 if x.dtype.kind == 'V': 40 dt = x.dtype.descr 41 else: 42 dt = x.dtype.str 43 44 x = np.ascontiguousarray(x) # np.frombuffer requires this 45 46 header = {'dtype': dt, 47 'strides': x.strides, 48 'shape': x.shape} 49 50 if blosc: 51 frames = frame_split_size([x.data]) 52 if sys.version_info.major == 2: 53 frames = [ensure_bytes(frame) for frame in frames] 54 frames = [blosc.compress(frame, typesize=size, 55 cname='lz4', clevel=5) for frame in frames] 56 header['compression'] = ['blosc'] * len(frames) 57 else: 58 frames = [x.data] 59 60 header['lengths'] = [x.nbytes] 61 62 return header, frames 63 64 65 def deserialize_numpy_ndarray(header, frames): 66 with log_errors(): 67 assert len(frames) == 1 68 69 if header.get('pickle'): 70 return pickle.loads(frames[0]) 71 72 dt = header['dtype'] 73 if isinstance(dt, tuple): 74 dt = list(dt) 75 dt = np.dtype(dt) 76 77 buffer = frames[0] 78 79 x = np.frombuffer(buffer, dt) 80 x = np.lib.stride_tricks.as_strided(x, header['shape'], header['strides']) 81 82 return x 83 84 85 register_serialization(np.ndarray, serialize_numpy_ndarray, deserialize_numpy_ndarray) 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/distributed/protocol/numpy.py b/distributed/protocol/numpy.py --- a/distributed/protocol/numpy.py +++ b/distributed/protocol/numpy.py @@ -47,15 +47,17 @@ 'strides': x.strides, 'shape': x.shape} + data = x.view('u1').data + if blosc: - frames = frame_split_size([x.data]) + frames = frame_split_size([data]) if sys.version_info.major == 2: frames = [ensure_bytes(frame) for frame in frames] frames = [blosc.compress(frame, typesize=size, cname='lz4', clevel=5) for frame in frames] header['compression'] = ['blosc'] * len(frames) else: - frames = [x.data] + frames = [data] header['lengths'] = [x.nbytes]
{"golden_diff": "diff --git a/distributed/protocol/numpy.py b/distributed/protocol/numpy.py\n--- a/distributed/protocol/numpy.py\n+++ b/distributed/protocol/numpy.py\n@@ -47,15 +47,17 @@\n 'strides': x.strides,\n 'shape': x.shape}\n \n+ data = x.view('u1').data\n+\n if blosc:\n- frames = frame_split_size([x.data])\n+ frames = frame_split_size([data])\n if sys.version_info.major == 2:\n frames = [ensure_bytes(frame) for frame in frames]\n frames = [blosc.compress(frame, typesize=size,\n cname='lz4', clevel=5) for frame in frames]\n header['compression'] = ['blosc'] * len(frames)\n else:\n- frames = [x.data]\n+ frames = [data]\n \n header['lengths'] = [x.nbytes]\n", "issue": "Cannot serialize datetime64/timedelta64 numpy arrays\n```\r\ndistributed.core - INFO - Unserializable Message: {'finalize-c29ed21fd1e79d8eb6b3ff89cf2ae354': <Serialize: ['2010-01-01T00:00:00.000000000' '2010-01-02T00:00:00.000000000'\r\n '2010-01-03T00:00:00.000000000']>}\r\ndistributed.core - ERROR - cannot include dtype 'M' in a buffer\r\nTraceback (most recent call last):\r\n File \"/Users/shoyer/dev/distributed/distributed/core.py\", line 228, in write\r\n frames = protocol.dumps(msg)\r\n File \"/Users/shoyer/dev/distributed/distributed/protocol/core.py\", line 43, in dumps\r\n for key, value in data.items()\r\n File \"/Users/shoyer/dev/distributed/distributed/protocol/core.py\", line 44, in <dictcomp>\r\n if type(value) is Serialize}\r\n File \"/Users/shoyer/dev/distributed/distributed/protocol/serialize.py\", line 103, in serialize\r\n header, frames = serializers[name](x)\r\n File \"/Users/shoyer/dev/distributed/distributed/protocol/numpy.py\", line 58, in serialize_numpy_ndarray\r\n frames = [x.data]\r\nValueError: cannot include dtype 'M' in a buffer\r\n```\r\n\r\nThe buffer protocol fails on these (sigh). You can view as int64, but then you'll need to keep track of the original type (including time units) separately.\r\n\r\nThis came up in some of my integration tests with xarray.\n", "before_files": [{"content": "from __future__ import print_function, division, absolute_import\n\nimport sys\n\nimport numpy as np\n\ntry:\n import blosc\n n = blosc.set_nthreads(2)\nexcept ImportError:\n blosc = False\n\nfrom .utils import frame_split_size\nfrom .serialize import register_serialization\nfrom . import pickle\n\nfrom ..utils import log_errors, ensure_bytes\n\n\ndef itemsize(dt):\n \"\"\" Itemsize of dtype\n\n Try to return the itemsize of the base element, return 8 as a fallback\n \"\"\"\n result = dt.base.itemsize\n if result > 255:\n result = 8\n return result\n\n\ndef serialize_numpy_ndarray(x):\n if x.dtype.hasobject:\n header = {'pickle': True}\n frames = [pickle.dumps(x)]\n return header, frames\n\n size = itemsize(x.dtype)\n\n if x.dtype.kind == 'V':\n dt = x.dtype.descr\n else:\n dt = x.dtype.str\n\n x = np.ascontiguousarray(x) # np.frombuffer requires this\n\n header = {'dtype': dt,\n 'strides': x.strides,\n 'shape': x.shape}\n\n if blosc:\n frames = frame_split_size([x.data])\n if sys.version_info.major == 2:\n frames = [ensure_bytes(frame) for frame in frames]\n frames = [blosc.compress(frame, typesize=size,\n cname='lz4', clevel=5) for frame in frames]\n header['compression'] = ['blosc'] * len(frames)\n else:\n frames = [x.data]\n\n header['lengths'] = [x.nbytes]\n\n return header, frames\n\n\ndef deserialize_numpy_ndarray(header, frames):\n with log_errors():\n assert len(frames) == 1\n\n if header.get('pickle'):\n return pickle.loads(frames[0])\n\n dt = header['dtype']\n if isinstance(dt, tuple):\n dt = list(dt)\n dt = np.dtype(dt)\n\n buffer = frames[0]\n\n x = np.frombuffer(buffer, dt)\n x = np.lib.stride_tricks.as_strided(x, header['shape'], header['strides'])\n\n return x\n\n\nregister_serialization(np.ndarray, serialize_numpy_ndarray, deserialize_numpy_ndarray)\n", "path": "distributed/protocol/numpy.py"}], "after_files": [{"content": "from __future__ import print_function, division, absolute_import\n\nimport sys\n\nimport numpy as np\n\ntry:\n import blosc\n n = blosc.set_nthreads(2)\nexcept ImportError:\n blosc = False\n\nfrom .utils import frame_split_size\nfrom .serialize import register_serialization\nfrom . import pickle\n\nfrom ..utils import log_errors, ensure_bytes\n\n\ndef itemsize(dt):\n \"\"\" Itemsize of dtype\n\n Try to return the itemsize of the base element, return 8 as a fallback\n \"\"\"\n result = dt.base.itemsize\n if result > 255:\n result = 8\n return result\n\n\ndef serialize_numpy_ndarray(x):\n if x.dtype.hasobject:\n header = {'pickle': True}\n frames = [pickle.dumps(x)]\n return header, frames\n\n size = itemsize(x.dtype)\n\n if x.dtype.kind == 'V':\n dt = x.dtype.descr\n else:\n dt = x.dtype.str\n\n x = np.ascontiguousarray(x) # np.frombuffer requires this\n\n header = {'dtype': dt,\n 'strides': x.strides,\n 'shape': x.shape}\n\n data = x.view('u1').data\n\n if blosc:\n frames = frame_split_size([data])\n if sys.version_info.major == 2:\n frames = [ensure_bytes(frame) for frame in frames]\n frames = [blosc.compress(frame, typesize=size,\n cname='lz4', clevel=5) for frame in frames]\n header['compression'] = ['blosc'] * len(frames)\n else:\n frames = [data]\n\n header['lengths'] = [x.nbytes]\n\n return header, frames\n\n\ndef deserialize_numpy_ndarray(header, frames):\n with log_errors():\n assert len(frames) == 1\n\n if header.get('pickle'):\n return pickle.loads(frames[0])\n\n dt = header['dtype']\n if isinstance(dt, tuple):\n dt = list(dt)\n dt = np.dtype(dt)\n\n buffer = frames[0]\n\n x = np.frombuffer(buffer, dt)\n x = np.lib.stride_tricks.as_strided(x, header['shape'], header['strides'])\n\n return x\n\n\nregister_serialization(np.ndarray, serialize_numpy_ndarray, deserialize_numpy_ndarray)\n", "path": "distributed/protocol/numpy.py"}]}
1,347
210
gh_patches_debug_14829
rasdani/github-patches
git_diff
mozilla__pontoon-2330
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [notifications] Notify project Translators when suggestions are submitted *This issue was created automatically by a [script](https://github.com/mathjazz/bugzilla2github/).* ## [Bug 1398861](https://bugzilla.mozilla.org/show_bug.cgi?id=1398861) Bug Reporter: @mathjazz CC: @MikkCZ, [email protected] See also: https://bugzilla.mozilla.org/show_bug.cgi?id=1625102 We should probably do that periodically and aggregate notifications. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pontoon/projects/management/commands/send_suggestion_notifications.py` Content: ``` 1 import calendar 2 3 from collections import defaultdict 4 from datetime import timedelta 5 from functools import cached_property 6 7 from django.conf import settings 8 from django.contrib.auth.models import User 9 from django.core.management.base import BaseCommand, CommandError 10 from django.db.models import Prefetch, Q 11 from django.template.loader import render_to_string 12 from django.utils import timezone 13 from notifications.signals import notify 14 15 from pontoon.base.models import Comment, Locale, ProjectLocale, Translation 16 17 18 class Command(BaseCommand): 19 help = "Notify contributors about newly added unreviewed suggestions" 20 21 def add_arguments(self, parser): 22 parser.add_argument( 23 "--force", 24 action="store_true", 25 dest="force", 26 default=False, 27 help="Force run command, regardless of what day of the week it is", 28 ) 29 30 @cached_property 31 def locale_reviewers(self): 32 locales = Locale.objects.prefetch_related( 33 Prefetch("managers_group__user_set", to_attr="fetched_managers"), 34 Prefetch("translators_group__user_set", to_attr="fetched_translators"), 35 ) 36 37 locale_reviewers = {} 38 39 for locale in locales: 40 managers = locale.managers_group.fetched_managers 41 translators = locale.translators_group.fetched_translators 42 locale_reviewers[locale] = managers + translators 43 44 return locale_reviewers 45 46 def extract_notifications_data(self, data, suggestion): 47 locale = suggestion.locale 48 entity = suggestion.entity 49 project = entity.resource.project 50 project_locale = ProjectLocale.objects.get(project=project, locale=locale) 51 52 translations = Translation.objects.filter(entity=entity, locale=locale) 53 recipients = set() 54 55 # Users with permission to review suggestions 56 recipients = recipients.union(self.locale_reviewers[locale]) 57 58 # Authors of previous translations of the same string 59 recipients = recipients.union(User.objects.filter(translation__in=translations)) 60 61 # Authors of comments of previous translations 62 translations_comments = Comment.objects.filter(translation__in=translations) 63 recipients = recipients.union( 64 User.objects.filter(comment__in=translations_comments) 65 ) 66 67 # Authors of team comments of the same string 68 team_comments = Comment.objects.filter(entity=entity, locale=locale) 69 recipients = recipients.union(User.objects.filter(comment__in=team_comments)) 70 71 for recipient in recipients: 72 data[recipient].add(project_locale) 73 74 def get_suggestions(self): 75 start = timezone.now() - timedelta(days=7) 76 77 return Translation.objects.filter( 78 approved=False, rejected=False, fuzzy=False 79 ).filter( 80 Q(date__gt=start) 81 | Q(unapproved_date__gt=start) 82 | Q(unrejected_date__gt=start) 83 ) 84 85 def handle(self, *args, **options): 86 """ 87 This command sends notifications about newly created unreviewed suggestions that 88 were submitted, unapproved or unrejected in the last 7 days. Recipients of 89 notifications are users with permission to review them, as well as authors of 90 previous translations or comments of the same string. 91 92 The command is designed to run on a weekly basis. 93 """ 94 self.stdout.write("Sending suggestion notifications.") 95 96 today = calendar.day_name[timezone.datetime.today().weekday()] 97 day = calendar.day_name[settings.SUGGESTION_NOTIFICATIONS_DAY] 98 99 if today != day and not options["force"]: 100 raise CommandError(f"Skipping. Command runs every {day}. Today is {today}.") 101 102 suggestions = self.get_suggestions() 103 104 data = defaultdict(set) 105 106 for suggestion in suggestions: 107 self.extract_notifications_data(data, suggestion) 108 109 for recipient, project_locales in data.items(): 110 verb = render_to_string( 111 "projects/suggestion_notification.jinja", 112 {"project_locales": project_locales}, 113 ) 114 115 notify.send(recipient, recipient=recipient, verb=verb) 116 117 self.stdout.write("Suggestion notifications sent.") 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/pontoon/projects/management/commands/send_suggestion_notifications.py b/pontoon/projects/management/commands/send_suggestion_notifications.py --- a/pontoon/projects/management/commands/send_suggestion_notifications.py +++ b/pontoon/projects/management/commands/send_suggestion_notifications.py @@ -107,11 +107,13 @@ self.extract_notifications_data(data, suggestion) for recipient, project_locales in data.items(): - verb = render_to_string( + description = render_to_string( "projects/suggestion_notification.jinja", {"project_locales": project_locales}, ) - notify.send(recipient, recipient=recipient, verb=verb) + notify.send( + recipient, recipient=recipient, verb="", description=description + ) - self.stdout.write("Suggestion notifications sent.") + self.stdout.write(f"Suggestion notifications sent to {len(data)} users.")
{"golden_diff": "diff --git a/pontoon/projects/management/commands/send_suggestion_notifications.py b/pontoon/projects/management/commands/send_suggestion_notifications.py\n--- a/pontoon/projects/management/commands/send_suggestion_notifications.py\n+++ b/pontoon/projects/management/commands/send_suggestion_notifications.py\n@@ -107,11 +107,13 @@\n self.extract_notifications_data(data, suggestion)\n \n for recipient, project_locales in data.items():\n- verb = render_to_string(\n+ description = render_to_string(\n \"projects/suggestion_notification.jinja\",\n {\"project_locales\": project_locales},\n )\n \n- notify.send(recipient, recipient=recipient, verb=verb)\n+ notify.send(\n+ recipient, recipient=recipient, verb=\"\", description=description\n+ )\n \n- self.stdout.write(\"Suggestion notifications sent.\")\n+ self.stdout.write(f\"Suggestion notifications sent to {len(data)} users.\")\n", "issue": "[notifications] Notify project Translators when suggestions are submitted\n*This issue was created automatically by a [script](https://github.com/mathjazz/bugzilla2github/).*\n## [Bug 1398861](https://bugzilla.mozilla.org/show_bug.cgi?id=1398861)\nBug Reporter: @mathjazz\nCC: @MikkCZ, [email protected]\nSee also: https://bugzilla.mozilla.org/show_bug.cgi?id=1625102\n\nWe should probably do that periodically and aggregate notifications.\n", "before_files": [{"content": "import calendar\n\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom functools import cached_property\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Prefetch, Q\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom notifications.signals import notify\n\nfrom pontoon.base.models import Comment, Locale, ProjectLocale, Translation\n\n\nclass Command(BaseCommand):\n help = \"Notify contributors about newly added unreviewed suggestions\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--force\",\n action=\"store_true\",\n dest=\"force\",\n default=False,\n help=\"Force run command, regardless of what day of the week it is\",\n )\n\n @cached_property\n def locale_reviewers(self):\n locales = Locale.objects.prefetch_related(\n Prefetch(\"managers_group__user_set\", to_attr=\"fetched_managers\"),\n Prefetch(\"translators_group__user_set\", to_attr=\"fetched_translators\"),\n )\n\n locale_reviewers = {}\n\n for locale in locales:\n managers = locale.managers_group.fetched_managers\n translators = locale.translators_group.fetched_translators\n locale_reviewers[locale] = managers + translators\n\n return locale_reviewers\n\n def extract_notifications_data(self, data, suggestion):\n locale = suggestion.locale\n entity = suggestion.entity\n project = entity.resource.project\n project_locale = ProjectLocale.objects.get(project=project, locale=locale)\n\n translations = Translation.objects.filter(entity=entity, locale=locale)\n recipients = set()\n\n # Users with permission to review suggestions\n recipients = recipients.union(self.locale_reviewers[locale])\n\n # Authors of previous translations of the same string\n recipients = recipients.union(User.objects.filter(translation__in=translations))\n\n # Authors of comments of previous translations\n translations_comments = Comment.objects.filter(translation__in=translations)\n recipients = recipients.union(\n User.objects.filter(comment__in=translations_comments)\n )\n\n # Authors of team comments of the same string\n team_comments = Comment.objects.filter(entity=entity, locale=locale)\n recipients = recipients.union(User.objects.filter(comment__in=team_comments))\n\n for recipient in recipients:\n data[recipient].add(project_locale)\n\n def get_suggestions(self):\n start = timezone.now() - timedelta(days=7)\n\n return Translation.objects.filter(\n approved=False, rejected=False, fuzzy=False\n ).filter(\n Q(date__gt=start)\n | Q(unapproved_date__gt=start)\n | Q(unrejected_date__gt=start)\n )\n\n def handle(self, *args, **options):\n \"\"\"\n This command sends notifications about newly created unreviewed suggestions that\n were submitted, unapproved or unrejected in the last 7 days. Recipients of\n notifications are users with permission to review them, as well as authors of\n previous translations or comments of the same string.\n\n The command is designed to run on a weekly basis.\n \"\"\"\n self.stdout.write(\"Sending suggestion notifications.\")\n\n today = calendar.day_name[timezone.datetime.today().weekday()]\n day = calendar.day_name[settings.SUGGESTION_NOTIFICATIONS_DAY]\n\n if today != day and not options[\"force\"]:\n raise CommandError(f\"Skipping. Command runs every {day}. Today is {today}.\")\n\n suggestions = self.get_suggestions()\n\n data = defaultdict(set)\n\n for suggestion in suggestions:\n self.extract_notifications_data(data, suggestion)\n\n for recipient, project_locales in data.items():\n verb = render_to_string(\n \"projects/suggestion_notification.jinja\",\n {\"project_locales\": project_locales},\n )\n\n notify.send(recipient, recipient=recipient, verb=verb)\n\n self.stdout.write(\"Suggestion notifications sent.\")\n", "path": "pontoon/projects/management/commands/send_suggestion_notifications.py"}], "after_files": [{"content": "import calendar\n\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom functools import cached_property\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Prefetch, Q\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom notifications.signals import notify\n\nfrom pontoon.base.models import Comment, Locale, ProjectLocale, Translation\n\n\nclass Command(BaseCommand):\n help = \"Notify contributors about newly added unreviewed suggestions\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--force\",\n action=\"store_true\",\n dest=\"force\",\n default=False,\n help=\"Force run command, regardless of what day of the week it is\",\n )\n\n @cached_property\n def locale_reviewers(self):\n locales = Locale.objects.prefetch_related(\n Prefetch(\"managers_group__user_set\", to_attr=\"fetched_managers\"),\n Prefetch(\"translators_group__user_set\", to_attr=\"fetched_translators\"),\n )\n\n locale_reviewers = {}\n\n for locale in locales:\n managers = locale.managers_group.fetched_managers\n translators = locale.translators_group.fetched_translators\n locale_reviewers[locale] = managers + translators\n\n return locale_reviewers\n\n def extract_notifications_data(self, data, suggestion):\n locale = suggestion.locale\n entity = suggestion.entity\n project = entity.resource.project\n project_locale = ProjectLocale.objects.get(project=project, locale=locale)\n\n translations = Translation.objects.filter(entity=entity, locale=locale)\n recipients = set()\n\n # Users with permission to review suggestions\n recipients = recipients.union(self.locale_reviewers[locale])\n\n # Authors of previous translations of the same string\n recipients = recipients.union(User.objects.filter(translation__in=translations))\n\n # Authors of comments of previous translations\n translations_comments = Comment.objects.filter(translation__in=translations)\n recipients = recipients.union(\n User.objects.filter(comment__in=translations_comments)\n )\n\n # Authors of team comments of the same string\n team_comments = Comment.objects.filter(entity=entity, locale=locale)\n recipients = recipients.union(User.objects.filter(comment__in=team_comments))\n\n for recipient in recipients:\n data[recipient].add(project_locale)\n\n def get_suggestions(self):\n start = timezone.now() - timedelta(days=7)\n\n return Translation.objects.filter(\n approved=False, rejected=False, fuzzy=False\n ).filter(\n Q(date__gt=start)\n | Q(unapproved_date__gt=start)\n | Q(unrejected_date__gt=start)\n )\n\n def handle(self, *args, **options):\n \"\"\"\n This command sends notifications about newly created unreviewed suggestions that\n were submitted, unapproved or unrejected in the last 7 days. Recipients of\n notifications are users with permission to review them, as well as authors of\n previous translations or comments of the same string.\n\n The command is designed to run on a weekly basis.\n \"\"\"\n self.stdout.write(\"Sending suggestion notifications.\")\n\n today = calendar.day_name[timezone.datetime.today().weekday()]\n day = calendar.day_name[settings.SUGGESTION_NOTIFICATIONS_DAY]\n\n if today != day and not options[\"force\"]:\n raise CommandError(f\"Skipping. Command runs every {day}. Today is {today}.\")\n\n suggestions = self.get_suggestions()\n\n data = defaultdict(set)\n\n for suggestion in suggestions:\n self.extract_notifications_data(data, suggestion)\n\n for recipient, project_locales in data.items():\n description = render_to_string(\n \"projects/suggestion_notification.jinja\",\n {\"project_locales\": project_locales},\n )\n\n notify.send(\n recipient, recipient=recipient, verb=\"\", description=description\n )\n\n self.stdout.write(f\"Suggestion notifications sent to {len(data)} users.\")\n", "path": "pontoon/projects/management/commands/send_suggestion_notifications.py"}]}
1,476
205
gh_patches_debug_9202
rasdani/github-patches
git_diff
speechbrain__speechbrain-2494
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- PyPI install incorrectly ships a `tests` package ### Describe the bug If you check the `.whl` file of SB 1.0, for instance, you will notice that there is an empty `tests/` (with only the `__init__.py`). This is not a huge deal, but it has the unintended consequence that the user now has a `tests` package at their root level. ### Expected behaviour That package should not exist on normal or editable installs. ### To Reproduce ```python import tests ``` ```bash $ cat env/lib/python3.xx/speechbrain-xxx.dist-info/top_level.txt speechbrain tests ``` ### Environment Details _No response_ ### Relevant Log Output _No response_ ### Additional Context This is probably due to the way packages are specified in the `setup.py`. Does not seem like it would be linked to #2484 but it's worth investigating anyway. --- 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 import os 3 import sys 4 import site 5 import setuptools 6 from distutils.core import setup 7 8 9 # Editable install in user site directory can be allowed with this hack: 10 # https://github.com/pypa/pip/issues/7953. 11 site.ENABLE_USER_SITE = "--user" in sys.argv[1:] 12 13 with open("README.md") as f: 14 long_description = f.read() 15 16 with open(os.path.join("speechbrain", "version.txt")) as f: 17 version = f.read().strip() 18 19 setup( 20 name="speechbrain", 21 version=version, 22 description="All-in-one speech toolkit in pure Python and Pytorch", 23 long_description=long_description, 24 long_description_content_type="text/markdown", 25 author="Mirco Ravanelli & Others", 26 author_email="[email protected]", 27 classifiers=[ 28 "Programming Language :: Python :: 3", 29 "License :: OSI Approved :: Apache Software License", 30 ], 31 packages=setuptools.find_packages(), 32 package_data={"speechbrain": ["version.txt", "log-config.yaml"]}, 33 install_requires=[ 34 "hyperpyyaml", 35 "joblib", 36 "numpy", 37 "packaging", 38 "scipy", 39 "sentencepiece", 40 "torch>=1.9", 41 "torchaudio", 42 "tqdm", 43 "huggingface_hub", 44 ], 45 python_requires=">=3.8", 46 url="https://speechbrain.github.io/", 47 ) 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/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -28,7 +28,9 @@ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", ], - packages=setuptools.find_packages(), + # we don't want to ship the tests package. for future proofing, also + # exclude any tests subpackage (if we ever define __init__.py there) + packages=setuptools.find_packages(exclude=["tests", "tests.*"]), package_data={"speechbrain": ["version.txt", "log-config.yaml"]}, install_requires=[ "hyperpyyaml",
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -28,7 +28,9 @@\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n- packages=setuptools.find_packages(),\n+ # we don't want to ship the tests package. for future proofing, also\n+ # exclude any tests subpackage (if we ever define __init__.py there)\n+ packages=setuptools.find_packages(exclude=[\"tests\", \"tests.*\"]),\n package_data={\"speechbrain\": [\"version.txt\", \"log-config.yaml\"]},\n install_requires=[\n \"hyperpyyaml\",\n", "issue": "PyPI install incorrectly ships a `tests` package\n### Describe the bug\r\n\r\nIf you check the `.whl` file of SB 1.0, for instance, you will notice that there is an empty `tests/` (with only the `__init__.py`). This is not a huge deal, but it has the unintended consequence that the user now has a `tests` package at their root level.\r\n\r\n### Expected behaviour\r\n\r\nThat package should not exist on normal or editable installs.\r\n\r\n### To Reproduce\r\n\r\n```python\r\nimport tests\r\n```\r\n\r\n```bash\r\n$ cat env/lib/python3.xx/speechbrain-xxx.dist-info/top_level.txt \r\nspeechbrain\r\ntests\r\n```\r\n\r\n### Environment Details\r\n\r\n_No response_\r\n\r\n### Relevant Log Output\r\n\r\n_No response_\r\n\r\n### Additional Context\r\n\r\nThis is probably due to the way packages are specified in the `setup.py`.\r\n\r\nDoes not seem like it would be linked to #2484 but it's worth investigating anyway.\n", "before_files": [{"content": "#!/usr/bin/env python3\nimport os\nimport sys\nimport site\nimport setuptools\nfrom distutils.core import setup\n\n\n# Editable install in user site directory can be allowed with this hack:\n# https://github.com/pypa/pip/issues/7953.\nsite.ENABLE_USER_SITE = \"--user\" in sys.argv[1:]\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\nwith open(os.path.join(\"speechbrain\", \"version.txt\")) as f:\n version = f.read().strip()\n\nsetup(\n name=\"speechbrain\",\n version=version,\n description=\"All-in-one speech toolkit in pure Python and Pytorch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Mirco Ravanelli & Others\",\n author_email=\"[email protected]\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n packages=setuptools.find_packages(),\n package_data={\"speechbrain\": [\"version.txt\", \"log-config.yaml\"]},\n install_requires=[\n \"hyperpyyaml\",\n \"joblib\",\n \"numpy\",\n \"packaging\",\n \"scipy\",\n \"sentencepiece\",\n \"torch>=1.9\",\n \"torchaudio\",\n \"tqdm\",\n \"huggingface_hub\",\n ],\n python_requires=\">=3.8\",\n url=\"https://speechbrain.github.io/\",\n)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python3\nimport os\nimport sys\nimport site\nimport setuptools\nfrom distutils.core import setup\n\n\n# Editable install in user site directory can be allowed with this hack:\n# https://github.com/pypa/pip/issues/7953.\nsite.ENABLE_USER_SITE = \"--user\" in sys.argv[1:]\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\nwith open(os.path.join(\"speechbrain\", \"version.txt\")) as f:\n version = f.read().strip()\n\nsetup(\n name=\"speechbrain\",\n version=version,\n description=\"All-in-one speech toolkit in pure Python and Pytorch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Mirco Ravanelli & Others\",\n author_email=\"[email protected]\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n # we don't want to ship the tests package. for future proofing, also\n # exclude any tests subpackage (if we ever define __init__.py there)\n packages=setuptools.find_packages(exclude=[\"tests\", \"tests.*\"]),\n package_data={\"speechbrain\": [\"version.txt\", \"log-config.yaml\"]},\n install_requires=[\n \"hyperpyyaml\",\n \"joblib\",\n \"numpy\",\n \"packaging\",\n \"scipy\",\n \"sentencepiece\",\n \"torch>=1.9\",\n \"torchaudio\",\n \"tqdm\",\n \"huggingface_hub\",\n ],\n python_requires=\">=3.8\",\n url=\"https://speechbrain.github.io/\",\n)\n", "path": "setup.py"}]}
858
145
gh_patches_debug_12383
rasdani/github-patches
git_diff
Lightning-AI__pytorch-lightning-1523
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Performance drop when activating gradient clipping Hello all, I experienced a substantial drop in computation time when activating gradient clipping (by passing a non-zero value to the keyword argument `gradient_clip_val` when initializing the Trainer). I noticed that in the current implementation of the `clipping_gradient` method in pytorch-lightning/trainer/training_tricks.py redundant computations are made by first computing the 2-norm and second squaring this result, which could be shortened by computing the sum of squares directly. This saves one square root and squaring operation per parameter set. Best, Jonas ### Environment ``` cuda: GPU: available: False version: None packages: numpy: 1.18.1 pyTorch_debug: False pyTorch_version: 1.4.0 pytorch-lightning: 0.7.4-dev tensorboard: 2.2.1 tqdm: 4.45.0 system: OS: Darwin architecture: 64bit processor: i386 python: 3.8.2 version: Darwin Kernel Version 19.4.0: Wed Mar 4 22:28:40 PST 2020; root:xnu-6153.101.6~15/RELEASE_X86_64 ``` ### Additional context I trained a relatively small (two-layered) MLP on MNIST; perhaps this performance drop does not become that apparent when training on larger network architectures. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `pytorch_lightning/trainer/training_tricks.py` Content: ``` 1 import math 2 import sys 3 from abc import ABC, abstractmethod 4 5 import torch 6 from torch import Tensor 7 8 from pytorch_lightning import _logger as log 9 from pytorch_lightning.callbacks import GradientAccumulationScheduler 10 11 EPSILON = 1e-6 12 EPSILON_FP16 = 1e-5 13 14 15 class TrainerTrainingTricksMixin(ABC): 16 17 # this is just a summary on variables used in this abstract class, 18 # the proper values/initialisation should be done in child class 19 gradient_clip_val: ... 20 precision: ... 21 22 @abstractmethod 23 def get_model(self): 24 """Warning: this is just empty shell for code implemented in other class.""" 25 26 def clip_gradients(self): 27 # this code is a modification of torch.nn.utils.clip_grad_norm_ 28 # with TPU support based on https://github.com/pytorch/xla/blob/master/TROUBLESHOOTING.md 29 if self.gradient_clip_val > 0: 30 model = self.get_model() 31 parameters = model.parameters() 32 max_norm = float(self.gradient_clip_val) 33 norm_type = float(2.0) 34 if isinstance(parameters, torch.Tensor): 35 parameters = [parameters] 36 parameters = list(filter(lambda p: p.grad is not None, parameters)) 37 if norm_type == math.inf: 38 total_norm = max(p.grad.data.abs().max() for p in parameters) 39 else: 40 device = parameters[0].device 41 total_norm = torch.zeros([], device=device if parameters else None) 42 for p in parameters: 43 param_norm = p.grad.data.norm(norm_type) ** norm_type 44 total_norm.add_(param_norm) 45 total_norm = (total_norm ** (1. / norm_type)) 46 eps = EPSILON_FP16 if self.precision == 16 else EPSILON 47 clip_coef = torch.tensor(max_norm, device=device) / (total_norm + eps) 48 for p in parameters: 49 p.grad.data.mul_(torch.where(clip_coef < 1, clip_coef, torch.tensor(1., device=device))) 50 51 def print_nan_gradients(self) -> None: 52 model = self.get_model() 53 for param in model.parameters(): 54 if (param.grad is not None) and torch.isnan(param.grad.float()).any(): 55 log.info(param, param.grad) 56 57 def detect_nan_tensors(self, loss: Tensor) -> None: 58 model = self.get_model() 59 60 # check if loss is nan 61 if not torch.isfinite(loss).all(): 62 raise ValueError( 63 'The loss returned in `training_step` is nan or inf.' 64 ) 65 # check if a network weight is nan 66 for name, param in model.named_parameters(): 67 if not torch.isfinite(param).all(): 68 self.print_nan_gradients() 69 raise ValueError( 70 f'Detected nan and/or inf values in `{name}`.' 71 ' Check your forward pass for numerically unstable operations.' 72 ) 73 74 def configure_accumulated_gradients(self, accumulate_grad_batches): 75 if isinstance(accumulate_grad_batches, dict): 76 self.accumulation_scheduler = GradientAccumulationScheduler(accumulate_grad_batches) 77 elif isinstance(accumulate_grad_batches, int): 78 schedule = {1: accumulate_grad_batches} 79 self.accumulation_scheduler = GradientAccumulationScheduler(schedule) 80 else: 81 raise TypeError("Gradient accumulation supports only int and dict types") 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/pytorch_lightning/trainer/training_tricks.py b/pytorch_lightning/trainer/training_tricks.py --- a/pytorch_lightning/trainer/training_tricks.py +++ b/pytorch_lightning/trainer/training_tricks.py @@ -40,7 +40,7 @@ device = parameters[0].device total_norm = torch.zeros([], device=device if parameters else None) for p in parameters: - param_norm = p.grad.data.norm(norm_type) ** norm_type + param_norm = p.grad.data.pow(norm_type).sum() total_norm.add_(param_norm) total_norm = (total_norm ** (1. / norm_type)) eps = EPSILON_FP16 if self.precision == 16 else EPSILON
{"golden_diff": "diff --git a/pytorch_lightning/trainer/training_tricks.py b/pytorch_lightning/trainer/training_tricks.py\n--- a/pytorch_lightning/trainer/training_tricks.py\n+++ b/pytorch_lightning/trainer/training_tricks.py\n@@ -40,7 +40,7 @@\n device = parameters[0].device\n total_norm = torch.zeros([], device=device if parameters else None)\n for p in parameters:\n- param_norm = p.grad.data.norm(norm_type) ** norm_type\n+ param_norm = p.grad.data.pow(norm_type).sum()\n total_norm.add_(param_norm)\n total_norm = (total_norm ** (1. / norm_type))\n eps = EPSILON_FP16 if self.precision == 16 else EPSILON\n", "issue": "Performance drop when activating gradient clipping\nHello all,\r\n\r\nI experienced a substantial drop in computation time when activating gradient clipping (by passing a non-zero value to the keyword argument `gradient_clip_val` when initializing the Trainer).\r\n\r\nI noticed that in the current implementation of the `clipping_gradient` method in pytorch-lightning/trainer/training_tricks.py redundant computations are made by first computing the 2-norm and second squaring this result, which could be shortened by computing the sum of squares directly. This saves one square root and squaring operation per parameter set.\r\n\r\nBest,\r\nJonas\r\n\r\n### Environment\r\n\r\n```\r\ncuda:\r\n\tGPU:\r\n\tavailable: False\r\n\tversion: None\r\npackages:\r\n\tnumpy: 1.18.1\r\n\tpyTorch_debug: False\r\n\tpyTorch_version: 1.4.0\r\n\tpytorch-lightning: 0.7.4-dev\r\n\ttensorboard: 2.2.1\r\n\ttqdm: 4.45.0\r\nsystem:\r\n\tOS: Darwin\r\n\tarchitecture:\r\n\t\t64bit\r\n\t\t\r\n\tprocessor: i386\r\n\tpython: 3.8.2\r\n\tversion: Darwin Kernel Version 19.4.0: Wed Mar 4 22:28:40 PST 2020; root:xnu-6153.101.6~15/RELEASE_X86_64\r\n```\r\n\r\n### Additional context\r\n\r\nI trained a relatively small (two-layered) MLP on MNIST; perhaps this performance drop does not become that apparent when training on larger network architectures.\n", "before_files": [{"content": "import math\nimport sys\nfrom abc import ABC, abstractmethod\n\nimport torch\nfrom torch import Tensor\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.callbacks import GradientAccumulationScheduler\n\nEPSILON = 1e-6\nEPSILON_FP16 = 1e-5\n\n\nclass TrainerTrainingTricksMixin(ABC):\n\n # this is just a summary on variables used in this abstract class,\n # the proper values/initialisation should be done in child class\n gradient_clip_val: ...\n precision: ...\n\n @abstractmethod\n def get_model(self):\n \"\"\"Warning: this is just empty shell for code implemented in other class.\"\"\"\n\n def clip_gradients(self):\n # this code is a modification of torch.nn.utils.clip_grad_norm_\n # with TPU support based on https://github.com/pytorch/xla/blob/master/TROUBLESHOOTING.md\n if self.gradient_clip_val > 0:\n model = self.get_model()\n parameters = model.parameters()\n max_norm = float(self.gradient_clip_val)\n norm_type = float(2.0)\n if isinstance(parameters, torch.Tensor):\n parameters = [parameters]\n parameters = list(filter(lambda p: p.grad is not None, parameters))\n if norm_type == math.inf:\n total_norm = max(p.grad.data.abs().max() for p in parameters)\n else:\n device = parameters[0].device\n total_norm = torch.zeros([], device=device if parameters else None)\n for p in parameters:\n param_norm = p.grad.data.norm(norm_type) ** norm_type\n total_norm.add_(param_norm)\n total_norm = (total_norm ** (1. / norm_type))\n eps = EPSILON_FP16 if self.precision == 16 else EPSILON\n clip_coef = torch.tensor(max_norm, device=device) / (total_norm + eps)\n for p in parameters:\n p.grad.data.mul_(torch.where(clip_coef < 1, clip_coef, torch.tensor(1., device=device)))\n\n def print_nan_gradients(self) -> None:\n model = self.get_model()\n for param in model.parameters():\n if (param.grad is not None) and torch.isnan(param.grad.float()).any():\n log.info(param, param.grad)\n\n def detect_nan_tensors(self, loss: Tensor) -> None:\n model = self.get_model()\n\n # check if loss is nan\n if not torch.isfinite(loss).all():\n raise ValueError(\n 'The loss returned in `training_step` is nan or inf.'\n )\n # check if a network weight is nan\n for name, param in model.named_parameters():\n if not torch.isfinite(param).all():\n self.print_nan_gradients()\n raise ValueError(\n f'Detected nan and/or inf values in `{name}`.'\n ' Check your forward pass for numerically unstable operations.'\n )\n\n def configure_accumulated_gradients(self, accumulate_grad_batches):\n if isinstance(accumulate_grad_batches, dict):\n self.accumulation_scheduler = GradientAccumulationScheduler(accumulate_grad_batches)\n elif isinstance(accumulate_grad_batches, int):\n schedule = {1: accumulate_grad_batches}\n self.accumulation_scheduler = GradientAccumulationScheduler(schedule)\n else:\n raise TypeError(\"Gradient accumulation supports only int and dict types\")\n", "path": "pytorch_lightning/trainer/training_tricks.py"}], "after_files": [{"content": "import math\nimport sys\nfrom abc import ABC, abstractmethod\n\nimport torch\nfrom torch import Tensor\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.callbacks import GradientAccumulationScheduler\n\nEPSILON = 1e-6\nEPSILON_FP16 = 1e-5\n\n\nclass TrainerTrainingTricksMixin(ABC):\n\n # this is just a summary on variables used in this abstract class,\n # the proper values/initialisation should be done in child class\n gradient_clip_val: ...\n precision: ...\n\n @abstractmethod\n def get_model(self):\n \"\"\"Warning: this is just empty shell for code implemented in other class.\"\"\"\n\n def clip_gradients(self):\n # this code is a modification of torch.nn.utils.clip_grad_norm_\n # with TPU support based on https://github.com/pytorch/xla/blob/master/TROUBLESHOOTING.md\n if self.gradient_clip_val > 0:\n model = self.get_model()\n parameters = model.parameters()\n max_norm = float(self.gradient_clip_val)\n norm_type = float(2.0)\n if isinstance(parameters, torch.Tensor):\n parameters = [parameters]\n parameters = list(filter(lambda p: p.grad is not None, parameters))\n if norm_type == math.inf:\n total_norm = max(p.grad.data.abs().max() for p in parameters)\n else:\n device = parameters[0].device\n total_norm = torch.zeros([], device=device if parameters else None)\n for p in parameters:\n param_norm = p.grad.data.pow(norm_type).sum()\n total_norm.add_(param_norm)\n total_norm = (total_norm ** (1. / norm_type))\n eps = EPSILON_FP16 if self.precision == 16 else EPSILON\n clip_coef = torch.tensor(max_norm, device=device) / (total_norm + eps)\n for p in parameters:\n p.grad.data.mul_(torch.where(clip_coef < 1, clip_coef, torch.tensor(1., device=device)))\n\n def print_nan_gradients(self) -> None:\n model = self.get_model()\n for param in model.parameters():\n if (param.grad is not None) and torch.isnan(param.grad.float()).any():\n log.info(param, param.grad)\n\n def detect_nan_tensors(self, loss: Tensor) -> None:\n model = self.get_model()\n\n # check if loss is nan\n if not torch.isfinite(loss).all():\n raise ValueError(\n 'The loss returned in `training_step` is nan or inf.'\n )\n # check if a network weight is nan\n for name, param in model.named_parameters():\n if not torch.isfinite(param).all():\n self.print_nan_gradients()\n raise ValueError(\n f'Detected nan and/or inf values in `{name}`.'\n ' Check your forward pass for numerically unstable operations.'\n )\n\n def configure_accumulated_gradients(self, accumulate_grad_batches):\n if isinstance(accumulate_grad_batches, dict):\n self.accumulation_scheduler = GradientAccumulationScheduler(accumulate_grad_batches)\n elif isinstance(accumulate_grad_batches, int):\n schedule = {1: accumulate_grad_batches}\n self.accumulation_scheduler = GradientAccumulationScheduler(schedule)\n else:\n raise TypeError(\"Gradient accumulation supports only int and dict types\")\n", "path": "pytorch_lightning/trainer/training_tricks.py"}]}
1,481
169
gh_patches_debug_5057
rasdani/github-patches
git_diff
pypa__pip-2308
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- pip6.0.4 can not work under python3.4, windows7 64bit. use" pip list" command, met a error: ``` python Traceback (most recent call last): File "C:\Python34\Scripts\pip-script.py", line 9, in <module> load_entry_point('pip==6.0.4', 'console_scripts', 'pip')() File "C:\Python34\lib\site-packages\pip-6.0.4-py3.4.egg\pip\__init__.py", line 217, in main return command.main(cmd_args) File "C:\Python34\lib\site-packages\pip-6.0.4-py3.4.egg\pip\basecommand.py", l ine 122, in main write_debug_log = check_path_owner(debug_log_path, os.geteuid()) AttributeError: 'module' object has no attribute 'geteuid' ``` other commands can not work also. --- 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/filesystem.py` Content: ``` 1 import os.path 2 3 from pip.compat import get_path_uid 4 5 6 def check_path_owner(path, uid): 7 previous = None 8 while path != previous: 9 if os.path.lexists(path): 10 # Actually do the ownership check 11 try: 12 if get_path_uid(path) != os.geteuid(): 13 return False 14 except OSError: 15 return False 16 return True 17 else: 18 previous, path = path, os.path.dirname(path) 19 ``` --- 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/filesystem.py b/pip/utils/filesystem.py --- a/pip/utils/filesystem.py +++ b/pip/utils/filesystem.py @@ -1,9 +1,15 @@ +import os import os.path from pip.compat import get_path_uid def check_path_owner(path, uid): + # If we don't have a way to check the effective uid of this process, then + # we'll just assume that we own the directory. + if not hasattr(os, "geteuid"): + return True + previous = None while path != previous: if os.path.lexists(path):
{"golden_diff": "diff --git a/pip/utils/filesystem.py b/pip/utils/filesystem.py\n--- a/pip/utils/filesystem.py\n+++ b/pip/utils/filesystem.py\n@@ -1,9 +1,15 @@\n+import os\n import os.path\n \n from pip.compat import get_path_uid\n \n \n def check_path_owner(path, uid):\n+ # If we don't have a way to check the effective uid of this process, then\n+ # we'll just assume that we own the directory.\n+ if not hasattr(os, \"geteuid\"):\n+ return True\n+\n previous = None\n while path != previous:\n if os.path.lexists(path):\n", "issue": "pip6.0.4 can not work under python3.4, windows7 64bit.\nuse\" pip list\" command, met a error:\n\n``` python\nTraceback (most recent call last):\n File \"C:\\Python34\\Scripts\\pip-script.py\", line 9, in <module>\n load_entry_point('pip==6.0.4', 'console_scripts', 'pip')()\n File \"C:\\Python34\\lib\\site-packages\\pip-6.0.4-py3.4.egg\\pip\\__init__.py\", line\n 217, in main\n return command.main(cmd_args)\n File \"C:\\Python34\\lib\\site-packages\\pip-6.0.4-py3.4.egg\\pip\\basecommand.py\", l\nine 122, in main\n write_debug_log = check_path_owner(debug_log_path, os.geteuid())\nAttributeError: 'module' object has no attribute 'geteuid'\n```\n\nother commands can not work also.\n\n", "before_files": [{"content": "import os.path\n\nfrom pip.compat import get_path_uid\n\n\ndef check_path_owner(path, uid):\n previous = None\n while path != previous:\n if os.path.lexists(path):\n # Actually do the ownership check\n try:\n if get_path_uid(path) != os.geteuid():\n return False\n except OSError:\n return False\n return True\n else:\n previous, path = path, os.path.dirname(path)\n", "path": "pip/utils/filesystem.py"}], "after_files": [{"content": "import os\nimport os.path\n\nfrom pip.compat import get_path_uid\n\n\ndef check_path_owner(path, uid):\n # If we don't have a way to check the effective uid of this process, then\n # we'll just assume that we own the directory.\n if not hasattr(os, \"geteuid\"):\n return True\n\n previous = None\n while path != previous:\n if os.path.lexists(path):\n # Actually do the ownership check\n try:\n if get_path_uid(path) != os.geteuid():\n return False\n except OSError:\n return False\n return True\n else:\n previous, path = path, os.path.dirname(path)\n", "path": "pip/utils/filesystem.py"}]}
613
143
gh_patches_debug_16838
rasdani/github-patches
git_diff
facebookresearch__hydra-252
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Hydra client API Create Hydra client API to allow jobs to interact with Hydra. one immediate need is to allow executed code to find out what is the original working directory is was executed from. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `hydra/utils.py` Content: ``` 1 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 2 import logging.config 3 4 from omegaconf import OmegaConf 5 6 # pylint: disable=C0103 7 log = logging.getLogger(__name__) 8 9 10 def get_method(path): 11 return get_class(path) 12 13 14 def get_class(path): 15 try: 16 from importlib import import_module 17 18 module_path, _, class_name = path.rpartition(".") 19 mod = import_module(module_path) 20 try: 21 klass = getattr(mod, class_name) 22 except AttributeError: 23 raise ImportError( 24 "Class {} is not in module {}".format(class_name, module_path) 25 ) 26 return klass 27 except ValueError as e: 28 log.error("Error initializing class " + path) 29 raise e 30 31 32 def get_static_method(full_method_name): 33 try: 34 spl = full_method_name.split(".") 35 method_name = spl.pop() 36 class_name = ".".join(spl) 37 clz = get_class(class_name) 38 return getattr(clz, method_name) 39 except Exception as e: 40 log.error("Error getting static method {} : {}".format(full_method_name, e)) 41 raise e 42 43 44 def instantiate(config, *args, **kwargs): 45 assert config is not None, "Input config is None" 46 try: 47 clazz = get_class(config["class"]) 48 params = config.params if "params" in config else OmegaConf.create() 49 params.merge_with(OmegaConf.create(kwargs)) 50 return clazz(*args, **params) 51 except Exception as e: 52 log.error("Error instantiating {} : {}".format(config["class"], e)) 53 raise e 54 ``` --- 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/hydra/utils.py b/hydra/utils.py --- a/hydra/utils.py +++ b/hydra/utils.py @@ -3,6 +3,9 @@ from omegaconf import OmegaConf +from hydra._internal.pathlib import Path +from hydra.plugins.common.utils import HydraConfig + # pylint: disable=C0103 log = logging.getLogger(__name__) @@ -51,3 +54,23 @@ except Exception as e: log.error("Error instantiating {} : {}".format(config["class"], e)) raise e + + +def get_original_cwd(): + return HydraConfig().hydra.runtime.cwd + + +def to_absolute_path(path): + """ + converts the specified path to be absolute path. + if the input path is relative, it's interpreted as relative to the original working directory + if it's absolute, it's returned as is + :param path: + :return: + """ + path = Path(path) + if path.is_absolute(): + ret = path + else: + ret = Path(get_original_cwd()) / path + return str(ret)
{"golden_diff": "diff --git a/hydra/utils.py b/hydra/utils.py\n--- a/hydra/utils.py\n+++ b/hydra/utils.py\n@@ -3,6 +3,9 @@\n \n from omegaconf import OmegaConf\n \n+from hydra._internal.pathlib import Path\n+from hydra.plugins.common.utils import HydraConfig\n+\n # pylint: disable=C0103\n log = logging.getLogger(__name__)\n \n@@ -51,3 +54,23 @@\n except Exception as e:\n log.error(\"Error instantiating {} : {}\".format(config[\"class\"], e))\n raise e\n+\n+\n+def get_original_cwd():\n+ return HydraConfig().hydra.runtime.cwd\n+\n+\n+def to_absolute_path(path):\n+ \"\"\"\n+ converts the specified path to be absolute path.\n+ if the input path is relative, it's interpreted as relative to the original working directory\n+ if it's absolute, it's returned as is\n+ :param path:\n+ :return:\n+ \"\"\"\n+ path = Path(path)\n+ if path.is_absolute():\n+ ret = path\n+ else:\n+ ret = Path(get_original_cwd()) / path\n+ return str(ret)\n", "issue": "Hydra client API\nCreate Hydra client API to allow jobs to interact with Hydra.\r\none immediate need is to allow executed code to find out what is the original working directory is was executed from.\n", "before_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging.config\n\nfrom omegaconf import OmegaConf\n\n# pylint: disable=C0103\nlog = logging.getLogger(__name__)\n\n\ndef get_method(path):\n return get_class(path)\n\n\ndef get_class(path):\n try:\n from importlib import import_module\n\n module_path, _, class_name = path.rpartition(\".\")\n mod = import_module(module_path)\n try:\n klass = getattr(mod, class_name)\n except AttributeError:\n raise ImportError(\n \"Class {} is not in module {}\".format(class_name, module_path)\n )\n return klass\n except ValueError as e:\n log.error(\"Error initializing class \" + path)\n raise e\n\n\ndef get_static_method(full_method_name):\n try:\n spl = full_method_name.split(\".\")\n method_name = spl.pop()\n class_name = \".\".join(spl)\n clz = get_class(class_name)\n return getattr(clz, method_name)\n except Exception as e:\n log.error(\"Error getting static method {} : {}\".format(full_method_name, e))\n raise e\n\n\ndef instantiate(config, *args, **kwargs):\n assert config is not None, \"Input config is None\"\n try:\n clazz = get_class(config[\"class\"])\n params = config.params if \"params\" in config else OmegaConf.create()\n params.merge_with(OmegaConf.create(kwargs))\n return clazz(*args, **params)\n except Exception as e:\n log.error(\"Error instantiating {} : {}\".format(config[\"class\"], e))\n raise e\n", "path": "hydra/utils.py"}], "after_files": [{"content": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging.config\n\nfrom omegaconf import OmegaConf\n\nfrom hydra._internal.pathlib import Path\nfrom hydra.plugins.common.utils import HydraConfig\n\n# pylint: disable=C0103\nlog = logging.getLogger(__name__)\n\n\ndef get_method(path):\n return get_class(path)\n\n\ndef get_class(path):\n try:\n from importlib import import_module\n\n module_path, _, class_name = path.rpartition(\".\")\n mod = import_module(module_path)\n try:\n klass = getattr(mod, class_name)\n except AttributeError:\n raise ImportError(\n \"Class {} is not in module {}\".format(class_name, module_path)\n )\n return klass\n except ValueError as e:\n log.error(\"Error initializing class \" + path)\n raise e\n\n\ndef get_static_method(full_method_name):\n try:\n spl = full_method_name.split(\".\")\n method_name = spl.pop()\n class_name = \".\".join(spl)\n clz = get_class(class_name)\n return getattr(clz, method_name)\n except Exception as e:\n log.error(\"Error getting static method {} : {}\".format(full_method_name, e))\n raise e\n\n\ndef instantiate(config, *args, **kwargs):\n assert config is not None, \"Input config is None\"\n try:\n clazz = get_class(config[\"class\"])\n params = config.params if \"params\" in config else OmegaConf.create()\n params.merge_with(OmegaConf.create(kwargs))\n return clazz(*args, **params)\n except Exception as e:\n log.error(\"Error instantiating {} : {}\".format(config[\"class\"], e))\n raise e\n\n\ndef get_original_cwd():\n return HydraConfig().hydra.runtime.cwd\n\n\ndef to_absolute_path(path):\n \"\"\"\n converts the specified path to be absolute path.\n if the input path is relative, it's interpreted as relative to the original working directory\n if it's absolute, it's returned as is\n :param path:\n :return:\n \"\"\"\n path = Path(path)\n if path.is_absolute():\n ret = path\n else:\n ret = Path(get_original_cwd()) / path\n return str(ret)\n", "path": "hydra/utils.py"}]}
743
264
gh_patches_debug_33267
rasdani/github-patches
git_diff
kserve__kserve-2673
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Numpy 1.24 breaking changes /kind bug **What steps did you take and what happened:** [A clear and concise description of what the bug is.] numpy 1.24 was released on 12/18 https://pypi.org/project/numpy/1.24.0/ https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations ``` kserve/test/test_v1beta1_transformer_spec.py - AttributeError: module 'numpy' has no attribute 'float' [1927](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1928) ERROR kserve/test/test_v1beta1_transformers_config.py - AttributeError: module 'numpy' has no attribute 'float' [1928](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1929) ERROR kserve/test/test_v1beta1_triton_spec.py - AttributeError: module 'numpy' has no attribute 'float' [1929](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1930) ERROR kserve/test/test_v1beta1_xg_boost_spec.py - AttributeError: module 'numpy' has no attribute 'float' ``` **What did you expect to happen:** **What's the InferenceService yaml:** [To help us debug please run `kubectl get isvc $name -n $namespace -oyaml` and paste the output] **Anything else you would like to add:** [Miscellaneous information that will assist in solving the issue.] **Environment:** - Istio Version: - Knative Version: - KServe Version: - Kubeflow version: - Cloud Environment:[k8s_istio/istio_dex/gcp_basic_auth/gcp_iap/aws/aws_cognito/ibm] - Minikube/Kind version: - Kubernetes version: (use `kubectl version`): - OS (e.g. from `/etc/os-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: `python/kserve/kserve/api/watch.py` Content: ``` 1 # Copyright 2021 The KServe 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 import time 16 from kubernetes import client 17 from kubernetes import watch as k8s_watch 18 from table_logger import TableLogger 19 20 from ..constants import constants 21 from ..utils import utils 22 23 24 def isvc_watch(name=None, namespace=None, timeout_seconds=600, generation=0): 25 """Watch the created or patched InferenceService in the specified namespace""" 26 27 if namespace is None: 28 namespace = utils.get_default_target_namespace() 29 30 tbl = TableLogger( 31 columns='NAME,READY,PREV,LATEST,URL', 32 colwidth={'NAME': 20, 'READY': 10, 'PREV': 25, 'LATEST': 25, 'URL': 65}, 33 border=False) 34 35 stream = k8s_watch.Watch().stream( 36 client.CustomObjectsApi().list_namespaced_custom_object, 37 constants.KSERVE_GROUP, 38 constants.KSERVE_V1BETA1_VERSION, 39 namespace, 40 constants.KSERVE_PLURAL, 41 timeout_seconds=timeout_seconds) 42 43 for event in stream: 44 isvc = event['object'] 45 isvc_name = isvc['metadata']['name'] 46 if name and name != isvc_name: 47 continue 48 else: 49 status = 'Unknown' 50 if isvc.get('status', ''): 51 url = isvc['status'].get('url', '') 52 traffic = isvc['status'].get('components', {}).get( 53 'predictor', {}).get('traffic', []) 54 traffic_percent = 100 55 if constants.OBSERVED_GENERATION in isvc['status']: 56 observed_generation = isvc['status'][constants.OBSERVED_GENERATION] 57 for t in traffic: 58 if t["latestRevision"]: 59 traffic_percent = t["percent"] 60 61 if generation != 0 and observed_generation != generation: 62 continue 63 for condition in isvc['status'].get('conditions', {}): 64 if condition.get('type', '') == 'Ready': 65 status = condition.get('status', 'Unknown') 66 tbl(isvc_name, status, 100-traffic_percent, traffic_percent, url) 67 if status == 'True': 68 break 69 70 else: 71 tbl(isvc_name, status, '', '', '') 72 # Sleep 2 to avoid status section is not generated within a very short time. 73 time.sleep(2) 74 continue 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/python/kserve/kserve/api/watch.py b/python/kserve/kserve/api/watch.py --- a/python/kserve/kserve/api/watch.py +++ b/python/kserve/kserve/api/watch.py @@ -13,9 +13,10 @@ # limitations under the License. import time + from kubernetes import client from kubernetes import watch as k8s_watch -from table_logger import TableLogger +from tabulate import tabulate from ..constants import constants from ..utils import utils @@ -27,10 +28,8 @@ if namespace is None: namespace = utils.get_default_target_namespace() - tbl = TableLogger( - columns='NAME,READY,PREV,LATEST,URL', - colwidth={'NAME': 20, 'READY': 10, 'PREV': 25, 'LATEST': 25, 'URL': 65}, - border=False) + headers = ['NAME', 'READY', 'PREV', 'LATEST', 'URL'] + table_fmt = 'plain' stream = k8s_watch.Watch().stream( client.CustomObjectsApi().list_namespaced_custom_object, @@ -63,12 +62,13 @@ for condition in isvc['status'].get('conditions', {}): if condition.get('type', '') == 'Ready': status = condition.get('status', 'Unknown') - tbl(isvc_name, status, 100-traffic_percent, traffic_percent, url) + print(tabulate([[isvc_name, status, 100 - traffic_percent, traffic_percent, url]], + headers=headers, tablefmt=table_fmt)) if status == 'True': break else: - tbl(isvc_name, status, '', '', '') + print(tabulate([[isvc_name, status, '', '', '']], headers=headers, tablefmt=table_fmt)) # Sleep 2 to avoid status section is not generated within a very short time. time.sleep(2) continue
{"golden_diff": "diff --git a/python/kserve/kserve/api/watch.py b/python/kserve/kserve/api/watch.py\n--- a/python/kserve/kserve/api/watch.py\n+++ b/python/kserve/kserve/api/watch.py\n@@ -13,9 +13,10 @@\n # limitations under the License.\n \n import time\n+\n from kubernetes import client\n from kubernetes import watch as k8s_watch\n-from table_logger import TableLogger\n+from tabulate import tabulate\n \n from ..constants import constants\n from ..utils import utils\n@@ -27,10 +28,8 @@\n if namespace is None:\n namespace = utils.get_default_target_namespace()\n \n- tbl = TableLogger(\n- columns='NAME,READY,PREV,LATEST,URL',\n- colwidth={'NAME': 20, 'READY': 10, 'PREV': 25, 'LATEST': 25, 'URL': 65},\n- border=False)\n+ headers = ['NAME', 'READY', 'PREV', 'LATEST', 'URL']\n+ table_fmt = 'plain'\n \n stream = k8s_watch.Watch().stream(\n client.CustomObjectsApi().list_namespaced_custom_object,\n@@ -63,12 +62,13 @@\n for condition in isvc['status'].get('conditions', {}):\n if condition.get('type', '') == 'Ready':\n status = condition.get('status', 'Unknown')\n- tbl(isvc_name, status, 100-traffic_percent, traffic_percent, url)\n+ print(tabulate([[isvc_name, status, 100 - traffic_percent, traffic_percent, url]],\n+ headers=headers, tablefmt=table_fmt))\n if status == 'True':\n break\n \n else:\n- tbl(isvc_name, status, '', '', '')\n+ print(tabulate([[isvc_name, status, '', '', '']], headers=headers, tablefmt=table_fmt))\n # Sleep 2 to avoid status section is not generated within a very short time.\n time.sleep(2)\n continue\n", "issue": "Numpy 1.24 breaking changes \n/kind bug\r\n\r\n**What steps did you take and what happened:**\r\n[A clear and concise description of what the bug is.]\r\nnumpy 1.24 was released on 12/18 https://pypi.org/project/numpy/1.24.0/\r\n\r\nhttps://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\r\n```\r\nkserve/test/test_v1beta1_transformer_spec.py - AttributeError: module 'numpy' has no attribute 'float'\r\n[1927](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1928)\r\nERROR kserve/test/test_v1beta1_transformers_config.py - AttributeError: module 'numpy' has no attribute 'float'\r\n[1928](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1929)\r\nERROR kserve/test/test_v1beta1_triton_spec.py - AttributeError: module 'numpy' has no attribute 'float'\r\n[1929](https://github.com/kserve/kserve/actions/runs/3731363145/jobs/6329505081#step:5:1930)\r\nERROR kserve/test/test_v1beta1_xg_boost_spec.py - AttributeError: module 'numpy' has no attribute 'float'\r\n```\r\n\r\n**What did you expect to happen:**\r\n\r\n\r\n**What's the InferenceService yaml:**\r\n[To help us debug please run `kubectl get isvc $name -n $namespace -oyaml` and paste the output]\r\n\r\n**Anything else you would like to add:**\r\n[Miscellaneous information that will assist in solving the issue.]\r\n\r\n\r\n**Environment:**\r\n\r\n- Istio Version:\r\n- Knative Version:\r\n- KServe Version:\r\n- Kubeflow version:\r\n- Cloud Environment:[k8s_istio/istio_dex/gcp_basic_auth/gcp_iap/aws/aws_cognito/ibm]\r\n- Minikube/Kind version:\r\n- Kubernetes version: (use `kubectl version`):\r\n- OS (e.g. from `/etc/os-release`):\r\n\n", "before_files": [{"content": "# Copyright 2021 The KServe 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\nimport time\nfrom kubernetes import client\nfrom kubernetes import watch as k8s_watch\nfrom table_logger import TableLogger\n\nfrom ..constants import constants\nfrom ..utils import utils\n\n\ndef isvc_watch(name=None, namespace=None, timeout_seconds=600, generation=0):\n \"\"\"Watch the created or patched InferenceService in the specified namespace\"\"\"\n\n if namespace is None:\n namespace = utils.get_default_target_namespace()\n\n tbl = TableLogger(\n columns='NAME,READY,PREV,LATEST,URL',\n colwidth={'NAME': 20, 'READY': 10, 'PREV': 25, 'LATEST': 25, 'URL': 65},\n border=False)\n\n stream = k8s_watch.Watch().stream(\n client.CustomObjectsApi().list_namespaced_custom_object,\n constants.KSERVE_GROUP,\n constants.KSERVE_V1BETA1_VERSION,\n namespace,\n constants.KSERVE_PLURAL,\n timeout_seconds=timeout_seconds)\n\n for event in stream:\n isvc = event['object']\n isvc_name = isvc['metadata']['name']\n if name and name != isvc_name:\n continue\n else:\n status = 'Unknown'\n if isvc.get('status', ''):\n url = isvc['status'].get('url', '')\n traffic = isvc['status'].get('components', {}).get(\n 'predictor', {}).get('traffic', [])\n traffic_percent = 100\n if constants.OBSERVED_GENERATION in isvc['status']:\n observed_generation = isvc['status'][constants.OBSERVED_GENERATION]\n for t in traffic:\n if t[\"latestRevision\"]:\n traffic_percent = t[\"percent\"]\n\n if generation != 0 and observed_generation != generation:\n continue\n for condition in isvc['status'].get('conditions', {}):\n if condition.get('type', '') == 'Ready':\n status = condition.get('status', 'Unknown')\n tbl(isvc_name, status, 100-traffic_percent, traffic_percent, url)\n if status == 'True':\n break\n\n else:\n tbl(isvc_name, status, '', '', '')\n # Sleep 2 to avoid status section is not generated within a very short time.\n time.sleep(2)\n continue\n", "path": "python/kserve/kserve/api/watch.py"}], "after_files": [{"content": "# Copyright 2021 The KServe 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\nimport time\n\nfrom kubernetes import client\nfrom kubernetes import watch as k8s_watch\nfrom tabulate import tabulate\n\nfrom ..constants import constants\nfrom ..utils import utils\n\n\ndef isvc_watch(name=None, namespace=None, timeout_seconds=600, generation=0):\n \"\"\"Watch the created or patched InferenceService in the specified namespace\"\"\"\n\n if namespace is None:\n namespace = utils.get_default_target_namespace()\n\n headers = ['NAME', 'READY', 'PREV', 'LATEST', 'URL']\n table_fmt = 'plain'\n\n stream = k8s_watch.Watch().stream(\n client.CustomObjectsApi().list_namespaced_custom_object,\n constants.KSERVE_GROUP,\n constants.KSERVE_V1BETA1_VERSION,\n namespace,\n constants.KSERVE_PLURAL,\n timeout_seconds=timeout_seconds)\n\n for event in stream:\n isvc = event['object']\n isvc_name = isvc['metadata']['name']\n if name and name != isvc_name:\n continue\n else:\n status = 'Unknown'\n if isvc.get('status', ''):\n url = isvc['status'].get('url', '')\n traffic = isvc['status'].get('components', {}).get(\n 'predictor', {}).get('traffic', [])\n traffic_percent = 100\n if constants.OBSERVED_GENERATION in isvc['status']:\n observed_generation = isvc['status'][constants.OBSERVED_GENERATION]\n for t in traffic:\n if t[\"latestRevision\"]:\n traffic_percent = t[\"percent\"]\n\n if generation != 0 and observed_generation != generation:\n continue\n for condition in isvc['status'].get('conditions', {}):\n if condition.get('type', '') == 'Ready':\n status = condition.get('status', 'Unknown')\n print(tabulate([[isvc_name, status, 100 - traffic_percent, traffic_percent, url]],\n headers=headers, tablefmt=table_fmt))\n if status == 'True':\n break\n\n else:\n print(tabulate([[isvc_name, status, '', '', '']], headers=headers, tablefmt=table_fmt))\n # Sleep 2 to avoid status section is not generated within a very short time.\n time.sleep(2)\n continue\n", "path": "python/kserve/kserve/api/watch.py"}]}
1,551
450
gh_patches_debug_20397
rasdani/github-patches
git_diff
CTFd__CTFd-1824
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Empty and null prerequisites can be added from admin UI **Environment**: - CTFd Version/Commit: 843546b (tip of master) - Operating System: Linux - Web Browser and Version: Firefox **What happened?** Adding a prerequisite to a challenge without selecting a valid challenge entry in the drop down results in either `""` (selecting the "--" item in the drop down) or `null` (not selecting anything in the dropdown). This also breaks rendering of any previously added prerequisites when the UI is reloaded. **What did you expect to happen?** The backend should reject invalid prerequisites (probably via the `ChallengeSchema`?) and the frontend also shouldn't make it easy to submit them. **How to reproduce your issue** 1. Create two challenges A and B 2. VIsit the admin UI page to edit B and click on the "Requirements" tab 3. Select A in the dropdown and click "Add Prerequisite" 4. Select the "--" entry in the dropdown and click "Add Prerequisite" again - observe rendering breakage 5. Solve A in either user or teams mode 6. Query `/api/v1/challenges` and observe that B is not present 7. Visit the admin UI again and select nothing in the requirements dropdown (it will remain blank), then click "Add Prerequisite" once more 8. Check the requirements for the B in the DB/from the ORM. They will be `[<ID of A>, "", None]` **Any associated stack traces or error logs** --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `CTFd/schemas/challenges.py` Content: ``` 1 from marshmallow import validate 2 from marshmallow_sqlalchemy import field_for 3 4 from CTFd.models import Challenges, ma 5 6 7 class ChallengeSchema(ma.ModelSchema): 8 class Meta: 9 model = Challenges 10 include_fk = True 11 dump_only = ("id",) 12 13 name = field_for( 14 Challenges, 15 "name", 16 validate=[ 17 validate.Length( 18 min=0, 19 max=80, 20 error="Challenge could not be saved. Challenge name too long", 21 ) 22 ], 23 ) 24 25 category = field_for( 26 Challenges, 27 "category", 28 validate=[ 29 validate.Length( 30 min=0, 31 max=80, 32 error="Challenge could not be saved. Challenge category too long", 33 ) 34 ], 35 ) 36 37 description = field_for( 38 Challenges, 39 "description", 40 allow_none=True, 41 validate=[ 42 validate.Length( 43 min=0, 44 max=65535, 45 error="Challenge could not be saved. Challenge description too long", 46 ) 47 ], 48 ) 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/CTFd/schemas/challenges.py b/CTFd/schemas/challenges.py --- a/CTFd/schemas/challenges.py +++ b/CTFd/schemas/challenges.py @@ -1,9 +1,29 @@ from marshmallow import validate +from marshmallow.exceptions import ValidationError from marshmallow_sqlalchemy import field_for from CTFd.models import Challenges, ma +class ChallengeRequirementsValidator(validate.Validator): + default_message = "Error parsing challenge requirements" + + def __init__(self, error=None): + self.error = error or self.default_message + + def __call__(self, value): + if isinstance(value, dict) is False: + raise ValidationError(self.default_message) + + prereqs = value.get("prerequisites", []) + if all(prereqs) is False: + raise ValidationError( + "Challenge requirements cannot have a null prerequisite" + ) + + return value + + class ChallengeSchema(ma.ModelSchema): class Meta: model = Challenges @@ -46,3 +66,7 @@ ) ], ) + + requirements = field_for( + Challenges, "requirements", validate=[ChallengeRequirementsValidator()], + )
{"golden_diff": "diff --git a/CTFd/schemas/challenges.py b/CTFd/schemas/challenges.py\n--- a/CTFd/schemas/challenges.py\n+++ b/CTFd/schemas/challenges.py\n@@ -1,9 +1,29 @@\n from marshmallow import validate\n+from marshmallow.exceptions import ValidationError\n from marshmallow_sqlalchemy import field_for\n \n from CTFd.models import Challenges, ma\n \n \n+class ChallengeRequirementsValidator(validate.Validator):\n+ default_message = \"Error parsing challenge requirements\"\n+\n+ def __init__(self, error=None):\n+ self.error = error or self.default_message\n+\n+ def __call__(self, value):\n+ if isinstance(value, dict) is False:\n+ raise ValidationError(self.default_message)\n+\n+ prereqs = value.get(\"prerequisites\", [])\n+ if all(prereqs) is False:\n+ raise ValidationError(\n+ \"Challenge requirements cannot have a null prerequisite\"\n+ )\n+\n+ return value\n+\n+\n class ChallengeSchema(ma.ModelSchema):\n class Meta:\n model = Challenges\n@@ -46,3 +66,7 @@\n )\n ],\n )\n+\n+ requirements = field_for(\n+ Challenges, \"requirements\", validate=[ChallengeRequirementsValidator()],\n+ )\n", "issue": "Empty and null prerequisites can be added from admin UI\n**Environment**:\r\n\r\n- CTFd Version/Commit: 843546b (tip of master)\r\n- Operating System: Linux\r\n- Web Browser and Version: Firefox\r\n\r\n**What happened?**\r\nAdding a prerequisite to a challenge without selecting a valid challenge entry in the drop down results in either `\"\"` (selecting the \"--\" item in the drop down) or `null` (not selecting anything in the dropdown). This also breaks rendering of any previously added prerequisites when the UI is reloaded.\r\n\r\n**What did you expect to happen?**\r\nThe backend should reject invalid prerequisites (probably via the `ChallengeSchema`?) and the frontend also shouldn't make it easy to submit them.\r\n\r\n**How to reproduce your issue**\r\n1. Create two challenges A and B\r\n2. VIsit the admin UI page to edit B and click on the \"Requirements\" tab\r\n3. Select A in the dropdown and click \"Add Prerequisite\"\r\n4. Select the \"--\" entry in the dropdown and click \"Add Prerequisite\" again - observe rendering breakage\r\n5. Solve A in either user or teams mode\r\n6. Query `/api/v1/challenges` and observe that B is not present\r\n7. Visit the admin UI again and select nothing in the requirements dropdown (it will remain blank), then click \"Add Prerequisite\" once more\r\n8. Check the requirements for the B in the DB/from the ORM. They will be `[<ID of A>, \"\", None]`\r\n\r\n**Any associated stack traces or error logs**\r\n\n", "before_files": [{"content": "from marshmallow import validate\nfrom marshmallow_sqlalchemy import field_for\n\nfrom CTFd.models import Challenges, ma\n\n\nclass ChallengeSchema(ma.ModelSchema):\n class Meta:\n model = Challenges\n include_fk = True\n dump_only = (\"id\",)\n\n name = field_for(\n Challenges,\n \"name\",\n validate=[\n validate.Length(\n min=0,\n max=80,\n error=\"Challenge could not be saved. Challenge name too long\",\n )\n ],\n )\n\n category = field_for(\n Challenges,\n \"category\",\n validate=[\n validate.Length(\n min=0,\n max=80,\n error=\"Challenge could not be saved. Challenge category too long\",\n )\n ],\n )\n\n description = field_for(\n Challenges,\n \"description\",\n allow_none=True,\n validate=[\n validate.Length(\n min=0,\n max=65535,\n error=\"Challenge could not be saved. Challenge description too long\",\n )\n ],\n )\n", "path": "CTFd/schemas/challenges.py"}], "after_files": [{"content": "from marshmallow import validate\nfrom marshmallow.exceptions import ValidationError\nfrom marshmallow_sqlalchemy import field_for\n\nfrom CTFd.models import Challenges, ma\n\n\nclass ChallengeRequirementsValidator(validate.Validator):\n default_message = \"Error parsing challenge requirements\"\n\n def __init__(self, error=None):\n self.error = error or self.default_message\n\n def __call__(self, value):\n if isinstance(value, dict) is False:\n raise ValidationError(self.default_message)\n\n prereqs = value.get(\"prerequisites\", [])\n if all(prereqs) is False:\n raise ValidationError(\n \"Challenge requirements cannot have a null prerequisite\"\n )\n\n return value\n\n\nclass ChallengeSchema(ma.ModelSchema):\n class Meta:\n model = Challenges\n include_fk = True\n dump_only = (\"id\",)\n\n name = field_for(\n Challenges,\n \"name\",\n validate=[\n validate.Length(\n min=0,\n max=80,\n error=\"Challenge could not be saved. Challenge name too long\",\n )\n ],\n )\n\n category = field_for(\n Challenges,\n \"category\",\n validate=[\n validate.Length(\n min=0,\n max=80,\n error=\"Challenge could not be saved. Challenge category too long\",\n )\n ],\n )\n\n description = field_for(\n Challenges,\n \"description\",\n allow_none=True,\n validate=[\n validate.Length(\n min=0,\n max=65535,\n error=\"Challenge could not be saved. Challenge description too long\",\n )\n ],\n )\n\n requirements = field_for(\n Challenges, \"requirements\", validate=[ChallengeRequirementsValidator()],\n )\n", "path": "CTFd/schemas/challenges.py"}]}
901
272
gh_patches_debug_26513
rasdani/github-patches
git_diff
getsentry__sentry-5804
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Issues resolved via UI do not appear in releases overview To reproduce: * Navigate to an issue * Click "Resolve in current release (abc123)" * Navigate to that release (abc123) * Issue does not appear under "New Issues in this 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/sentry/api/endpoints/issues_resolved_in_release.py` Content: ``` 1 from __future__ import absolute_import 2 3 from rest_framework.response import Response 4 5 from sentry.api.base import DocSection 6 from sentry.api.bases.project import ProjectEndpoint, ProjectPermission 7 from sentry.api.exceptions import ResourceDoesNotExist 8 from sentry.api.serializers import serialize 9 from sentry.api.serializers.models.group import StreamGroupSerializer 10 from sentry.models import ( 11 Group, 12 GroupCommitResolution, 13 Release, 14 ReleaseCommit, 15 ) 16 17 18 class IssuesResolvedInReleaseEndpoint(ProjectEndpoint): 19 doc_section = DocSection.RELEASES 20 permission_classes = (ProjectPermission, ) 21 22 def get(self, request, project, version): 23 """ 24 List issues to be resolved in a particular release 25 ```````````````````````` 26 27 Retrieve a list of issues to be resolved in a given release. 28 29 :pparam string organization_slug: the slug of the organization the 30 release belongs to. 31 :pparam string project_slug: the slug of the project associated with the release. 32 :pparam string version: the version identifier of the release. 33 :auth: required 34 """ 35 try: 36 release = Release.objects.get(version=version, organization=project.organization) 37 except Release.DoesNotExist: 38 raise ResourceDoesNotExist 39 40 groups = Group.objects.filter( 41 project=project, 42 id__in=GroupCommitResolution.objects.filter( 43 commit_id__in=ReleaseCommit.objects.filter( 44 release=release, 45 ).values_list('commit_id', flat=True), 46 ).values_list('group_id', flat=True), 47 ) 48 49 context = serialize(list(groups), request.user, StreamGroupSerializer(stats_period=None)) 50 return Response(context) 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/sentry/api/endpoints/issues_resolved_in_release.py b/src/sentry/api/endpoints/issues_resolved_in_release.py --- a/src/sentry/api/endpoints/issues_resolved_in_release.py +++ b/src/sentry/api/endpoints/issues_resolved_in_release.py @@ -10,6 +10,7 @@ from sentry.models import ( Group, GroupCommitResolution, + GroupResolution, Release, ReleaseCommit, ) @@ -37,14 +38,27 @@ except Release.DoesNotExist: raise ResourceDoesNotExist - groups = Group.objects.filter( - project=project, - id__in=GroupCommitResolution.objects.filter( + group_ids = set() + group_ids |= set( + GroupResolution.objects.filter( + release=release, + ).values_list('group_id', flat=True) + ) + group_ids |= set( + GroupCommitResolution.objects.filter( commit_id__in=ReleaseCommit.objects.filter( release=release, - ).values_list('commit_id', flat=True), - ).values_list('group_id', flat=True), + ).values_list( + 'commit_id', + flat=True, + ) + ).values_list( + 'group_id', + flat=True, + ) ) + groups = Group.objects.filter(project=project, id__in=group_ids) + context = serialize(list(groups), request.user, StreamGroupSerializer(stats_period=None)) return Response(context)
{"golden_diff": "diff --git a/src/sentry/api/endpoints/issues_resolved_in_release.py b/src/sentry/api/endpoints/issues_resolved_in_release.py\n--- a/src/sentry/api/endpoints/issues_resolved_in_release.py\n+++ b/src/sentry/api/endpoints/issues_resolved_in_release.py\n@@ -10,6 +10,7 @@\n from sentry.models import (\n Group,\n GroupCommitResolution,\n+ GroupResolution,\n Release,\n ReleaseCommit,\n )\n@@ -37,14 +38,27 @@\n except Release.DoesNotExist:\n raise ResourceDoesNotExist\n \n- groups = Group.objects.filter(\n- project=project,\n- id__in=GroupCommitResolution.objects.filter(\n+ group_ids = set()\n+ group_ids |= set(\n+ GroupResolution.objects.filter(\n+ release=release,\n+ ).values_list('group_id', flat=True)\n+ )\n+ group_ids |= set(\n+ GroupCommitResolution.objects.filter(\n commit_id__in=ReleaseCommit.objects.filter(\n release=release,\n- ).values_list('commit_id', flat=True),\n- ).values_list('group_id', flat=True),\n+ ).values_list(\n+ 'commit_id',\n+ flat=True,\n+ )\n+ ).values_list(\n+ 'group_id',\n+ flat=True,\n+ )\n )\n \n+ groups = Group.objects.filter(project=project, id__in=group_ids)\n+\n context = serialize(list(groups), request.user, StreamGroupSerializer(stats_period=None))\n return Response(context)\n", "issue": "Issues resolved via UI do not appear in releases overview\nTo reproduce:\r\n\r\n* Navigate to an issue\r\n* Click \"Resolve in current release (abc123)\"\r\n* Navigate to that release (abc123)\r\n* Issue does not appear under \"New Issues in this Release\"\r\n\n", "before_files": [{"content": "from __future__ import absolute_import\n\nfrom rest_framework.response import Response\n\nfrom sentry.api.base import DocSection\nfrom sentry.api.bases.project import ProjectEndpoint, ProjectPermission\nfrom sentry.api.exceptions import ResourceDoesNotExist\nfrom sentry.api.serializers import serialize\nfrom sentry.api.serializers.models.group import StreamGroupSerializer\nfrom sentry.models import (\n Group,\n GroupCommitResolution,\n Release,\n ReleaseCommit,\n)\n\n\nclass IssuesResolvedInReleaseEndpoint(ProjectEndpoint):\n doc_section = DocSection.RELEASES\n permission_classes = (ProjectPermission, )\n\n def get(self, request, project, version):\n \"\"\"\n List issues to be resolved in a particular release\n ````````````````````````\n\n Retrieve a list of issues to be resolved in a given release.\n\n :pparam string organization_slug: the slug of the organization the\n release belongs to.\n :pparam string project_slug: the slug of the project associated with the release.\n :pparam string version: the version identifier of the release.\n :auth: required\n \"\"\"\n try:\n release = Release.objects.get(version=version, organization=project.organization)\n except Release.DoesNotExist:\n raise ResourceDoesNotExist\n\n groups = Group.objects.filter(\n project=project,\n id__in=GroupCommitResolution.objects.filter(\n commit_id__in=ReleaseCommit.objects.filter(\n release=release,\n ).values_list('commit_id', flat=True),\n ).values_list('group_id', flat=True),\n )\n\n context = serialize(list(groups), request.user, StreamGroupSerializer(stats_period=None))\n return Response(context)\n", "path": "src/sentry/api/endpoints/issues_resolved_in_release.py"}], "after_files": [{"content": "from __future__ import absolute_import\n\nfrom rest_framework.response import Response\n\nfrom sentry.api.base import DocSection\nfrom sentry.api.bases.project import ProjectEndpoint, ProjectPermission\nfrom sentry.api.exceptions import ResourceDoesNotExist\nfrom sentry.api.serializers import serialize\nfrom sentry.api.serializers.models.group import StreamGroupSerializer\nfrom sentry.models import (\n Group,\n GroupCommitResolution,\n GroupResolution,\n Release,\n ReleaseCommit,\n)\n\n\nclass IssuesResolvedInReleaseEndpoint(ProjectEndpoint):\n doc_section = DocSection.RELEASES\n permission_classes = (ProjectPermission, )\n\n def get(self, request, project, version):\n \"\"\"\n List issues to be resolved in a particular release\n ````````````````````````\n\n Retrieve a list of issues to be resolved in a given release.\n\n :pparam string organization_slug: the slug of the organization the\n release belongs to.\n :pparam string project_slug: the slug of the project associated with the release.\n :pparam string version: the version identifier of the release.\n :auth: required\n \"\"\"\n try:\n release = Release.objects.get(version=version, organization=project.organization)\n except Release.DoesNotExist:\n raise ResourceDoesNotExist\n\n group_ids = set()\n group_ids |= set(\n GroupResolution.objects.filter(\n release=release,\n ).values_list('group_id', flat=True)\n )\n group_ids |= set(\n GroupCommitResolution.objects.filter(\n commit_id__in=ReleaseCommit.objects.filter(\n release=release,\n ).values_list(\n 'commit_id',\n flat=True,\n )\n ).values_list(\n 'group_id',\n flat=True,\n )\n )\n\n groups = Group.objects.filter(project=project, id__in=group_ids)\n\n context = serialize(list(groups), request.user, StreamGroupSerializer(stats_period=None))\n return Response(context)\n", "path": "src/sentry/api/endpoints/issues_resolved_in_release.py"}]}
773
331
gh_patches_debug_23241
rasdani/github-patches
git_diff
Cog-Creators__Red-DiscordBot-3361
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [crash] bank balance - when the bot doesnt have perms to send message ```Traceback (most recent call last): File "/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 79, in wrapped ret = await coro(*args, **kwargs) File "/home/bb8/venv/lib/python3.7/site-packages/redbot/cogs/economy/economy.py", line 174, in balance user=user.display_name, num=humanize_number(bal), currency=currency File "/home/bb8/venv/lib/python3.7/site-packages/redbot/core/commands/context.py", line 81, in send return await super().send(content=content, **kwargs) File "/home/bb8/venv/lib/python3.7/site-packages/discord/abc.py", line 823, in send data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce) File "/home/bb8/venv/lib/python3.7/site-packages/discord/http.py", line 218, in request raise Forbidden(r, data) discord.errors.Forbidden: 403 FORBIDDEN (error code: 50013): Missing Permissions The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke await ctx.command.invoke(ctx) File "/home/bb8/venv/lib/python3.7/site-packages/redbot/core/commands/commands.py", line 587, in invoke await super().invoke(ctx) File "/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 1158, in invoke await ctx.invoked_subcommand.invoke(ctx) File "/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 728, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py", line 88, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 FORBIDDEN (error code: 50013): Missing Permissions``` Trace taken from BB-8 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `redbot/core/global_checks.py` Content: ``` 1 """The checks in this module run on every command.""" 2 from . import commands 3 4 5 def init_global_checks(bot): 6 @bot.check_once 7 def actually_up(ctx): 8 """ 9 Uptime is set during the initial startup process. 10 If this hasn't been set, we should assume the bot isn't ready yet. 11 """ 12 return ctx.bot.uptime is not None 13 14 @bot.check_once 15 async def whiteblacklist_checks(ctx): 16 return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author) 17 18 @bot.check_once 19 def bots(ctx): 20 """Check the user is not another bot.""" 21 return not ctx.author.bot 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/redbot/core/global_checks.py b/redbot/core/global_checks.py --- a/redbot/core/global_checks.py +++ b/redbot/core/global_checks.py @@ -4,7 +4,17 @@ def init_global_checks(bot): @bot.check_once - def actually_up(ctx): + def minimum_bot_perms(ctx) -> bool: + """ + Too many 403, 401, and 429 Errors can cause bots to get global'd + + It's reasonable to assume the below as a minimum amount of perms for + commands. + """ + return ctx.channel.permissions_for(ctx.me).send_messages + + @bot.check_once + def actually_up(ctx) -> bool: """ Uptime is set during the initial startup process. If this hasn't been set, we should assume the bot isn't ready yet. @@ -12,10 +22,10 @@ return ctx.bot.uptime is not None @bot.check_once - async def whiteblacklist_checks(ctx): + async def whiteblacklist_checks(ctx) -> bool: return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author) @bot.check_once - def bots(ctx): + def bots(ctx) -> bool: """Check the user is not another bot.""" return not ctx.author.bot
{"golden_diff": "diff --git a/redbot/core/global_checks.py b/redbot/core/global_checks.py\n--- a/redbot/core/global_checks.py\n+++ b/redbot/core/global_checks.py\n@@ -4,7 +4,17 @@\n \n def init_global_checks(bot):\n @bot.check_once\n- def actually_up(ctx):\n+ def minimum_bot_perms(ctx) -> bool:\n+ \"\"\"\n+ Too many 403, 401, and 429 Errors can cause bots to get global'd\n+ \n+ It's reasonable to assume the below as a minimum amount of perms for\n+ commands.\n+ \"\"\"\n+ return ctx.channel.permissions_for(ctx.me).send_messages\n+\n+ @bot.check_once\n+ def actually_up(ctx) -> bool:\n \"\"\" \n Uptime is set during the initial startup process.\n If this hasn't been set, we should assume the bot isn't ready yet. \n@@ -12,10 +22,10 @@\n return ctx.bot.uptime is not None\n \n @bot.check_once\n- async def whiteblacklist_checks(ctx):\n+ async def whiteblacklist_checks(ctx) -> bool:\n return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author)\n \n @bot.check_once\n- def bots(ctx):\n+ def bots(ctx) -> bool:\n \"\"\"Check the user is not another bot.\"\"\"\n return not ctx.author.bot\n", "issue": "[crash] bank balance - when the bot doesnt have perms to send message\n```Traceback (most recent call last):\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py\", line 79, in wrapped\r\n ret = await coro(*args, **kwargs)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/redbot/cogs/economy/economy.py\", line 174, in balance\r\n user=user.display_name, num=humanize_number(bal), currency=currency\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/redbot/core/commands/context.py\", line 81, in send\r\n return await super().send(content=content, **kwargs)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/abc.py\", line 823, in send\r\n data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/http.py\", line 218, in request\r\n raise Forbidden(r, data)\r\ndiscord.errors.Forbidden: 403 FORBIDDEN (error code: 50013): Missing Permissions\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/bot.py\", line 863, in invoke\r\n await ctx.command.invoke(ctx)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/redbot/core/commands/commands.py\", line 587, in invoke\r\n await super().invoke(ctx)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py\", line 1158, in invoke\r\n await ctx.invoked_subcommand.invoke(ctx)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py\", line 728, in invoke\r\n await injected(*ctx.args, **ctx.kwargs)\r\n File \"/home/bb8/venv/lib/python3.7/site-packages/discord/ext/commands/core.py\", line 88, in wrapped\r\n raise CommandInvokeError(exc) from exc\r\ndiscord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 FORBIDDEN (error code: 50013): Missing Permissions```\r\n\r\nTrace taken from BB-8\n", "before_files": [{"content": "\"\"\"The checks in this module run on every command.\"\"\"\nfrom . import commands\n\n\ndef init_global_checks(bot):\n @bot.check_once\n def actually_up(ctx):\n \"\"\" \n Uptime is set during the initial startup process.\n If this hasn't been set, we should assume the bot isn't ready yet. \n \"\"\"\n return ctx.bot.uptime is not None\n\n @bot.check_once\n async def whiteblacklist_checks(ctx):\n return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author)\n\n @bot.check_once\n def bots(ctx):\n \"\"\"Check the user is not another bot.\"\"\"\n return not ctx.author.bot\n", "path": "redbot/core/global_checks.py"}], "after_files": [{"content": "\"\"\"The checks in this module run on every command.\"\"\"\nfrom . import commands\n\n\ndef init_global_checks(bot):\n @bot.check_once\n def minimum_bot_perms(ctx) -> bool:\n \"\"\"\n Too many 403, 401, and 429 Errors can cause bots to get global'd\n \n It's reasonable to assume the below as a minimum amount of perms for\n commands.\n \"\"\"\n return ctx.channel.permissions_for(ctx.me).send_messages\n\n @bot.check_once\n def actually_up(ctx) -> bool:\n \"\"\" \n Uptime is set during the initial startup process.\n If this hasn't been set, we should assume the bot isn't ready yet. \n \"\"\"\n return ctx.bot.uptime is not None\n\n @bot.check_once\n async def whiteblacklist_checks(ctx) -> bool:\n return await ctx.bot.allowed_by_whitelist_blacklist(ctx.author)\n\n @bot.check_once\n def bots(ctx) -> bool:\n \"\"\"Check the user is not another bot.\"\"\"\n return not ctx.author.bot\n", "path": "redbot/core/global_checks.py"}]}
1,009
305
gh_patches_debug_19583
rasdani/github-patches
git_diff
dotkom__onlineweb4-1455
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Group Sync when changing a User Currently the group syncer is only run when a group is updated (saved). If a user is added to (or removed from) a group, the syncer won't run. Fix: Connect to the signal sent by User.groups m2m-relation when a user is saved, like described here: https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed This is to be done in `apps/authentication/signals.py`. --- 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/authentication/signals.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 from django.contrib.auth.models import Group 3 from django.db.models.signals import post_save 4 from django.dispatch import receiver 5 6 from apps.authentication.tasks import SynchronizeGroups 7 8 9 @receiver(post_save, sender=Group) 10 def trigger_group_syncer(sender, instance, created, **kwargs): 11 """ 12 :param sender: The model that triggered this hook 13 :param instance: The model instance triggering this hook 14 :param created: True if the instance was created, False if the instance was updated 15 16 Calls the SynchronizeGroups Task if a group is updated. (Not if it's the initial creation of a group) 17 """ 18 19 if created: 20 # If a new instance is created, we do not need to trigger group sync. 21 pass 22 else: 23 SynchronizeGroups.run() 24 ``` --- 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/authentication/signals.py b/apps/authentication/signals.py --- a/apps/authentication/signals.py +++ b/apps/authentication/signals.py @@ -1,13 +1,17 @@ # -*- coding: utf-8 -*- +from django.contrib.auth import get_user_model from django.contrib.auth.models import Group -from django.db.models.signals import post_save +from django.db.models.signals import m2m_changed, post_save from django.dispatch import receiver from apps.authentication.tasks import SynchronizeGroups +User = get_user_model() + + @receiver(post_save, sender=Group) -def trigger_group_syncer(sender, instance, created, **kwargs): +def trigger_group_syncer(sender, instance, created=False, **kwargs): """ :param sender: The model that triggered this hook :param instance: The model instance triggering this hook @@ -21,3 +25,5 @@ pass else: SynchronizeGroups.run() + +m2m_changed.connect(trigger_group_syncer, sender=User.groups.through)
{"golden_diff": "diff --git a/apps/authentication/signals.py b/apps/authentication/signals.py\n--- a/apps/authentication/signals.py\n+++ b/apps/authentication/signals.py\n@@ -1,13 +1,17 @@\n # -*- coding: utf-8 -*-\n+from django.contrib.auth import get_user_model\n from django.contrib.auth.models import Group\n-from django.db.models.signals import post_save\n+from django.db.models.signals import m2m_changed, post_save\n from django.dispatch import receiver\n \n from apps.authentication.tasks import SynchronizeGroups\n \n \n+User = get_user_model()\n+\n+\n @receiver(post_save, sender=Group)\n-def trigger_group_syncer(sender, instance, created, **kwargs):\n+def trigger_group_syncer(sender, instance, created=False, **kwargs):\n \"\"\"\n :param sender: The model that triggered this hook\n :param instance: The model instance triggering this hook\n@@ -21,3 +25,5 @@\n pass\n else:\n SynchronizeGroups.run()\n+\n+m2m_changed.connect(trigger_group_syncer, sender=User.groups.through)\n", "issue": "Group Sync when changing a User\nCurrently the group syncer is only run when a group is updated (saved). If a user is added to (or removed from) a group, the syncer won't run. \n\nFix:\nConnect to the signal sent by User.groups m2m-relation when a user is saved, like described here: https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed\n\nThis is to be done in `apps/authentication/signals.py`.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nfrom django.contrib.auth.models import Group\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom apps.authentication.tasks import SynchronizeGroups\n\n\n@receiver(post_save, sender=Group)\ndef trigger_group_syncer(sender, instance, created, **kwargs):\n \"\"\"\n :param sender: The model that triggered this hook\n :param instance: The model instance triggering this hook\n :param created: True if the instance was created, False if the instance was updated\n\n Calls the SynchronizeGroups Task if a group is updated. (Not if it's the initial creation of a group)\n \"\"\"\n\n if created:\n # If a new instance is created, we do not need to trigger group sync.\n pass\n else:\n SynchronizeGroups.run()\n", "path": "apps/authentication/signals.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\nfrom django.db.models.signals import m2m_changed, post_save\nfrom django.dispatch import receiver\n\nfrom apps.authentication.tasks import SynchronizeGroups\n\n\nUser = get_user_model()\n\n\n@receiver(post_save, sender=Group)\ndef trigger_group_syncer(sender, instance, created=False, **kwargs):\n \"\"\"\n :param sender: The model that triggered this hook\n :param instance: The model instance triggering this hook\n :param created: True if the instance was created, False if the instance was updated\n\n Calls the SynchronizeGroups Task if a group is updated. (Not if it's the initial creation of a group)\n \"\"\"\n\n if created:\n # If a new instance is created, we do not need to trigger group sync.\n pass\n else:\n SynchronizeGroups.run()\n\nm2m_changed.connect(trigger_group_syncer, sender=User.groups.through)\n", "path": "apps/authentication/signals.py"}]}
573
225
gh_patches_debug_11051
rasdani/github-patches
git_diff
saleor__saleor-1447
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add Categories to the Sitemap Sitemap consists of Products only, we should expand it to include categories 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: `saleor/core/sitemaps.py` Content: ``` 1 from __future__ import unicode_literals 2 3 from django.contrib.sitemaps import Sitemap 4 5 from ..product.models import Product 6 7 8 class ProductSitemap(Sitemap): 9 10 def items(self): 11 return Product.objects.only('id', 'name').order_by('-id') 12 13 14 sitemaps = {'products': ProductSitemap} 15 ``` --- 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/saleor/core/sitemaps.py b/saleor/core/sitemaps.py --- a/saleor/core/sitemaps.py +++ b/saleor/core/sitemaps.py @@ -2,7 +2,7 @@ from django.contrib.sitemaps import Sitemap -from ..product.models import Product +from ..product.models import Category, Product class ProductSitemap(Sitemap): @@ -11,4 +11,13 @@ return Product.objects.only('id', 'name').order_by('-id') -sitemaps = {'products': ProductSitemap} +class CategorySitemap(Sitemap): + + def items(self): + categories = Category.objects.all().order_by('id') + return categories.only('id', 'name', 'slug') + +sitemaps = { + 'categories': CategorySitemap, + 'products': ProductSitemap +}
{"golden_diff": "diff --git a/saleor/core/sitemaps.py b/saleor/core/sitemaps.py\n--- a/saleor/core/sitemaps.py\n+++ b/saleor/core/sitemaps.py\n@@ -2,7 +2,7 @@\n \n from django.contrib.sitemaps import Sitemap\n \n-from ..product.models import Product\n+from ..product.models import Category, Product\n \n \n class ProductSitemap(Sitemap):\n@@ -11,4 +11,13 @@\n return Product.objects.only('id', 'name').order_by('-id')\n \n \n-sitemaps = {'products': ProductSitemap}\n+class CategorySitemap(Sitemap):\n+\n+ def items(self):\n+ categories = Category.objects.all().order_by('id')\n+ return categories.only('id', 'name', 'slug')\n+\n+sitemaps = {\n+ 'categories': CategorySitemap,\n+ 'products': ProductSitemap\n+}\n", "issue": "Add Categories to the Sitemap\nSitemap consists of Products only, we should expand it to include categories as well.\n", "before_files": [{"content": "from __future__ import unicode_literals\n\nfrom django.contrib.sitemaps import Sitemap\n\nfrom ..product.models import Product\n\n\nclass ProductSitemap(Sitemap):\n\n def items(self):\n return Product.objects.only('id', 'name').order_by('-id')\n\n\nsitemaps = {'products': ProductSitemap}\n", "path": "saleor/core/sitemaps.py"}], "after_files": [{"content": "from __future__ import unicode_literals\n\nfrom django.contrib.sitemaps import Sitemap\n\nfrom ..product.models import Category, Product\n\n\nclass ProductSitemap(Sitemap):\n\n def items(self):\n return Product.objects.only('id', 'name').order_by('-id')\n\n\nclass CategorySitemap(Sitemap):\n\n def items(self):\n categories = Category.objects.all().order_by('id')\n return categories.only('id', 'name', 'slug')\n\nsitemaps = {\n 'categories': CategorySitemap,\n 'products': ProductSitemap\n}\n", "path": "saleor/core/sitemaps.py"}]}
377
199
gh_patches_debug_16716
rasdani/github-patches
git_diff
sosreport__sos-2872
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- smartcard plugin is using tools removed/not available from rhel8 and newer The pam_pkcs11 was last available in RHEL7 and is no longer available in RHEL8 and newer so there is no point for checking it and its configuration files in: https://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L21-L22 The `pcsc-tools` package above is not available in RHEL (only from EPEL). Instead, this list should contain `pcsc-lite` and `pcsc-lite-ccid` packages. Also the following commands/path do not have any significance so I propose to remove them (the `pklogin_finder` is part of pam_pkcs11`, which is not available in RHEL8 and newer). The respective replacement would be some command from sssd, but most of the sssd logs are already collected so I do not think we need a separate command: https://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L32-L33 https://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L40 The `pcsc_scan` is a tool that is shipped in `pcsc-tools` package, which is available in EPEL only so I suggest to remove it: https://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L34 Let me know if this sounds ok to you or I should open a PR with the proposed changes. Note, that these are still needed for RHEL7, but I think for RHEL7 you have a different branch. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `sos/report/plugins/smartcard.py` Content: ``` 1 # Copyright (C) 2007 Sadique Puthen <[email protected]> 2 3 # This file is part of the sos project: https://github.com/sosreport/sos 4 # 5 # This copyrighted material is made available to anyone wishing to use, 6 # modify, copy, or redistribute it subject to the terms and conditions of 7 # version 2 of the GNU General Public License. 8 # 9 # See the LICENSE file in the source distribution for further information. 10 11 from sos.report.plugins import Plugin, RedHatPlugin 12 13 14 class Smartcard(Plugin, RedHatPlugin): 15 16 short_desc = 'PKCS#11 smart cards' 17 18 plugin_name = 'smartcard' 19 profiles = ('security', 'identity', 'hardware') 20 21 files = ('/etc/pam_pkcs11/pam_pkcs11.conf',) 22 packages = ('pam_pkcs11', 'pcsc-tools', 'opensc') 23 24 def setup(self): 25 self.add_copy_spec([ 26 "/etc/reader.conf", 27 "/etc/reader.conf.d/", 28 "/etc/pam_pkcs11/", 29 "/etc/opensc-*.conf" 30 ]) 31 self.add_cmd_output([ 32 "pklogin_finder debug", 33 "ls -nl /usr/lib*/pam_pkcs11/", 34 "pcsc_scan", 35 "pkcs11-tool --show-info", 36 "pkcs11-tool --list-mechanisms", 37 "pkcs11-tool --list-slots", 38 "pkcs11-tool --list-objects" 39 ]) 40 self.add_forbidden_path("/etc/pam_pkcs11/nssdb/key[3-4].db") 41 42 # vim: set et ts=4 sw=4 : 43 ``` --- 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/sos/report/plugins/smartcard.py b/sos/report/plugins/smartcard.py --- a/sos/report/plugins/smartcard.py +++ b/sos/report/plugins/smartcard.py @@ -19,14 +19,18 @@ profiles = ('security', 'identity', 'hardware') files = ('/etc/pam_pkcs11/pam_pkcs11.conf',) - packages = ('pam_pkcs11', 'pcsc-tools', 'opensc') + # The pam_pkcs11 is available only in RHEL7 + packages = ('pam_pkcs11', 'pcsc-tools', 'opensc', 'pcsc-lite', + 'pcsc-lite-ccid') def setup(self): self.add_copy_spec([ "/etc/reader.conf", "/etc/reader.conf.d/", "/etc/pam_pkcs11/", - "/etc/opensc-*.conf" + "/etc/opensc-*.conf", + "/etc/pkcs11/modules/*.module", + "/usr/share/p11-kit/modules/*.module" ]) self.add_cmd_output([ "pklogin_finder debug",
{"golden_diff": "diff --git a/sos/report/plugins/smartcard.py b/sos/report/plugins/smartcard.py\n--- a/sos/report/plugins/smartcard.py\n+++ b/sos/report/plugins/smartcard.py\n@@ -19,14 +19,18 @@\n profiles = ('security', 'identity', 'hardware')\n \n files = ('/etc/pam_pkcs11/pam_pkcs11.conf',)\n- packages = ('pam_pkcs11', 'pcsc-tools', 'opensc')\n+ # The pam_pkcs11 is available only in RHEL7\n+ packages = ('pam_pkcs11', 'pcsc-tools', 'opensc', 'pcsc-lite',\n+ 'pcsc-lite-ccid')\n \n def setup(self):\n self.add_copy_spec([\n \"/etc/reader.conf\",\n \"/etc/reader.conf.d/\",\n \"/etc/pam_pkcs11/\",\n- \"/etc/opensc-*.conf\"\n+ \"/etc/opensc-*.conf\",\n+ \"/etc/pkcs11/modules/*.module\",\n+ \"/usr/share/p11-kit/modules/*.module\"\n ])\n self.add_cmd_output([\n \"pklogin_finder debug\",\n", "issue": "smartcard plugin is using tools removed/not available from rhel8 and newer\nThe pam_pkcs11 was last available in RHEL7 and is no longer available in RHEL8 and newer so there is no point for checking it and its configuration files in:\r\n\r\nhttps://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L21-L22\r\n\r\nThe `pcsc-tools` package above is not available in RHEL (only from EPEL). Instead, this list should contain `pcsc-lite` and `pcsc-lite-ccid` packages.\r\n\r\nAlso the following commands/path do not have any significance so I propose to remove them (the `pklogin_finder` is part of pam_pkcs11`, which is not available in RHEL8 and newer). The respective replacement would be some command from sssd, but most of the sssd logs are already collected so I do not think we need a separate command:\r\n\r\nhttps://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L32-L33\r\nhttps://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L40\r\n\r\nThe `pcsc_scan` is a tool that is shipped in `pcsc-tools` package, which is available in EPEL only so I suggest to remove it:\r\n\r\nhttps://github.com/sosreport/sos/blob/b96926f151da984491de3082af7d06ecb07fc517/sos/report/plugins/smartcard.py#L34\r\n\r\nLet me know if this sounds ok to you or I should open a PR with the proposed changes.\r\n\r\nNote, that these are still needed for RHEL7, but I think for RHEL7 you have a different branch.\n", "before_files": [{"content": "# Copyright (C) 2007 Sadique Puthen <[email protected]>\n\n# This file is part of the sos project: https://github.com/sosreport/sos\n#\n# This copyrighted material is made available to anyone wishing to use,\n# modify, copy, or redistribute it subject to the terms and conditions of\n# version 2 of the GNU General Public License.\n#\n# See the LICENSE file in the source distribution for further information.\n\nfrom sos.report.plugins import Plugin, RedHatPlugin\n\n\nclass Smartcard(Plugin, RedHatPlugin):\n\n short_desc = 'PKCS#11 smart cards'\n\n plugin_name = 'smartcard'\n profiles = ('security', 'identity', 'hardware')\n\n files = ('/etc/pam_pkcs11/pam_pkcs11.conf',)\n packages = ('pam_pkcs11', 'pcsc-tools', 'opensc')\n\n def setup(self):\n self.add_copy_spec([\n \"/etc/reader.conf\",\n \"/etc/reader.conf.d/\",\n \"/etc/pam_pkcs11/\",\n \"/etc/opensc-*.conf\"\n ])\n self.add_cmd_output([\n \"pklogin_finder debug\",\n \"ls -nl /usr/lib*/pam_pkcs11/\",\n \"pcsc_scan\",\n \"pkcs11-tool --show-info\",\n \"pkcs11-tool --list-mechanisms\",\n \"pkcs11-tool --list-slots\",\n \"pkcs11-tool --list-objects\"\n ])\n self.add_forbidden_path(\"/etc/pam_pkcs11/nssdb/key[3-4].db\")\n\n# vim: set et ts=4 sw=4 :\n", "path": "sos/report/plugins/smartcard.py"}], "after_files": [{"content": "# Copyright (C) 2007 Sadique Puthen <[email protected]>\n\n# This file is part of the sos project: https://github.com/sosreport/sos\n#\n# This copyrighted material is made available to anyone wishing to use,\n# modify, copy, or redistribute it subject to the terms and conditions of\n# version 2 of the GNU General Public License.\n#\n# See the LICENSE file in the source distribution for further information.\n\nfrom sos.report.plugins import Plugin, RedHatPlugin\n\n\nclass Smartcard(Plugin, RedHatPlugin):\n\n short_desc = 'PKCS#11 smart cards'\n\n plugin_name = 'smartcard'\n profiles = ('security', 'identity', 'hardware')\n\n files = ('/etc/pam_pkcs11/pam_pkcs11.conf',)\n # The pam_pkcs11 is available only in RHEL7\n packages = ('pam_pkcs11', 'pcsc-tools', 'opensc', 'pcsc-lite',\n 'pcsc-lite-ccid')\n\n def setup(self):\n self.add_copy_spec([\n \"/etc/reader.conf\",\n \"/etc/reader.conf.d/\",\n \"/etc/pam_pkcs11/\",\n \"/etc/opensc-*.conf\",\n \"/etc/pkcs11/modules/*.module\",\n \"/usr/share/p11-kit/modules/*.module\"\n ])\n self.add_cmd_output([\n \"pklogin_finder debug\",\n \"ls -nl /usr/lib*/pam_pkcs11/\",\n \"pcsc_scan\",\n \"pkcs11-tool --show-info\",\n \"pkcs11-tool --list-mechanisms\",\n \"pkcs11-tool --list-slots\",\n \"pkcs11-tool --list-objects\"\n ])\n self.add_forbidden_path(\"/etc/pam_pkcs11/nssdb/key[3-4].db\")\n\n# vim: set et ts=4 sw=4 :\n", "path": "sos/report/plugins/smartcard.py"}]}
1,205
265
gh_patches_debug_43248
rasdani/github-patches
git_diff
qutebrowser__qutebrowser-1789
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- external editor 'gvim' under windows launches in read-only mode Hi There Today I found out, that a long missed feature existed all along. The external editor configured via `general/editor`. I assume I'm one of the first people actually using it with windows because when I tried to edit the file with gvim it always got opened in read-only mode. Naturally I wanted to try other editors and `notepad` turned out to be very helpful towards finding the cause. When trying to save the following message popped up: ``` The process cannot access the file because it is being used by another process. ``` I assume that the file is still open in python. A possible solution would be to close the file upon opening an external editor and reading it once the external editor gets closed. Thank you for this amazing project! troubas --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `qutebrowser/misc/editor.py` Content: ``` 1 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: 2 3 # Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]> 4 # 5 # This file is part of qutebrowser. 6 # 7 # qutebrowser 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 3 of the License, or 10 # (at your option) any later version. 11 # 12 # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. 19 20 """Launcher for an external editor.""" 21 22 import os 23 import tempfile 24 25 from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QProcess 26 27 from qutebrowser.config import config 28 from qutebrowser.utils import message, log 29 from qutebrowser.misc import guiprocess 30 31 32 class ExternalEditor(QObject): 33 34 """Class to simplify editing a text in an external editor. 35 36 Attributes: 37 _text: The current text before the editor is opened. 38 _oshandle: The OS level handle to the tmpfile. 39 _filehandle: The file handle to the tmpfile. 40 _proc: The GUIProcess of the editor. 41 _win_id: The window ID the ExternalEditor is associated with. 42 """ 43 44 editing_finished = pyqtSignal(str) 45 46 def __init__(self, win_id, parent=None): 47 super().__init__(parent) 48 self._text = None 49 self._oshandle = None 50 self._filename = None 51 self._proc = None 52 self._win_id = win_id 53 54 def _cleanup(self): 55 """Clean up temporary files after the editor closed.""" 56 if self._oshandle is None or self._filename is None: 57 # Could not create initial file. 58 return 59 try: 60 os.close(self._oshandle) 61 if self._proc.exit_status() != QProcess.CrashExit: 62 os.remove(self._filename) 63 except OSError as e: 64 # NOTE: Do not replace this with "raise CommandError" as it's 65 # executed async. 66 message.error(self._win_id, 67 "Failed to delete tempfile... ({})".format(e)) 68 69 @pyqtSlot(int, QProcess.ExitStatus) 70 def on_proc_closed(self, exitcode, exitstatus): 71 """Write the editor text into the form field and clean up tempfile. 72 73 Callback for QProcess when the editor was closed. 74 """ 75 log.procs.debug("Editor closed") 76 if exitstatus != QProcess.NormalExit: 77 # No error/cleanup here, since we already handle this in 78 # on_proc_error. 79 return 80 try: 81 if exitcode != 0: 82 return 83 encoding = config.get('general', 'editor-encoding') 84 try: 85 with open(self._filename, 'r', encoding=encoding) as f: 86 text = f.read() 87 except OSError as e: 88 # NOTE: Do not replace this with "raise CommandError" as it's 89 # executed async. 90 message.error(self._win_id, "Failed to read back edited file: " 91 "{}".format(e)) 92 return 93 log.procs.debug("Read back: {}".format(text)) 94 self.editing_finished.emit(text) 95 finally: 96 self._cleanup() 97 98 @pyqtSlot(QProcess.ProcessError) 99 def on_proc_error(self, _err): 100 self._cleanup() 101 102 def edit(self, text): 103 """Edit a given text. 104 105 Args: 106 text: The initial text to edit. 107 """ 108 if self._text is not None: 109 raise ValueError("Already editing a file!") 110 self._text = text 111 try: 112 self._oshandle, self._filename = tempfile.mkstemp( 113 text=True, prefix='qutebrowser-editor-') 114 if text: 115 encoding = config.get('general', 'editor-encoding') 116 with open(self._filename, 'w', encoding=encoding) as f: 117 f.write(text) 118 except OSError as e: 119 message.error(self._win_id, "Failed to create initial file: " 120 "{}".format(e)) 121 return 122 self._proc = guiprocess.GUIProcess(self._win_id, what='editor', 123 parent=self) 124 self._proc.finished.connect(self.on_proc_closed) 125 self._proc.error.connect(self.on_proc_error) 126 editor = config.get('general', 'editor') 127 executable = editor[0] 128 args = [arg.replace('{}', self._filename) for arg in editor[1:]] 129 log.procs.debug("Calling \"{}\" with args {}".format(executable, args)) 130 self._proc.start(executable, args) 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/qutebrowser/misc/editor.py b/qutebrowser/misc/editor.py --- a/qutebrowser/misc/editor.py +++ b/qutebrowser/misc/editor.py @@ -35,8 +35,8 @@ Attributes: _text: The current text before the editor is opened. - _oshandle: The OS level handle to the tmpfile. - _filehandle: The file handle to the tmpfile. + _file: The file handle as tempfile.NamedTemporaryFile. Note that this + handle will be closed after the initial file has been created. _proc: The GUIProcess of the editor. _win_id: The window ID the ExternalEditor is associated with. """ @@ -46,20 +46,18 @@ def __init__(self, win_id, parent=None): super().__init__(parent) self._text = None - self._oshandle = None - self._filename = None + self._file = None self._proc = None self._win_id = win_id def _cleanup(self): """Clean up temporary files after the editor closed.""" - if self._oshandle is None or self._filename is None: + if self._file is None: # Could not create initial file. return try: - os.close(self._oshandle) if self._proc.exit_status() != QProcess.CrashExit: - os.remove(self._filename) + os.remove(self._file.name) except OSError as e: # NOTE: Do not replace this with "raise CommandError" as it's # executed async. @@ -82,7 +80,7 @@ return encoding = config.get('general', 'editor-encoding') try: - with open(self._filename, 'r', encoding=encoding) as f: + with open(self._file.name, 'r', encoding=encoding) as f: text = f.read() except OSError as e: # NOTE: Do not replace this with "raise CommandError" as it's @@ -108,13 +106,18 @@ if self._text is not None: raise ValueError("Already editing a file!") self._text = text + encoding = config.get('general', 'editor-encoding') try: - self._oshandle, self._filename = tempfile.mkstemp( - text=True, prefix='qutebrowser-editor-') - if text: - encoding = config.get('general', 'editor-encoding') - with open(self._filename, 'w', encoding=encoding) as f: - f.write(text) + # Close while the external process is running, as otherwise systems + # with exclusive write access (e.g. Windows) may fail to update + # the file from the external editor, see + # https://github.com/The-Compiler/qutebrowser/issues/1767 + with tempfile.NamedTemporaryFile( + mode='w', prefix='qutebrowser-editor-', encoding=encoding, + delete=False) as fobj: + if text: + fobj.write(text) + self._file = fobj except OSError as e: message.error(self._win_id, "Failed to create initial file: " "{}".format(e)) @@ -125,6 +128,6 @@ self._proc.error.connect(self.on_proc_error) editor = config.get('general', 'editor') executable = editor[0] - args = [arg.replace('{}', self._filename) for arg in editor[1:]] + args = [arg.replace('{}', self._file.name) for arg in editor[1:]] log.procs.debug("Calling \"{}\" with args {}".format(executable, args)) self._proc.start(executable, args)
{"golden_diff": "diff --git a/qutebrowser/misc/editor.py b/qutebrowser/misc/editor.py\n--- a/qutebrowser/misc/editor.py\n+++ b/qutebrowser/misc/editor.py\n@@ -35,8 +35,8 @@\n \n Attributes:\n _text: The current text before the editor is opened.\n- _oshandle: The OS level handle to the tmpfile.\n- _filehandle: The file handle to the tmpfile.\n+ _file: The file handle as tempfile.NamedTemporaryFile. Note that this\n+ handle will be closed after the initial file has been created.\n _proc: The GUIProcess of the editor.\n _win_id: The window ID the ExternalEditor is associated with.\n \"\"\"\n@@ -46,20 +46,18 @@\n def __init__(self, win_id, parent=None):\n super().__init__(parent)\n self._text = None\n- self._oshandle = None\n- self._filename = None\n+ self._file = None\n self._proc = None\n self._win_id = win_id\n \n def _cleanup(self):\n \"\"\"Clean up temporary files after the editor closed.\"\"\"\n- if self._oshandle is None or self._filename is None:\n+ if self._file is None:\n # Could not create initial file.\n return\n try:\n- os.close(self._oshandle)\n if self._proc.exit_status() != QProcess.CrashExit:\n- os.remove(self._filename)\n+ os.remove(self._file.name)\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n # executed async.\n@@ -82,7 +80,7 @@\n return\n encoding = config.get('general', 'editor-encoding')\n try:\n- with open(self._filename, 'r', encoding=encoding) as f:\n+ with open(self._file.name, 'r', encoding=encoding) as f:\n text = f.read()\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n@@ -108,13 +106,18 @@\n if self._text is not None:\n raise ValueError(\"Already editing a file!\")\n self._text = text\n+ encoding = config.get('general', 'editor-encoding')\n try:\n- self._oshandle, self._filename = tempfile.mkstemp(\n- text=True, prefix='qutebrowser-editor-')\n- if text:\n- encoding = config.get('general', 'editor-encoding')\n- with open(self._filename, 'w', encoding=encoding) as f:\n- f.write(text)\n+ # Close while the external process is running, as otherwise systems\n+ # with exclusive write access (e.g. Windows) may fail to update\n+ # the file from the external editor, see\n+ # https://github.com/The-Compiler/qutebrowser/issues/1767\n+ with tempfile.NamedTemporaryFile(\n+ mode='w', prefix='qutebrowser-editor-', encoding=encoding,\n+ delete=False) as fobj:\n+ if text:\n+ fobj.write(text)\n+ self._file = fobj\n except OSError as e:\n message.error(self._win_id, \"Failed to create initial file: \"\n \"{}\".format(e))\n@@ -125,6 +128,6 @@\n self._proc.error.connect(self.on_proc_error)\n editor = config.get('general', 'editor')\n executable = editor[0]\n- args = [arg.replace('{}', self._filename) for arg in editor[1:]]\n+ args = [arg.replace('{}', self._file.name) for arg in editor[1:]]\n log.procs.debug(\"Calling \\\"{}\\\" with args {}\".format(executable, args))\n self._proc.start(executable, args)\n", "issue": "external editor 'gvim' under windows launches in read-only mode\nHi There\n\nToday I found out, that a long missed feature existed all along. The external editor configured via `general/editor`.\n\nI assume I'm one of the first people actually using it with windows because when I tried to edit the file with gvim it always got opened in read-only mode. Naturally I wanted to try other editors and `notepad` turned out to be very helpful towards finding the cause. When trying to save the following message popped up:\n\n```\nThe process cannot access the file because it is being used by another process.\n```\n\nI assume that the file is still open in python. A possible solution would be to close the file upon opening an external editor and reading it once the external editor gets closed.\n\nThank you for this amazing project!\ntroubas\n\n", "before_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General 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# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"Launcher for an external editor.\"\"\"\n\nimport os\nimport tempfile\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QProcess\n\nfrom qutebrowser.config import config\nfrom qutebrowser.utils import message, log\nfrom qutebrowser.misc import guiprocess\n\n\nclass ExternalEditor(QObject):\n\n \"\"\"Class to simplify editing a text in an external editor.\n\n Attributes:\n _text: The current text before the editor is opened.\n _oshandle: The OS level handle to the tmpfile.\n _filehandle: The file handle to the tmpfile.\n _proc: The GUIProcess of the editor.\n _win_id: The window ID the ExternalEditor is associated with.\n \"\"\"\n\n editing_finished = pyqtSignal(str)\n\n def __init__(self, win_id, parent=None):\n super().__init__(parent)\n self._text = None\n self._oshandle = None\n self._filename = None\n self._proc = None\n self._win_id = win_id\n\n def _cleanup(self):\n \"\"\"Clean up temporary files after the editor closed.\"\"\"\n if self._oshandle is None or self._filename is None:\n # Could not create initial file.\n return\n try:\n os.close(self._oshandle)\n if self._proc.exit_status() != QProcess.CrashExit:\n os.remove(self._filename)\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n # executed async.\n message.error(self._win_id,\n \"Failed to delete tempfile... ({})\".format(e))\n\n @pyqtSlot(int, QProcess.ExitStatus)\n def on_proc_closed(self, exitcode, exitstatus):\n \"\"\"Write the editor text into the form field and clean up tempfile.\n\n Callback for QProcess when the editor was closed.\n \"\"\"\n log.procs.debug(\"Editor closed\")\n if exitstatus != QProcess.NormalExit:\n # No error/cleanup here, since we already handle this in\n # on_proc_error.\n return\n try:\n if exitcode != 0:\n return\n encoding = config.get('general', 'editor-encoding')\n try:\n with open(self._filename, 'r', encoding=encoding) as f:\n text = f.read()\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n # executed async.\n message.error(self._win_id, \"Failed to read back edited file: \"\n \"{}\".format(e))\n return\n log.procs.debug(\"Read back: {}\".format(text))\n self.editing_finished.emit(text)\n finally:\n self._cleanup()\n\n @pyqtSlot(QProcess.ProcessError)\n def on_proc_error(self, _err):\n self._cleanup()\n\n def edit(self, text):\n \"\"\"Edit a given text.\n\n Args:\n text: The initial text to edit.\n \"\"\"\n if self._text is not None:\n raise ValueError(\"Already editing a file!\")\n self._text = text\n try:\n self._oshandle, self._filename = tempfile.mkstemp(\n text=True, prefix='qutebrowser-editor-')\n if text:\n encoding = config.get('general', 'editor-encoding')\n with open(self._filename, 'w', encoding=encoding) as f:\n f.write(text)\n except OSError as e:\n message.error(self._win_id, \"Failed to create initial file: \"\n \"{}\".format(e))\n return\n self._proc = guiprocess.GUIProcess(self._win_id, what='editor',\n parent=self)\n self._proc.finished.connect(self.on_proc_closed)\n self._proc.error.connect(self.on_proc_error)\n editor = config.get('general', 'editor')\n executable = editor[0]\n args = [arg.replace('{}', self._filename) for arg in editor[1:]]\n log.procs.debug(\"Calling \\\"{}\\\" with args {}\".format(executable, args))\n self._proc.start(executable, args)\n", "path": "qutebrowser/misc/editor.py"}], "after_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General 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# qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"Launcher for an external editor.\"\"\"\n\nimport os\nimport tempfile\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QProcess\n\nfrom qutebrowser.config import config\nfrom qutebrowser.utils import message, log\nfrom qutebrowser.misc import guiprocess\n\n\nclass ExternalEditor(QObject):\n\n \"\"\"Class to simplify editing a text in an external editor.\n\n Attributes:\n _text: The current text before the editor is opened.\n _file: The file handle as tempfile.NamedTemporaryFile. Note that this\n handle will be closed after the initial file has been created.\n _proc: The GUIProcess of the editor.\n _win_id: The window ID the ExternalEditor is associated with.\n \"\"\"\n\n editing_finished = pyqtSignal(str)\n\n def __init__(self, win_id, parent=None):\n super().__init__(parent)\n self._text = None\n self._file = None\n self._proc = None\n self._win_id = win_id\n\n def _cleanup(self):\n \"\"\"Clean up temporary files after the editor closed.\"\"\"\n if self._file is None:\n # Could not create initial file.\n return\n try:\n if self._proc.exit_status() != QProcess.CrashExit:\n os.remove(self._file.name)\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n # executed async.\n message.error(self._win_id,\n \"Failed to delete tempfile... ({})\".format(e))\n\n @pyqtSlot(int, QProcess.ExitStatus)\n def on_proc_closed(self, exitcode, exitstatus):\n \"\"\"Write the editor text into the form field and clean up tempfile.\n\n Callback for QProcess when the editor was closed.\n \"\"\"\n log.procs.debug(\"Editor closed\")\n if exitstatus != QProcess.NormalExit:\n # No error/cleanup here, since we already handle this in\n # on_proc_error.\n return\n try:\n if exitcode != 0:\n return\n encoding = config.get('general', 'editor-encoding')\n try:\n with open(self._file.name, 'r', encoding=encoding) as f:\n text = f.read()\n except OSError as e:\n # NOTE: Do not replace this with \"raise CommandError\" as it's\n # executed async.\n message.error(self._win_id, \"Failed to read back edited file: \"\n \"{}\".format(e))\n return\n log.procs.debug(\"Read back: {}\".format(text))\n self.editing_finished.emit(text)\n finally:\n self._cleanup()\n\n @pyqtSlot(QProcess.ProcessError)\n def on_proc_error(self, _err):\n self._cleanup()\n\n def edit(self, text):\n \"\"\"Edit a given text.\n\n Args:\n text: The initial text to edit.\n \"\"\"\n if self._text is not None:\n raise ValueError(\"Already editing a file!\")\n self._text = text\n encoding = config.get('general', 'editor-encoding')\n try:\n # Close while the external process is running, as otherwise systems\n # with exclusive write access (e.g. Windows) may fail to update\n # the file from the external editor, see\n # https://github.com/The-Compiler/qutebrowser/issues/1767\n with tempfile.NamedTemporaryFile(\n mode='w', prefix='qutebrowser-editor-', encoding=encoding,\n delete=False) as fobj:\n if text:\n fobj.write(text)\n self._file = fobj\n except OSError as e:\n message.error(self._win_id, \"Failed to create initial file: \"\n \"{}\".format(e))\n return\n self._proc = guiprocess.GUIProcess(self._win_id, what='editor',\n parent=self)\n self._proc.finished.connect(self.on_proc_closed)\n self._proc.error.connect(self.on_proc_error)\n editor = config.get('general', 'editor')\n executable = editor[0]\n args = [arg.replace('{}', self._file.name) for arg in editor[1:]]\n log.procs.debug(\"Calling \\\"{}\\\" with args {}\".format(executable, args))\n self._proc.start(executable, args)\n", "path": "qutebrowser/misc/editor.py"}]}
1,801
854
gh_patches_debug_4924
rasdani/github-patches
git_diff
saleor__saleor-1604
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Promotional code field and button overlap each other. In the checkout process: <img width="465" alt="zrzut ekranu 2018-01-10 o 10 02 22" src="https://user-images.githubusercontent.com/1561204/34765559-24865056-f5f2-11e7-9e2a-d0ff639e7a79.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: `saleor/discount/forms.py` Content: ``` 1 from datetime import date 2 3 from django import forms 4 from django.utils.encoding import smart_text 5 from django.utils.translation import pgettext_lazy 6 7 from .models import NotApplicable, Voucher 8 9 10 class VoucherField(forms.ModelChoiceField): 11 12 default_error_messages = { 13 'invalid_choice': pgettext_lazy( 14 'voucher', pgettext_lazy( 15 'Voucher form error', 'Discount code incorrect or expired')), 16 } 17 18 19 class CheckoutDiscountForm(forms.Form): 20 21 voucher = VoucherField( 22 queryset=Voucher.objects.none(), 23 to_field_name='code', 24 label=pgettext_lazy( 25 'Checkout discount form label for voucher field', 26 'Gift card or discount code'), 27 widget=forms.TextInput) 28 29 def __init__(self, *args, **kwargs): 30 self.checkout = kwargs.pop('checkout') 31 initial = kwargs.get('initial', {}) 32 if 'voucher' not in initial: 33 initial['voucher'] = self.checkout.voucher_code 34 kwargs['initial'] = initial 35 super().__init__(*args, **kwargs) 36 self.fields['voucher'].queryset = Voucher.objects.active( 37 date=date.today()) 38 39 def clean(self): 40 cleaned_data = super().clean() 41 if 'voucher' in cleaned_data: 42 voucher = cleaned_data['voucher'] 43 try: 44 discount = voucher.get_discount_for_checkout(self.checkout) 45 cleaned_data['discount'] = discount 46 except NotApplicable as e: 47 self.add_error('voucher', smart_text(e)) 48 return cleaned_data 49 50 def apply_discount(self): 51 discount = self.cleaned_data['discount'] 52 voucher = self.cleaned_data['voucher'] 53 self.checkout.discount = discount 54 self.checkout.voucher_code = voucher.code 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/saleor/discount/forms.py b/saleor/discount/forms.py --- a/saleor/discount/forms.py +++ b/saleor/discount/forms.py @@ -21,7 +21,7 @@ voucher = VoucherField( queryset=Voucher.objects.none(), to_field_name='code', - label=pgettext_lazy( + help_text=pgettext_lazy( 'Checkout discount form label for voucher field', 'Gift card or discount code'), widget=forms.TextInput)
{"golden_diff": "diff --git a/saleor/discount/forms.py b/saleor/discount/forms.py\n--- a/saleor/discount/forms.py\n+++ b/saleor/discount/forms.py\n@@ -21,7 +21,7 @@\n voucher = VoucherField(\n queryset=Voucher.objects.none(),\n to_field_name='code',\n- label=pgettext_lazy(\n+ help_text=pgettext_lazy(\n 'Checkout discount form label for voucher field',\n 'Gift card or discount code'),\n widget=forms.TextInput)\n", "issue": "Promotional code field and button overlap each other.\nIn the checkout process:\r\n<img width=\"465\" alt=\"zrzut ekranu 2018-01-10 o 10 02 22\" src=\"https://user-images.githubusercontent.com/1561204/34765559-24865056-f5f2-11e7-9e2a-d0ff639e7a79.png\">\r\n\n", "before_files": [{"content": "from datetime import date\n\nfrom django import forms\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import pgettext_lazy\n\nfrom .models import NotApplicable, Voucher\n\n\nclass VoucherField(forms.ModelChoiceField):\n\n default_error_messages = {\n 'invalid_choice': pgettext_lazy(\n 'voucher', pgettext_lazy(\n 'Voucher form error', 'Discount code incorrect or expired')),\n }\n\n\nclass CheckoutDiscountForm(forms.Form):\n\n voucher = VoucherField(\n queryset=Voucher.objects.none(),\n to_field_name='code',\n label=pgettext_lazy(\n 'Checkout discount form label for voucher field',\n 'Gift card or discount code'),\n widget=forms.TextInput)\n\n def __init__(self, *args, **kwargs):\n self.checkout = kwargs.pop('checkout')\n initial = kwargs.get('initial', {})\n if 'voucher' not in initial:\n initial['voucher'] = self.checkout.voucher_code\n kwargs['initial'] = initial\n super().__init__(*args, **kwargs)\n self.fields['voucher'].queryset = Voucher.objects.active(\n date=date.today())\n\n def clean(self):\n cleaned_data = super().clean()\n if 'voucher' in cleaned_data:\n voucher = cleaned_data['voucher']\n try:\n discount = voucher.get_discount_for_checkout(self.checkout)\n cleaned_data['discount'] = discount\n except NotApplicable as e:\n self.add_error('voucher', smart_text(e))\n return cleaned_data\n\n def apply_discount(self):\n discount = self.cleaned_data['discount']\n voucher = self.cleaned_data['voucher']\n self.checkout.discount = discount\n self.checkout.voucher_code = voucher.code\n", "path": "saleor/discount/forms.py"}], "after_files": [{"content": "from datetime import date\n\nfrom django import forms\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import pgettext_lazy\n\nfrom .models import NotApplicable, Voucher\n\n\nclass VoucherField(forms.ModelChoiceField):\n\n default_error_messages = {\n 'invalid_choice': pgettext_lazy(\n 'voucher', pgettext_lazy(\n 'Voucher form error', 'Discount code incorrect or expired')),\n }\n\n\nclass CheckoutDiscountForm(forms.Form):\n\n voucher = VoucherField(\n queryset=Voucher.objects.none(),\n to_field_name='code',\n help_text=pgettext_lazy(\n 'Checkout discount form label for voucher field',\n 'Gift card or discount code'),\n widget=forms.TextInput)\n\n def __init__(self, *args, **kwargs):\n self.checkout = kwargs.pop('checkout')\n initial = kwargs.get('initial', {})\n if 'voucher' not in initial:\n initial['voucher'] = self.checkout.voucher_code\n kwargs['initial'] = initial\n super().__init__(*args, **kwargs)\n self.fields['voucher'].queryset = Voucher.objects.active(\n date=date.today())\n\n def clean(self):\n cleaned_data = super().clean()\n if 'voucher' in cleaned_data:\n voucher = cleaned_data['voucher']\n try:\n discount = voucher.get_discount_for_checkout(self.checkout)\n cleaned_data['discount'] = discount\n except NotApplicable as e:\n self.add_error('voucher', smart_text(e))\n return cleaned_data\n\n def apply_discount(self):\n discount = self.cleaned_data['discount']\n voucher = self.cleaned_data['voucher']\n self.checkout.discount = discount\n self.checkout.voucher_code = voucher.code\n", "path": "saleor/discount/forms.py"}]}
843
112
gh_patches_debug_31936
rasdani/github-patches
git_diff
WordPress__openverse-api-210
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [Feature] Add new Authority Type ## Problem <!-- Describe a problem solved by this feature; or delete the section entirely. --> We currently lack an authority type for curated image galleries: places like https://stocksnap.io where content is manually curated by the platform, but it isn't a site with social, user-uploaded content, or isn't a formal GLAM institution. ## Description <!-- Describe the feature and how it solves the problem. --> Our current authorities: https://github.com/WordPress/openverse-api/blob/9d0d724651f18cc9f96931e01bea92b8032bd6a0/ingestion_server/ingestion_server/authority.py#L32-L36 Should be modified to: ```diff boost = { - AuthorityTypes.CURATED: 90, + AuthorityTypes.CURATED: 87.5, + AuthorityTypes.CULTURAL_INSTITUTIONS: 90, AuthorityTypes.SOCIAL_MEDIA: 80, AuthorityTypes.DEFAULT: 85 } ``` We'll also need to re-classify the existing providers classified as `CURATED` to `CULTURAL_INSTITUTIONS` and add a line for StockSnap here (we might also want to sort these alphabetically): https://github.com/WordPress/openverse-api/blob/9d0d724651f18cc9f96931e01bea92b8032bd6a0/ingestion_server/ingestion_server/authority.py#L37-L53 ## Alternatives <!-- Describe any alternative solutions or features you have considered. How is this feature better? --> ## Additional context <!-- Add any other context about the feature here; or delete the section entirely. --> ## Implementation <!-- Replace the [ ] with [x] to check the box. --> - [ ] 🙋 I would be interested in implementing this feature. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `ingestion_server/ingestion_server/authority.py` Content: ``` 1 from enum import Enum, auto 2 3 4 """ 5 Authority is a ranking from 0 to 100 (with 0 being least authoritative) 6 indicating the pedigree of an image. Some examples of things that could impact 7 authority: 8 - The reputation of the website that posted an image 9 - The popularity of the uploader on a social media site in terms of number of 10 followers 11 - Whether the uploader has uploaded images that have previously been flagged for 12 copyright infringement. 13 - etc 14 15 The authority can be set from the catalog layer through the meta_data field 16 or through the ingestion layer. As of now, we are only factoring in the 17 reputation of the website as a static hand-picked list based on experience 18 and search result quality, with the intention to add more sophisticated and 19 tailored measures of authority later on. 20 21 Also note that this is just one factor in rankings, and the magnitude of the 22 boost can be adjusted at search-time. 23 """ 24 25 26 class AuthorityTypes(Enum): 27 CURATED = auto() 28 SOCIAL_MEDIA = auto() 29 DEFAULT = auto() 30 31 32 # We want to boost curated collections where each image has been vetted for 33 # cultural significance. 34 boost = { 35 AuthorityTypes.CURATED: 90, 36 AuthorityTypes.SOCIAL_MEDIA: 80, 37 AuthorityTypes.DEFAULT: 85, 38 } 39 authority_types = { 40 "flickr": AuthorityTypes.SOCIAL_MEDIA, 41 "behance": AuthorityTypes.SOCIAL_MEDIA, 42 "thingiverse": AuthorityTypes.SOCIAL_MEDIA, 43 "sketchfab": AuthorityTypes.SOCIAL_MEDIA, 44 "deviantart": AuthorityTypes.SOCIAL_MEDIA, 45 "thorvaldsensmuseum": AuthorityTypes.CURATED, 46 "svgsilh": AuthorityTypes.CURATED, 47 "smithsonian": AuthorityTypes.CURATED, 48 "rijksmuseum": AuthorityTypes.CURATED, 49 "museumsvictoria": AuthorityTypes.CURATED, 50 "met": AuthorityTypes.CURATED, 51 "mccordsmuseum": AuthorityTypes.CURATED, 52 "digitaltmuseum": AuthorityTypes.CURATED, 53 "clevelandmuseum": AuthorityTypes.CURATED, 54 "brooklynmuseum": AuthorityTypes.CURATED, 55 } 56 57 58 def get_authority_boost(source): 59 authority_boost = None 60 if source in authority_types: 61 authority_type = authority_types[source] 62 if authority_type in boost: 63 authority_boost = boost[authority_type] 64 else: 65 authority_boost = boost[AuthorityTypes.DEFAULT] 66 return authority_boost 67 ``` --- 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/ingestion_server/ingestion_server/authority.py b/ingestion_server/ingestion_server/authority.py --- a/ingestion_server/ingestion_server/authority.py +++ b/ingestion_server/ingestion_server/authority.py @@ -25,6 +25,7 @@ class AuthorityTypes(Enum): CURATED = auto() + CULTURAL_INSTITUTION = auto() SOCIAL_MEDIA = auto() DEFAULT = auto() @@ -32,26 +33,29 @@ # We want to boost curated collections where each image has been vetted for # cultural significance. boost = { - AuthorityTypes.CURATED: 90, - AuthorityTypes.SOCIAL_MEDIA: 80, - AuthorityTypes.DEFAULT: 85, + AuthorityTypes.CURATED: 85, + AuthorityTypes.CULTURAL_INSTITUTION: 90, + AuthorityTypes.SOCIAL_MEDIA: 75, + AuthorityTypes.DEFAULT: 80, } + authority_types = { "flickr": AuthorityTypes.SOCIAL_MEDIA, "behance": AuthorityTypes.SOCIAL_MEDIA, "thingiverse": AuthorityTypes.SOCIAL_MEDIA, "sketchfab": AuthorityTypes.SOCIAL_MEDIA, "deviantart": AuthorityTypes.SOCIAL_MEDIA, - "thorvaldsensmuseum": AuthorityTypes.CURATED, - "svgsilh": AuthorityTypes.CURATED, - "smithsonian": AuthorityTypes.CURATED, - "rijksmuseum": AuthorityTypes.CURATED, - "museumsvictoria": AuthorityTypes.CURATED, - "met": AuthorityTypes.CURATED, - "mccordsmuseum": AuthorityTypes.CURATED, - "digitaltmuseum": AuthorityTypes.CURATED, - "clevelandmuseum": AuthorityTypes.CURATED, - "brooklynmuseum": AuthorityTypes.CURATED, + "thorvaldsensmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "svgsilh": AuthorityTypes.CULTURAL_INSTITUTION, + "smithsonian": AuthorityTypes.CULTURAL_INSTITUTION, + "rijksmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "museumsvictoria": AuthorityTypes.CULTURAL_INSTITUTION, + "met": AuthorityTypes.CULTURAL_INSTITUTION, + "mccordsmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "digitaltmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "clevelandmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "brooklynmuseum": AuthorityTypes.CULTURAL_INSTITUTION, + "stocksnap": AuthorityTypes.CURATED, }
{"golden_diff": "diff --git a/ingestion_server/ingestion_server/authority.py b/ingestion_server/ingestion_server/authority.py\n--- a/ingestion_server/ingestion_server/authority.py\n+++ b/ingestion_server/ingestion_server/authority.py\n@@ -25,6 +25,7 @@\n \n class AuthorityTypes(Enum):\n CURATED = auto()\n+ CULTURAL_INSTITUTION = auto()\n SOCIAL_MEDIA = auto()\n DEFAULT = auto()\n \n@@ -32,26 +33,29 @@\n # We want to boost curated collections where each image has been vetted for\n # cultural significance.\n boost = {\n- AuthorityTypes.CURATED: 90,\n- AuthorityTypes.SOCIAL_MEDIA: 80,\n- AuthorityTypes.DEFAULT: 85,\n+ AuthorityTypes.CURATED: 85,\n+ AuthorityTypes.CULTURAL_INSTITUTION: 90,\n+ AuthorityTypes.SOCIAL_MEDIA: 75,\n+ AuthorityTypes.DEFAULT: 80,\n }\n+\n authority_types = {\n \"flickr\": AuthorityTypes.SOCIAL_MEDIA,\n \"behance\": AuthorityTypes.SOCIAL_MEDIA,\n \"thingiverse\": AuthorityTypes.SOCIAL_MEDIA,\n \"sketchfab\": AuthorityTypes.SOCIAL_MEDIA,\n \"deviantart\": AuthorityTypes.SOCIAL_MEDIA,\n- \"thorvaldsensmuseum\": AuthorityTypes.CURATED,\n- \"svgsilh\": AuthorityTypes.CURATED,\n- \"smithsonian\": AuthorityTypes.CURATED,\n- \"rijksmuseum\": AuthorityTypes.CURATED,\n- \"museumsvictoria\": AuthorityTypes.CURATED,\n- \"met\": AuthorityTypes.CURATED,\n- \"mccordsmuseum\": AuthorityTypes.CURATED,\n- \"digitaltmuseum\": AuthorityTypes.CURATED,\n- \"clevelandmuseum\": AuthorityTypes.CURATED,\n- \"brooklynmuseum\": AuthorityTypes.CURATED,\n+ \"thorvaldsensmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"svgsilh\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"smithsonian\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"rijksmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"museumsvictoria\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"met\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"mccordsmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"digitaltmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"clevelandmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"brooklynmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n+ \"stocksnap\": AuthorityTypes.CURATED,\n }\n", "issue": "[Feature] Add new Authority Type\n## Problem\r\n<!-- Describe a problem solved by this feature; or delete the section entirely. -->\r\n\r\nWe currently lack an authority type for curated image galleries: places like https://stocksnap.io where content is manually curated by the platform, but it isn't a site with social, user-uploaded content, or isn't a formal GLAM institution.\r\n\r\n## Description\r\n<!-- Describe the feature and how it solves the problem. -->\r\n\r\nOur current authorities:\r\n\r\nhttps://github.com/WordPress/openverse-api/blob/9d0d724651f18cc9f96931e01bea92b8032bd6a0/ingestion_server/ingestion_server/authority.py#L32-L36\r\n\r\nShould be modified to:\r\n\r\n\r\n```diff\r\nboost = {\r\n- AuthorityTypes.CURATED: 90,\r\n+ AuthorityTypes.CURATED: 87.5,\r\n+ AuthorityTypes.CULTURAL_INSTITUTIONS: 90,\r\n AuthorityTypes.SOCIAL_MEDIA: 80,\r\n AuthorityTypes.DEFAULT: 85\r\n}\r\n```\r\n\r\nWe'll also need to re-classify the existing providers classified as `CURATED` to `CULTURAL_INSTITUTIONS` and add a line for StockSnap here (we might also want to sort these alphabetically):\r\n\r\nhttps://github.com/WordPress/openverse-api/blob/9d0d724651f18cc9f96931e01bea92b8032bd6a0/ingestion_server/ingestion_server/authority.py#L37-L53\r\n\r\n\r\n\r\n## Alternatives\r\n<!-- Describe any alternative solutions or features you have considered. How is this feature better? -->\r\n\r\n## Additional context\r\n<!-- Add any other context about the feature here; or delete the section entirely. -->\r\n\r\n## Implementation\r\n<!-- Replace the [ ] with [x] to check the box. -->\r\n- [ ] \ud83d\ude4b I would be interested in implementing this feature.\r\n\n", "before_files": [{"content": "from enum import Enum, auto\n\n\n\"\"\"\nAuthority is a ranking from 0 to 100 (with 0 being least authoritative)\nindicating the pedigree of an image. Some examples of things that could impact\nauthority:\n- The reputation of the website that posted an image\n- The popularity of the uploader on a social media site in terms of number of\nfollowers\n- Whether the uploader has uploaded images that have previously been flagged for\ncopyright infringement.\n- etc\n\nThe authority can be set from the catalog layer through the meta_data field\nor through the ingestion layer. As of now, we are only factoring in the\nreputation of the website as a static hand-picked list based on experience\nand search result quality, with the intention to add more sophisticated and\ntailored measures of authority later on.\n\nAlso note that this is just one factor in rankings, and the magnitude of the\nboost can be adjusted at search-time.\n\"\"\"\n\n\nclass AuthorityTypes(Enum):\n CURATED = auto()\n SOCIAL_MEDIA = auto()\n DEFAULT = auto()\n\n\n# We want to boost curated collections where each image has been vetted for\n# cultural significance.\nboost = {\n AuthorityTypes.CURATED: 90,\n AuthorityTypes.SOCIAL_MEDIA: 80,\n AuthorityTypes.DEFAULT: 85,\n}\nauthority_types = {\n \"flickr\": AuthorityTypes.SOCIAL_MEDIA,\n \"behance\": AuthorityTypes.SOCIAL_MEDIA,\n \"thingiverse\": AuthorityTypes.SOCIAL_MEDIA,\n \"sketchfab\": AuthorityTypes.SOCIAL_MEDIA,\n \"deviantart\": AuthorityTypes.SOCIAL_MEDIA,\n \"thorvaldsensmuseum\": AuthorityTypes.CURATED,\n \"svgsilh\": AuthorityTypes.CURATED,\n \"smithsonian\": AuthorityTypes.CURATED,\n \"rijksmuseum\": AuthorityTypes.CURATED,\n \"museumsvictoria\": AuthorityTypes.CURATED,\n \"met\": AuthorityTypes.CURATED,\n \"mccordsmuseum\": AuthorityTypes.CURATED,\n \"digitaltmuseum\": AuthorityTypes.CURATED,\n \"clevelandmuseum\": AuthorityTypes.CURATED,\n \"brooklynmuseum\": AuthorityTypes.CURATED,\n}\n\n\ndef get_authority_boost(source):\n authority_boost = None\n if source in authority_types:\n authority_type = authority_types[source]\n if authority_type in boost:\n authority_boost = boost[authority_type]\n else:\n authority_boost = boost[AuthorityTypes.DEFAULT]\n return authority_boost\n", "path": "ingestion_server/ingestion_server/authority.py"}], "after_files": [{"content": "from enum import Enum, auto\n\n\n\"\"\"\nAuthority is a ranking from 0 to 100 (with 0 being least authoritative)\nindicating the pedigree of an image. Some examples of things that could impact\nauthority:\n- The reputation of the website that posted an image\n- The popularity of the uploader on a social media site in terms of number of\nfollowers\n- Whether the uploader has uploaded images that have previously been flagged for\ncopyright infringement.\n- etc\n\nThe authority can be set from the catalog layer through the meta_data field\nor through the ingestion layer. As of now, we are only factoring in the\nreputation of the website as a static hand-picked list based on experience\nand search result quality, with the intention to add more sophisticated and\ntailored measures of authority later on.\n\nAlso note that this is just one factor in rankings, and the magnitude of the\nboost can be adjusted at search-time.\n\"\"\"\n\n\nclass AuthorityTypes(Enum):\n CURATED = auto()\n CULTURAL_INSTITUTION = auto()\n SOCIAL_MEDIA = auto()\n DEFAULT = auto()\n\n\n# We want to boost curated collections where each image has been vetted for\n# cultural significance.\nboost = {\n AuthorityTypes.CURATED: 85,\n AuthorityTypes.CULTURAL_INSTITUTION: 90,\n AuthorityTypes.SOCIAL_MEDIA: 75,\n AuthorityTypes.DEFAULT: 80,\n}\n\nauthority_types = {\n \"flickr\": AuthorityTypes.SOCIAL_MEDIA,\n \"behance\": AuthorityTypes.SOCIAL_MEDIA,\n \"thingiverse\": AuthorityTypes.SOCIAL_MEDIA,\n \"sketchfab\": AuthorityTypes.SOCIAL_MEDIA,\n \"deviantart\": AuthorityTypes.SOCIAL_MEDIA,\n \"thorvaldsensmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"svgsilh\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"smithsonian\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"rijksmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"museumsvictoria\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"met\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"mccordsmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"digitaltmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"clevelandmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"brooklynmuseum\": AuthorityTypes.CULTURAL_INSTITUTION,\n \"stocksnap\": AuthorityTypes.CURATED,\n}\n\n\ndef get_authority_boost(source):\n authority_boost = None\n if source in authority_types:\n authority_type = authority_types[source]\n if authority_type in boost:\n authority_boost = boost[authority_type]\n else:\n authority_boost = boost[AuthorityTypes.DEFAULT]\n return authority_boost\n", "path": "ingestion_server/ingestion_server/authority.py"}]}
1,357
614
gh_patches_debug_1353
rasdani/github-patches
git_diff
microsoft__Qcodes-87
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- PR #70 breaks parameter .get and .set functionality I cannot debug the issue properly because all the objects are `multiprocessing` objects. A minimal example showing the issue: ``` python %matplotlib nbagg import matplotlib.pyplot as plt import time import numpy as np import qcodes as qc from toymodel import AModel, MockGates, MockSource, MockMeter, AverageGetter, AverageAndRaw # now create this "experiment" model = AModel() gates = MockGates('gates', model=model) c0, c1, c2 = gates.chan0, gates.chan1, gates.chan2 print('fine so far...') print('error...') c2.get() print('no effect?') c2.set(0.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: `docs/examples/toymodel.py` Content: ``` 1 # code for example notebook 2 3 import math 4 5 from qcodes import MockInstrument, MockModel, Parameter, Loop, DataArray 6 from qcodes.utils.validators import Numbers 7 8 9 class AModel(MockModel): 10 def __init__(self): 11 self._gates = [0.0, 0.0, 0.0] 12 self._excitation = 0.1 13 super().__init__() 14 15 def _output(self): 16 # my super exciting model! 17 # make a nice pattern that looks sort of double-dotty 18 # with the first two gates controlling the two dots, 19 # and the third looking like Vsd 20 delta_i = 10 21 delta_j = 10 22 di = (self._gates[0] + delta_i / 2) % delta_i - delta_i / 2 23 dj = (self._gates[1] + delta_j / 2) % delta_j - delta_j / 2 24 vsd = math.sqrt(self._gates[2]**2 + self._excitation**2) 25 dij = math.sqrt(di**2 + dj**2) - vsd 26 g = (vsd**2 + 1) * (1 / (dij**2 + 1) + 27 0.1 * (math.atan(-dij) + math.pi / 2)) 28 return g 29 30 def fmt(self, value): 31 return '{:.3f}'.format(value) 32 33 def gates_set(self, parameter, value): 34 if parameter[0] == 'c': 35 self._gates[int(parameter[1:])] = float(value) 36 elif parameter == 'rst' and value is None: 37 self._gates = [0.0, 0.0, 0.0] 38 else: 39 raise ValueError 40 41 def gates_get(self, parameter): 42 if parameter[0] == 'c': 43 return self.fmt(self.gates[int(parameter[1:])]) 44 else: 45 raise ValueError 46 47 def source_set(self, parameter, value): 48 if parameter == 'ampl': 49 self._excitation = float(value) 50 else: 51 raise ValueError 52 53 def source_get(self, parameter): 54 if parameter == 'ampl': 55 return self.fmt(self._excitation) 56 else: 57 raise ValueError 58 59 def meter_get(self, parameter): 60 if parameter == 'ampl': 61 return self.fmt(self._output() * self._excitation) 62 else: 63 raise ValueError 64 65 66 # make our mock instruments 67 # real instruments would subclass IPInstrument or VisaInstrument 68 # or just the base Instrument instead of MockInstrument, 69 # and be instantiated with an address rather than a model 70 class MockGates(MockInstrument): 71 def __init__(self, name, model=None, **kwargs): 72 super().__init__(name, model=model, **kwargs) 73 74 for i in range(3): 75 cmdbase = 'c{}'.format(i) 76 self.add_parameter('chan{}'.format(i), 77 label='Gate Channel {} (mV)'.format(i), 78 get_cmd=cmdbase + '?', 79 set_cmd=cmdbase + ':{:.4f}', 80 get_parser=float, 81 vals=Numbers(-100, 100)) 82 83 self.add_function('reset', call_cmd='rst') 84 85 86 class MockSource(MockInstrument): 87 def __init__(self, name, model=None, **kwargs): 88 super().__init__(name, model=model, **kwargs) 89 90 # this parameter uses built-in sweeping to change slowly 91 self.add_parameter('amplitude', 92 label='Source Amplitude (\u03bcV)', 93 get_cmd='ampl?', 94 set_cmd='ampl:{:.4f}', 95 get_parser=float, 96 vals=Numbers(0, 10), 97 sweep_step=0.1, 98 sweep_delay=0.05) 99 100 101 class MockMeter(MockInstrument): 102 def __init__(self, name, model=None, **kwargs): 103 super().__init__(name, model=model, **kwargs) 104 105 self.add_parameter('amplitude', 106 label='Current (nA)', 107 get_cmd='ampl?', 108 get_parser=float) 109 110 111 class AverageGetter(Parameter): 112 def __init__(self, measured_param, sweep_values, delay): 113 super().__init__(name='avg_' + measured_param.name) 114 self.measured_param = measured_param 115 self.sweep_values = sweep_values 116 self.delay = delay 117 if hasattr(measured_param, 'label'): 118 self.label = 'Average: ' + measured_param.label 119 120 def get(self): 121 loop = Loop(self.sweep_values, self.delay).each(self.measured_param) 122 data = loop.run_temp() 123 return data.arrays[self.measured_param.name].mean() 124 125 126 class AverageAndRaw(Parameter): 127 def __init__(self, measured_param, sweep_values, delay): 128 name = measured_param.name 129 super().__init__(names=(name, 'avg_' + name)) 130 self.measured_param = measured_param 131 self.sweep_values = sweep_values 132 self.delay = delay 133 self.sizes = (len(sweep_values), None) 134 set_array = DataArray(parameter=sweep_values.parameter, 135 preset_data=sweep_values) 136 self.setpoints = (set_array, None) 137 if hasattr(measured_param, 'label'): 138 self.labels = (measured_param.label, 139 'Average: ' + measured_param.label) 140 141 def get(self): 142 loop = Loop(self.sweep_values, self.delay).each(self.measured_param) 143 data = loop.run_temp() 144 array = data.arrays[self.measured_param.name] 145 return (array, array.mean()) 146 ``` --- 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/examples/toymodel.py b/docs/examples/toymodel.py --- a/docs/examples/toymodel.py +++ b/docs/examples/toymodel.py @@ -40,7 +40,7 @@ def gates_get(self, parameter): if parameter[0] == 'c': - return self.fmt(self.gates[int(parameter[1:])]) + return self.fmt(self._gates[int(parameter[1:])]) else: raise ValueError
{"golden_diff": "diff --git a/docs/examples/toymodel.py b/docs/examples/toymodel.py\n--- a/docs/examples/toymodel.py\n+++ b/docs/examples/toymodel.py\n@@ -40,7 +40,7 @@\n \n def gates_get(self, parameter):\n if parameter[0] == 'c':\n- return self.fmt(self.gates[int(parameter[1:])])\n+ return self.fmt(self._gates[int(parameter[1:])])\n else:\n raise ValueError\n", "issue": "PR #70 breaks parameter .get and .set functionality\nI cannot debug the issue properly because all the objects are `multiprocessing` objects. A minimal example showing the issue:\n\n``` python\n%matplotlib nbagg\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\nimport qcodes as qc\n\nfrom toymodel import AModel, MockGates, MockSource, MockMeter, AverageGetter, AverageAndRaw\n\n# now create this \"experiment\"\nmodel = AModel()\ngates = MockGates('gates', model=model)\n\nc0, c1, c2 = gates.chan0, gates.chan1, gates.chan2\nprint('fine so far...')\n\nprint('error...')\nc2.get()\nprint('no effect?')\nc2.set(0.5)\n\n```\n\n", "before_files": [{"content": "# code for example notebook\n\nimport math\n\nfrom qcodes import MockInstrument, MockModel, Parameter, Loop, DataArray\nfrom qcodes.utils.validators import Numbers\n\n\nclass AModel(MockModel):\n def __init__(self):\n self._gates = [0.0, 0.0, 0.0]\n self._excitation = 0.1\n super().__init__()\n\n def _output(self):\n # my super exciting model!\n # make a nice pattern that looks sort of double-dotty\n # with the first two gates controlling the two dots,\n # and the third looking like Vsd\n delta_i = 10\n delta_j = 10\n di = (self._gates[0] + delta_i / 2) % delta_i - delta_i / 2\n dj = (self._gates[1] + delta_j / 2) % delta_j - delta_j / 2\n vsd = math.sqrt(self._gates[2]**2 + self._excitation**2)\n dij = math.sqrt(di**2 + dj**2) - vsd\n g = (vsd**2 + 1) * (1 / (dij**2 + 1) +\n 0.1 * (math.atan(-dij) + math.pi / 2))\n return g\n\n def fmt(self, value):\n return '{:.3f}'.format(value)\n\n def gates_set(self, parameter, value):\n if parameter[0] == 'c':\n self._gates[int(parameter[1:])] = float(value)\n elif parameter == 'rst' and value is None:\n self._gates = [0.0, 0.0, 0.0]\n else:\n raise ValueError\n\n def gates_get(self, parameter):\n if parameter[0] == 'c':\n return self.fmt(self.gates[int(parameter[1:])])\n else:\n raise ValueError\n\n def source_set(self, parameter, value):\n if parameter == 'ampl':\n self._excitation = float(value)\n else:\n raise ValueError\n\n def source_get(self, parameter):\n if parameter == 'ampl':\n return self.fmt(self._excitation)\n else:\n raise ValueError\n\n def meter_get(self, parameter):\n if parameter == 'ampl':\n return self.fmt(self._output() * self._excitation)\n else:\n raise ValueError\n\n\n# make our mock instruments\n# real instruments would subclass IPInstrument or VisaInstrument\n# or just the base Instrument instead of MockInstrument,\n# and be instantiated with an address rather than a model\nclass MockGates(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n for i in range(3):\n cmdbase = 'c{}'.format(i)\n self.add_parameter('chan{}'.format(i),\n label='Gate Channel {} (mV)'.format(i),\n get_cmd=cmdbase + '?',\n set_cmd=cmdbase + ':{:.4f}',\n get_parser=float,\n vals=Numbers(-100, 100))\n\n self.add_function('reset', call_cmd='rst')\n\n\nclass MockSource(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n # this parameter uses built-in sweeping to change slowly\n self.add_parameter('amplitude',\n label='Source Amplitude (\\u03bcV)',\n get_cmd='ampl?',\n set_cmd='ampl:{:.4f}',\n get_parser=float,\n vals=Numbers(0, 10),\n sweep_step=0.1,\n sweep_delay=0.05)\n\n\nclass MockMeter(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n self.add_parameter('amplitude',\n label='Current (nA)',\n get_cmd='ampl?',\n get_parser=float)\n\n\nclass AverageGetter(Parameter):\n def __init__(self, measured_param, sweep_values, delay):\n super().__init__(name='avg_' + measured_param.name)\n self.measured_param = measured_param\n self.sweep_values = sweep_values\n self.delay = delay\n if hasattr(measured_param, 'label'):\n self.label = 'Average: ' + measured_param.label\n\n def get(self):\n loop = Loop(self.sweep_values, self.delay).each(self.measured_param)\n data = loop.run_temp()\n return data.arrays[self.measured_param.name].mean()\n\n\nclass AverageAndRaw(Parameter):\n def __init__(self, measured_param, sweep_values, delay):\n name = measured_param.name\n super().__init__(names=(name, 'avg_' + name))\n self.measured_param = measured_param\n self.sweep_values = sweep_values\n self.delay = delay\n self.sizes = (len(sweep_values), None)\n set_array = DataArray(parameter=sweep_values.parameter,\n preset_data=sweep_values)\n self.setpoints = (set_array, None)\n if hasattr(measured_param, 'label'):\n self.labels = (measured_param.label,\n 'Average: ' + measured_param.label)\n\n def get(self):\n loop = Loop(self.sweep_values, self.delay).each(self.measured_param)\n data = loop.run_temp()\n array = data.arrays[self.measured_param.name]\n return (array, array.mean())\n", "path": "docs/examples/toymodel.py"}], "after_files": [{"content": "# code for example notebook\n\nimport math\n\nfrom qcodes import MockInstrument, MockModel, Parameter, Loop, DataArray\nfrom qcodes.utils.validators import Numbers\n\n\nclass AModel(MockModel):\n def __init__(self):\n self._gates = [0.0, 0.0, 0.0]\n self._excitation = 0.1\n super().__init__()\n\n def _output(self):\n # my super exciting model!\n # make a nice pattern that looks sort of double-dotty\n # with the first two gates controlling the two dots,\n # and the third looking like Vsd\n delta_i = 10\n delta_j = 10\n di = (self._gates[0] + delta_i / 2) % delta_i - delta_i / 2\n dj = (self._gates[1] + delta_j / 2) % delta_j - delta_j / 2\n vsd = math.sqrt(self._gates[2]**2 + self._excitation**2)\n dij = math.sqrt(di**2 + dj**2) - vsd\n g = (vsd**2 + 1) * (1 / (dij**2 + 1) +\n 0.1 * (math.atan(-dij) + math.pi / 2))\n return g\n\n def fmt(self, value):\n return '{:.3f}'.format(value)\n\n def gates_set(self, parameter, value):\n if parameter[0] == 'c':\n self._gates[int(parameter[1:])] = float(value)\n elif parameter == 'rst' and value is None:\n self._gates = [0.0, 0.0, 0.0]\n else:\n raise ValueError\n\n def gates_get(self, parameter):\n if parameter[0] == 'c':\n return self.fmt(self._gates[int(parameter[1:])])\n else:\n raise ValueError\n\n def source_set(self, parameter, value):\n if parameter == 'ampl':\n self._excitation = float(value)\n else:\n raise ValueError\n\n def source_get(self, parameter):\n if parameter == 'ampl':\n return self.fmt(self._excitation)\n else:\n raise ValueError\n\n def meter_get(self, parameter):\n if parameter == 'ampl':\n return self.fmt(self._output() * self._excitation)\n else:\n raise ValueError\n\n\n# make our mock instruments\n# real instruments would subclass IPInstrument or VisaInstrument\n# or just the base Instrument instead of MockInstrument,\n# and be instantiated with an address rather than a model\nclass MockGates(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n for i in range(3):\n cmdbase = 'c{}'.format(i)\n self.add_parameter('chan{}'.format(i),\n label='Gate Channel {} (mV)'.format(i),\n get_cmd=cmdbase + '?',\n set_cmd=cmdbase + ':{:.4f}',\n get_parser=float,\n vals=Numbers(-100, 100))\n\n self.add_function('reset', call_cmd='rst')\n\n\nclass MockSource(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n # this parameter uses built-in sweeping to change slowly\n self.add_parameter('amplitude',\n label='Source Amplitude (\\u03bcV)',\n get_cmd='ampl?',\n set_cmd='ampl:{:.4f}',\n get_parser=float,\n vals=Numbers(0, 10),\n sweep_step=0.1,\n sweep_delay=0.05)\n\n\nclass MockMeter(MockInstrument):\n def __init__(self, name, model=None, **kwargs):\n super().__init__(name, model=model, **kwargs)\n\n self.add_parameter('amplitude',\n label='Current (nA)',\n get_cmd='ampl?',\n get_parser=float)\n\n\nclass AverageGetter(Parameter):\n def __init__(self, measured_param, sweep_values, delay):\n super().__init__(name='avg_' + measured_param.name)\n self.measured_param = measured_param\n self.sweep_values = sweep_values\n self.delay = delay\n if hasattr(measured_param, 'label'):\n self.label = 'Average: ' + measured_param.label\n\n def get(self):\n loop = Loop(self.sweep_values, self.delay).each(self.measured_param)\n data = loop.run_temp()\n return data.arrays[self.measured_param.name].mean()\n\n\nclass AverageAndRaw(Parameter):\n def __init__(self, measured_param, sweep_values, delay):\n name = measured_param.name\n super().__init__(names=(name, 'avg_' + name))\n self.measured_param = measured_param\n self.sweep_values = sweep_values\n self.delay = delay\n self.sizes = (len(sweep_values), None)\n set_array = DataArray(parameter=sweep_values.parameter,\n preset_data=sweep_values)\n self.setpoints = (set_array, None)\n if hasattr(measured_param, 'label'):\n self.labels = (measured_param.label,\n 'Average: ' + measured_param.label)\n\n def get(self):\n loop = Loop(self.sweep_values, self.delay).each(self.measured_param)\n data = loop.run_temp()\n array = data.arrays[self.measured_param.name]\n return (array, array.mean())\n", "path": "docs/examples/toymodel.py"}]}
1,985
105
gh_patches_debug_38636
rasdani/github-patches
git_diff
e-valuation__EvaP-1105
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Release Sisyphus data only after successful post When a user enters answers on the student vote page and then logs out in another window before submitting the form, Sisyphus releases the form data on the form submit, because a 302 redirect to the login page is not an error case. The data should be kept in browser storage until the vote was successfully counted. Release Sisyphus data only after successful post When a user enters answers on the student vote page and then logs out in another window before submitting the form, Sisyphus releases the form data on the form submit, because a 302 redirect to the login page is not an error case. The data should be kept in browser storage until the vote was successfully counted. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `evap/student/views.py` Content: ``` 1 from collections import OrderedDict 2 3 from django.contrib import messages 4 from django.core.exceptions import PermissionDenied, SuspiciousOperation 5 from django.db import transaction 6 from django.shortcuts import get_object_or_404, redirect, render 7 from django.utils.translation import ugettext as _ 8 9 from evap.evaluation.auth import participant_required 10 from evap.evaluation.models import Course, Semester 11 from evap.evaluation.tools import STUDENT_STATES_ORDERED 12 13 from evap.student.forms import QuestionsForm 14 from evap.student.tools import question_id 15 16 17 @participant_required 18 def index(request): 19 # retrieve all courses, where the user is a participant and that are not new 20 courses = list(set(Course.objects.filter(participants=request.user).exclude(state="new"))) 21 voted_courses = list(set(Course.objects.filter(voters=request.user))) 22 due_courses = list(set(Course.objects.filter(participants=request.user, state='in_evaluation').exclude(voters=request.user))) 23 24 sorter = lambda course: (list(STUDENT_STATES_ORDERED.keys()).index(course.student_state), course.vote_end_date, course.name) 25 courses.sort(key=sorter) 26 27 semesters = Semester.objects.all() 28 semester_list = [dict(semester_name=semester.name, id=semester.id, is_active_semester=semester.is_active_semester, 29 courses=[course for course in courses if course.semester_id == semester.id]) for semester in semesters] 30 31 template_data = dict( 32 semester_list=semester_list, 33 voted_courses=voted_courses, 34 due_courses=due_courses, 35 can_download_grades=request.user.can_download_grades, 36 ) 37 return render(request, "student_index.html", template_data) 38 39 40 def vote_preview(request, course, for_rendering_in_modal=False): 41 """ 42 Renders a preview of the voting page for the given course. 43 Not used by the student app itself, but by staff and contributor. 44 """ 45 form_groups = helper_create_voting_form_groups(request, course.contributions.all()) 46 course_form_group = form_groups.pop(course.general_contribution) 47 contributor_form_groups = list((contribution.contributor, contribution.label, form_group, False) for contribution, form_group in form_groups.items()) 48 49 template_data = dict( 50 errors_exist=False, 51 course_form_group=course_form_group, 52 contributor_form_groups=contributor_form_groups, 53 course=course, 54 preview=True, 55 for_rendering_in_modal=for_rendering_in_modal) 56 return render(request, "student_vote.html", template_data) 57 58 59 @participant_required 60 def vote(request, course_id): 61 # retrieve course and make sure that the user is allowed to vote 62 course = get_object_or_404(Course, id=course_id) 63 if not course.can_user_vote(request.user): 64 raise PermissionDenied 65 66 67 # prevent a user from voting on themselves. 68 contributions_to_vote_on = course.contributions.exclude(contributor=request.user).all() 69 form_groups = helper_create_voting_form_groups(request, contributions_to_vote_on) 70 71 if not all(all(form.is_valid() for form in form_group) for form_group in form_groups.values()): 72 errors_exist = any(helper_has_errors(form_group) for form_group in form_groups.values()) 73 74 course_form_group = form_groups.pop(course.general_contribution) 75 76 contributor_form_groups = list((contribution.contributor, contribution.label, form_group, helper_has_errors(form_group)) for contribution, form_group in form_groups.items()) 77 78 template_data = dict( 79 errors_exist=errors_exist, 80 course_form_group=course_form_group, 81 contributor_form_groups=contributor_form_groups, 82 course=course, 83 participants_warning=course.num_participants <= 5, 84 preview=False, 85 vote_end_datetime=course.vote_end_datetime, 86 hours_left_for_evaluation=course.time_left_for_evaluation.seconds//3600, 87 minutes_left_for_evaluation=(course.time_left_for_evaluation.seconds//60)%60, 88 evaluation_ends_soon=course.evaluation_ends_soon()) 89 return render(request, "student_vote.html", template_data) 90 91 # all forms are valid, begin vote operation 92 with transaction.atomic(): 93 # add user to course.voters 94 # not using course.voters.add(request.user) since it fails silently when done twice. 95 # manually inserting like this gives us the 'created' return value and ensures at the database level that nobody votes twice. 96 __, created = course.voters.through.objects.get_or_create(userprofile_id=request.user.pk, course_id=course.pk) 97 if not created: # vote already got recorded, bail out 98 raise SuspiciousOperation("A second vote has been received shortly after the first one.") 99 100 for contribution, form_group in form_groups.items(): 101 for questionnaire_form in form_group: 102 questionnaire = questionnaire_form.questionnaire 103 for question in questionnaire.question_set.all(): 104 identifier = question_id(contribution, questionnaire, question) 105 value = questionnaire_form.cleaned_data.get(identifier) 106 107 if question.is_text_question: 108 if value: 109 question.answer_class.objects.create( 110 contribution=contribution, 111 question=question, 112 answer=value) 113 elif question.is_heading_question: 114 pass # ignore these 115 else: 116 if value != 6: 117 answer_counter, __ = question.answer_class.objects.get_or_create(contribution=contribution, question=question, answer=value) 118 answer_counter.add_vote() 119 answer_counter.save() 120 121 course.course_evaluated.send(sender=Course, request=request, semester=course.semester) 122 123 messages.success(request, _("Your vote was recorded.")) 124 return redirect('student:index') 125 126 127 def helper_create_voting_form_groups(request, contributions): 128 form_groups = OrderedDict() 129 for contribution in contributions: 130 questionnaires = contribution.questionnaires.all() 131 if not questionnaires.exists(): 132 continue 133 form_groups[contribution] = [QuestionsForm(request.POST or None, contribution=contribution, questionnaire=questionnaire) for questionnaire in questionnaires] 134 return form_groups 135 136 137 def helper_has_errors(form_group): 138 return any(form.errors for form in form_group) 139 ``` --- 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/evap/student/views.py b/evap/student/views.py --- a/evap/student/views.py +++ b/evap/student/views.py @@ -3,7 +3,9 @@ from django.contrib import messages from django.core.exceptions import PermissionDenied, SuspiciousOperation from django.db import transaction +from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse from django.utils.translation import ugettext as _ from evap.evaluation.auth import participant_required @@ -13,6 +15,7 @@ from evap.student.forms import QuestionsForm from evap.student.tools import question_id +SUCCESS_MAGIC_STRING = 'vote submitted successfully' @participant_required def index(request): @@ -58,12 +61,11 @@ @participant_required def vote(request, course_id): - # retrieve course and make sure that the user is allowed to vote + course = get_object_or_404(Course, id=course_id) if not course.can_user_vote(request.user): raise PermissionDenied - # prevent a user from voting on themselves. contributions_to_vote_on = course.contributions.exclude(contributor=request.user).all() form_groups = helper_create_voting_form_groups(request, contributions_to_vote_on) @@ -85,6 +87,8 @@ vote_end_datetime=course.vote_end_datetime, hours_left_for_evaluation=course.time_left_for_evaluation.seconds//3600, minutes_left_for_evaluation=(course.time_left_for_evaluation.seconds//60)%60, + success_magic_string=SUCCESS_MAGIC_STRING, + success_redirect_url=reverse('student:index'), evaluation_ends_soon=course.evaluation_ends_soon()) return render(request, "student_vote.html", template_data) @@ -121,7 +125,7 @@ course.course_evaluated.send(sender=Course, request=request, semester=course.semester) messages.success(request, _("Your vote was recorded.")) - return redirect('student:index') + return HttpResponse(SUCCESS_MAGIC_STRING) def helper_create_voting_form_groups(request, contributions):
{"golden_diff": "diff --git a/evap/student/views.py b/evap/student/views.py\n--- a/evap/student/views.py\n+++ b/evap/student/views.py\n@@ -3,7 +3,9 @@\n from django.contrib import messages\n from django.core.exceptions import PermissionDenied, SuspiciousOperation\n from django.db import transaction\n+from django.http import HttpResponse\n from django.shortcuts import get_object_or_404, redirect, render\n+from django.urls import reverse\n from django.utils.translation import ugettext as _\n \n from evap.evaluation.auth import participant_required\n@@ -13,6 +15,7 @@\n from evap.student.forms import QuestionsForm\n from evap.student.tools import question_id\n \n+SUCCESS_MAGIC_STRING = 'vote submitted successfully'\n \n @participant_required\n def index(request):\n@@ -58,12 +61,11 @@\n \n @participant_required\n def vote(request, course_id):\n- # retrieve course and make sure that the user is allowed to vote\n+\n course = get_object_or_404(Course, id=course_id)\n if not course.can_user_vote(request.user):\n raise PermissionDenied\n \n- \n # prevent a user from voting on themselves.\n contributions_to_vote_on = course.contributions.exclude(contributor=request.user).all()\n form_groups = helper_create_voting_form_groups(request, contributions_to_vote_on)\n@@ -85,6 +87,8 @@\n vote_end_datetime=course.vote_end_datetime,\n hours_left_for_evaluation=course.time_left_for_evaluation.seconds//3600,\n minutes_left_for_evaluation=(course.time_left_for_evaluation.seconds//60)%60,\n+ success_magic_string=SUCCESS_MAGIC_STRING,\n+ success_redirect_url=reverse('student:index'),\n evaluation_ends_soon=course.evaluation_ends_soon())\n return render(request, \"student_vote.html\", template_data)\n \n@@ -121,7 +125,7 @@\n course.course_evaluated.send(sender=Course, request=request, semester=course.semester)\n \n messages.success(request, _(\"Your vote was recorded.\"))\n- return redirect('student:index')\n+ return HttpResponse(SUCCESS_MAGIC_STRING)\n \n \n def helper_create_voting_form_groups(request, contributions):\n", "issue": "Release Sisyphus data only after successful post\nWhen a user enters answers on the student vote page and then logs out in another window before submitting the form, Sisyphus releases the form data on the form submit, because a 302 redirect to the login page is not an error case.\r\nThe data should be kept in browser storage until the vote was successfully counted.\nRelease Sisyphus data only after successful post\nWhen a user enters answers on the student vote page and then logs out in another window before submitting the form, Sisyphus releases the form data on the form submit, because a 302 redirect to the login page is not an error case.\r\nThe data should be kept in browser storage until the vote was successfully counted.\n", "before_files": [{"content": "from collections import OrderedDict\n\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied, SuspiciousOperation\nfrom django.db import transaction\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.translation import ugettext as _\n\nfrom evap.evaluation.auth import participant_required\nfrom evap.evaluation.models import Course, Semester\nfrom evap.evaluation.tools import STUDENT_STATES_ORDERED\n\nfrom evap.student.forms import QuestionsForm\nfrom evap.student.tools import question_id\n\n\n@participant_required\ndef index(request):\n # retrieve all courses, where the user is a participant and that are not new\n courses = list(set(Course.objects.filter(participants=request.user).exclude(state=\"new\")))\n voted_courses = list(set(Course.objects.filter(voters=request.user)))\n due_courses = list(set(Course.objects.filter(participants=request.user, state='in_evaluation').exclude(voters=request.user)))\n\n sorter = lambda course: (list(STUDENT_STATES_ORDERED.keys()).index(course.student_state), course.vote_end_date, course.name)\n courses.sort(key=sorter)\n\n semesters = Semester.objects.all()\n semester_list = [dict(semester_name=semester.name, id=semester.id, is_active_semester=semester.is_active_semester,\n courses=[course for course in courses if course.semester_id == semester.id]) for semester in semesters]\n\n template_data = dict(\n semester_list=semester_list,\n voted_courses=voted_courses,\n due_courses=due_courses,\n can_download_grades=request.user.can_download_grades,\n )\n return render(request, \"student_index.html\", template_data)\n\n\ndef vote_preview(request, course, for_rendering_in_modal=False):\n \"\"\"\n Renders a preview of the voting page for the given course.\n Not used by the student app itself, but by staff and contributor.\n \"\"\"\n form_groups = helper_create_voting_form_groups(request, course.contributions.all())\n course_form_group = form_groups.pop(course.general_contribution)\n contributor_form_groups = list((contribution.contributor, contribution.label, form_group, False) for contribution, form_group in form_groups.items())\n\n template_data = dict(\n errors_exist=False,\n course_form_group=course_form_group,\n contributor_form_groups=contributor_form_groups,\n course=course,\n preview=True,\n for_rendering_in_modal=for_rendering_in_modal)\n return render(request, \"student_vote.html\", template_data)\n\n\n@participant_required\ndef vote(request, course_id):\n # retrieve course and make sure that the user is allowed to vote\n course = get_object_or_404(Course, id=course_id)\n if not course.can_user_vote(request.user):\n raise PermissionDenied\n\n \n # prevent a user from voting on themselves.\n contributions_to_vote_on = course.contributions.exclude(contributor=request.user).all()\n form_groups = helper_create_voting_form_groups(request, contributions_to_vote_on)\n\n if not all(all(form.is_valid() for form in form_group) for form_group in form_groups.values()):\n errors_exist = any(helper_has_errors(form_group) for form_group in form_groups.values())\n\n course_form_group = form_groups.pop(course.general_contribution)\n\n contributor_form_groups = list((contribution.contributor, contribution.label, form_group, helper_has_errors(form_group)) for contribution, form_group in form_groups.items())\n\n template_data = dict(\n errors_exist=errors_exist,\n course_form_group=course_form_group,\n contributor_form_groups=contributor_form_groups,\n course=course,\n participants_warning=course.num_participants <= 5,\n preview=False,\n vote_end_datetime=course.vote_end_datetime,\n hours_left_for_evaluation=course.time_left_for_evaluation.seconds//3600,\n minutes_left_for_evaluation=(course.time_left_for_evaluation.seconds//60)%60,\n evaluation_ends_soon=course.evaluation_ends_soon())\n return render(request, \"student_vote.html\", template_data)\n\n # all forms are valid, begin vote operation\n with transaction.atomic():\n # add user to course.voters\n # not using course.voters.add(request.user) since it fails silently when done twice.\n # manually inserting like this gives us the 'created' return value and ensures at the database level that nobody votes twice.\n __, created = course.voters.through.objects.get_or_create(userprofile_id=request.user.pk, course_id=course.pk)\n if not created: # vote already got recorded, bail out\n raise SuspiciousOperation(\"A second vote has been received shortly after the first one.\")\n\n for contribution, form_group in form_groups.items():\n for questionnaire_form in form_group:\n questionnaire = questionnaire_form.questionnaire\n for question in questionnaire.question_set.all():\n identifier = question_id(contribution, questionnaire, question)\n value = questionnaire_form.cleaned_data.get(identifier)\n\n if question.is_text_question:\n if value:\n question.answer_class.objects.create(\n contribution=contribution,\n question=question,\n answer=value)\n elif question.is_heading_question:\n pass # ignore these\n else:\n if value != 6:\n answer_counter, __ = question.answer_class.objects.get_or_create(contribution=contribution, question=question, answer=value)\n answer_counter.add_vote()\n answer_counter.save()\n\n course.course_evaluated.send(sender=Course, request=request, semester=course.semester)\n\n messages.success(request, _(\"Your vote was recorded.\"))\n return redirect('student:index')\n\n\ndef helper_create_voting_form_groups(request, contributions):\n form_groups = OrderedDict()\n for contribution in contributions:\n questionnaires = contribution.questionnaires.all()\n if not questionnaires.exists():\n continue\n form_groups[contribution] = [QuestionsForm(request.POST or None, contribution=contribution, questionnaire=questionnaire) for questionnaire in questionnaires]\n return form_groups\n\n\ndef helper_has_errors(form_group):\n return any(form.errors for form in form_group)\n", "path": "evap/student/views.py"}], "after_files": [{"content": "from collections import OrderedDict\n\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied, SuspiciousOperation\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext as _\n\nfrom evap.evaluation.auth import participant_required\nfrom evap.evaluation.models import Course, Semester\nfrom evap.evaluation.tools import STUDENT_STATES_ORDERED\n\nfrom evap.student.forms import QuestionsForm\nfrom evap.student.tools import question_id\n\nSUCCESS_MAGIC_STRING = 'vote submitted successfully'\n\n@participant_required\ndef index(request):\n # retrieve all courses, where the user is a participant and that are not new\n courses = list(set(Course.objects.filter(participants=request.user).exclude(state=\"new\")))\n voted_courses = list(set(Course.objects.filter(voters=request.user)))\n due_courses = list(set(Course.objects.filter(participants=request.user, state='in_evaluation').exclude(voters=request.user)))\n\n sorter = lambda course: (list(STUDENT_STATES_ORDERED.keys()).index(course.student_state), course.vote_end_date, course.name)\n courses.sort(key=sorter)\n\n semesters = Semester.objects.all()\n semester_list = [dict(semester_name=semester.name, id=semester.id, is_active_semester=semester.is_active_semester,\n courses=[course for course in courses if course.semester_id == semester.id]) for semester in semesters]\n\n template_data = dict(\n semester_list=semester_list,\n voted_courses=voted_courses,\n due_courses=due_courses,\n can_download_grades=request.user.can_download_grades,\n )\n return render(request, \"student_index.html\", template_data)\n\n\ndef vote_preview(request, course, for_rendering_in_modal=False):\n \"\"\"\n Renders a preview of the voting page for the given course.\n Not used by the student app itself, but by staff and contributor.\n \"\"\"\n form_groups = helper_create_voting_form_groups(request, course.contributions.all())\n course_form_group = form_groups.pop(course.general_contribution)\n contributor_form_groups = list((contribution.contributor, contribution.label, form_group, False) for contribution, form_group in form_groups.items())\n\n template_data = dict(\n errors_exist=False,\n course_form_group=course_form_group,\n contributor_form_groups=contributor_form_groups,\n course=course,\n preview=True,\n for_rendering_in_modal=for_rendering_in_modal)\n return render(request, \"student_vote.html\", template_data)\n\n\n@participant_required\ndef vote(request, course_id):\n\n course = get_object_or_404(Course, id=course_id)\n if not course.can_user_vote(request.user):\n raise PermissionDenied\n\n # prevent a user from voting on themselves.\n contributions_to_vote_on = course.contributions.exclude(contributor=request.user).all()\n form_groups = helper_create_voting_form_groups(request, contributions_to_vote_on)\n\n if not all(all(form.is_valid() for form in form_group) for form_group in form_groups.values()):\n errors_exist = any(helper_has_errors(form_group) for form_group in form_groups.values())\n\n course_form_group = form_groups.pop(course.general_contribution)\n\n contributor_form_groups = list((contribution.contributor, contribution.label, form_group, helper_has_errors(form_group)) for contribution, form_group in form_groups.items())\n\n template_data = dict(\n errors_exist=errors_exist,\n course_form_group=course_form_group,\n contributor_form_groups=contributor_form_groups,\n course=course,\n participants_warning=course.num_participants <= 5,\n preview=False,\n vote_end_datetime=course.vote_end_datetime,\n hours_left_for_evaluation=course.time_left_for_evaluation.seconds//3600,\n minutes_left_for_evaluation=(course.time_left_for_evaluation.seconds//60)%60,\n success_magic_string=SUCCESS_MAGIC_STRING,\n success_redirect_url=reverse('student:index'),\n evaluation_ends_soon=course.evaluation_ends_soon())\n return render(request, \"student_vote.html\", template_data)\n\n # all forms are valid, begin vote operation\n with transaction.atomic():\n # add user to course.voters\n # not using course.voters.add(request.user) since it fails silently when done twice.\n # manually inserting like this gives us the 'created' return value and ensures at the database level that nobody votes twice.\n __, created = course.voters.through.objects.get_or_create(userprofile_id=request.user.pk, course_id=course.pk)\n if not created: # vote already got recorded, bail out\n raise SuspiciousOperation(\"A second vote has been received shortly after the first one.\")\n\n for contribution, form_group in form_groups.items():\n for questionnaire_form in form_group:\n questionnaire = questionnaire_form.questionnaire\n for question in questionnaire.question_set.all():\n identifier = question_id(contribution, questionnaire, question)\n value = questionnaire_form.cleaned_data.get(identifier)\n\n if question.is_text_question:\n if value:\n question.answer_class.objects.create(\n contribution=contribution,\n question=question,\n answer=value)\n elif question.is_heading_question:\n pass # ignore these\n else:\n if value != 6:\n answer_counter, __ = question.answer_class.objects.get_or_create(contribution=contribution, question=question, answer=value)\n answer_counter.add_vote()\n answer_counter.save()\n\n course.course_evaluated.send(sender=Course, request=request, semester=course.semester)\n\n messages.success(request, _(\"Your vote was recorded.\"))\n return HttpResponse(SUCCESS_MAGIC_STRING)\n\n\ndef helper_create_voting_form_groups(request, contributions):\n form_groups = OrderedDict()\n for contribution in contributions:\n questionnaires = contribution.questionnaires.all()\n if not questionnaires.exists():\n continue\n form_groups[contribution] = [QuestionsForm(request.POST or None, contribution=contribution, questionnaire=questionnaire) for questionnaire in questionnaires]\n return form_groups\n\n\ndef helper_has_errors(form_group):\n return any(form.errors for form in form_group)\n", "path": "evap/student/views.py"}]}
2,000
474
gh_patches_debug_14673
rasdani/github-patches
git_diff
xonsh__xonsh-427
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Tab completing on empty line with prompt_toolkit kills terminal Arch Linux with xonsh 0.2.2 and using prompt toolkit. Hitting TAB on an empty line crashes the terminal (rxvt-unicode). I can see the traceback for a split second but then the terminal is gone. This doesn't happen using readline. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `xonsh/prompt_toolkit_key_bindings.py` Content: ``` 1 """Key bindings for prompt_toolkit xonsh shell.""" 2 import builtins 3 4 from prompt_toolkit.filters import Filter 5 from prompt_toolkit.keys import Keys 6 7 8 class TabShouldInsertIndentFilter(Filter): 9 """ 10 Filter that is intended to check if <Tab> should insert indent instead of 11 starting autocompletion. 12 It basically just checks if there are only whitespaces before the cursor - 13 if so indent should be inserted, otherwise autocompletion. 14 """ 15 def __call__(self, cli): 16 before_cursor = cli.current_buffer.document.current_line_before_cursor 17 18 return bool(not before_cursor or before_cursor.isspace()) 19 20 21 def load_xonsh_bindings(key_bindings_manager): 22 """ 23 Load custom key bindings. 24 """ 25 handle = key_bindings_manager.registry.add_binding 26 env = builtins.__xonsh_env__ 27 28 @handle(Keys.Tab, filter=TabShouldInsertIndentFilter()) 29 def _(event): 30 """ 31 If there are only whitespaces before current cursor position insert 32 indent instead of autocompleting. 33 """ 34 event.cli.current_buffer.insert_text(env['INDENT']) 35 36 37 ``` --- 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/xonsh/prompt_toolkit_key_bindings.py b/xonsh/prompt_toolkit_key_bindings.py --- a/xonsh/prompt_toolkit_key_bindings.py +++ b/xonsh/prompt_toolkit_key_bindings.py @@ -15,7 +15,7 @@ def __call__(self, cli): before_cursor = cli.current_buffer.document.current_line_before_cursor - return bool(not before_cursor or before_cursor.isspace()) + return bool(before_cursor.isspace()) def load_xonsh_bindings(key_bindings_manager): @@ -31,6 +31,6 @@ If there are only whitespaces before current cursor position insert indent instead of autocompleting. """ - event.cli.current_buffer.insert_text(env['INDENT']) + event.cli.current_buffer.insert_text(env.get('INDENT'))
{"golden_diff": "diff --git a/xonsh/prompt_toolkit_key_bindings.py b/xonsh/prompt_toolkit_key_bindings.py\n--- a/xonsh/prompt_toolkit_key_bindings.py\n+++ b/xonsh/prompt_toolkit_key_bindings.py\n@@ -15,7 +15,7 @@\n def __call__(self, cli):\n before_cursor = cli.current_buffer.document.current_line_before_cursor\n \n- return bool(not before_cursor or before_cursor.isspace())\n+ return bool(before_cursor.isspace())\n \n \n def load_xonsh_bindings(key_bindings_manager):\n@@ -31,6 +31,6 @@\n If there are only whitespaces before current cursor position insert\n indent instead of autocompleting.\n \"\"\"\n- event.cli.current_buffer.insert_text(env['INDENT'])\n+ event.cli.current_buffer.insert_text(env.get('INDENT'))\n", "issue": "Tab completing on empty line with prompt_toolkit kills terminal\nArch Linux with xonsh 0.2.2 and using prompt toolkit. Hitting TAB on an empty line crashes the terminal (rxvt-unicode). I can see the traceback for a split second but then the terminal is gone. \n\nThis doesn't happen using readline.\n\n", "before_files": [{"content": "\"\"\"Key bindings for prompt_toolkit xonsh shell.\"\"\"\nimport builtins\n\nfrom prompt_toolkit.filters import Filter\nfrom prompt_toolkit.keys import Keys\n\n\nclass TabShouldInsertIndentFilter(Filter):\n \"\"\"\n Filter that is intended to check if <Tab> should insert indent instead of\n starting autocompletion.\n It basically just checks if there are only whitespaces before the cursor -\n if so indent should be inserted, otherwise autocompletion.\n \"\"\"\n def __call__(self, cli):\n before_cursor = cli.current_buffer.document.current_line_before_cursor\n\n return bool(not before_cursor or before_cursor.isspace())\n\n\ndef load_xonsh_bindings(key_bindings_manager):\n \"\"\"\n Load custom key bindings.\n \"\"\"\n handle = key_bindings_manager.registry.add_binding\n env = builtins.__xonsh_env__\n\n @handle(Keys.Tab, filter=TabShouldInsertIndentFilter())\n def _(event):\n \"\"\"\n If there are only whitespaces before current cursor position insert\n indent instead of autocompleting.\n \"\"\"\n event.cli.current_buffer.insert_text(env['INDENT'])\n\n\n", "path": "xonsh/prompt_toolkit_key_bindings.py"}], "after_files": [{"content": "\"\"\"Key bindings for prompt_toolkit xonsh shell.\"\"\"\nimport builtins\n\nfrom prompt_toolkit.filters import Filter\nfrom prompt_toolkit.keys import Keys\n\n\nclass TabShouldInsertIndentFilter(Filter):\n \"\"\"\n Filter that is intended to check if <Tab> should insert indent instead of\n starting autocompletion.\n It basically just checks if there are only whitespaces before the cursor -\n if so indent should be inserted, otherwise autocompletion.\n \"\"\"\n def __call__(self, cli):\n before_cursor = cli.current_buffer.document.current_line_before_cursor\n\n return bool(before_cursor.isspace())\n\n\ndef load_xonsh_bindings(key_bindings_manager):\n \"\"\"\n Load custom key bindings.\n \"\"\"\n handle = key_bindings_manager.registry.add_binding\n env = builtins.__xonsh_env__\n\n @handle(Keys.Tab, filter=TabShouldInsertIndentFilter())\n def _(event):\n \"\"\"\n If there are only whitespaces before current cursor position insert\n indent instead of autocompleting.\n \"\"\"\n event.cli.current_buffer.insert_text(env.get('INDENT'))\n\n\n", "path": "xonsh/prompt_toolkit_key_bindings.py"}]}
634
182
gh_patches_debug_7426
rasdani/github-patches
git_diff
cltk__cltk-938
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add "Gorman Trees" corpus for Greek https://github.com/perseids-publications/gorman-trees = https://perseids-publications.github.io/gorman-trees/ ~500,000 tokens of parsed Ancient Greek. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `cltk/corpus/greek/corpora.py` Content: ``` 1 """Greek language corpora available for download or loading locally. 2 All remote corpora hosted by github on the cltk organization account, eg: 3 'http://github.com/cltk' + name 4 """ 5 6 GREEK_CORPORA = [ 7 {'name': 'greek_software_tlgu', 8 'origin': 'https://github.com/cltk/greek_software_tlgu.git', 9 'location': 'remote', 10 'type': 'software'}, 11 {'encoding': 'utf-8', 12 'markup': 'tei_xml', 13 'origin': 'https://github.com/cltk/greek_text_perseus.git', 14 'name': 'greek_text_perseus', 15 'location': 'remote', 16 'type': 'text'}, 17 {'encoding': 'latin-1', 18 'markup': 'beta_code', 19 'origin': None, 20 'name': 'phi7', 21 'location': 'local', 22 'type': 'text'}, 23 {'encoding': 'latin-1', 24 'markup': 'beta_code', 25 'name': 'tlg', 26 'origin': None, 27 'location': 'local', 28 'type': 'text'}, 29 {'encoding': 'utf-8', 30 'markup': 'plaintext', 31 'name': 'greek_proper_names_cltk', 32 'origin': 'https://github.com/cltk/greek_proper_names_cltk.git', 33 'location': 'remote', 34 'type': 'lexicon'}, 35 {'name': 'greek_models_cltk', 36 'origin': 'https://github.com/cltk/greek_models_cltk.git', 37 'location': 'remote', 38 'type': 'model'}, 39 {'encoding': 'utf-8', 40 'markup': 'xml', 41 'origin': 'https://github.com/cltk/greek_treebank_perseus.git', 42 'name': 'greek_treebank_perseus', 43 'location': 'remote', 44 'type': 'treebank'}, 45 {'encoding': 'xml', 46 'markup': 'plaintext', 47 'origin': 'https://github.com/cltk/greek_lexica_perseus.git', 48 'name': 'greek_lexica_perseus', 49 'location': 'remote', 50 'type': 'lexicon'}, 51 {'encoding': 'utf-8', 52 'markup': 'plaintext', 53 'origin': 'https://github.com/cltk/greek_training_set_sentence_cltk.git', 54 'name': 'greek_training_set_sentence_cltk', 55 'location': 'remote', 56 'type': 'training_set'}, 57 {'name': 'greek_word2vec_cltk', 58 'origin': 'https://github.com/cltk/greek_word2vec_cltk.git', 59 'location': 'remote', 60 'type': 'model'}, 61 {'name': 'greek_text_lacus_curtius', 62 'origin': 'https://github.com/cltk/greek_text_lacus_curtius.git', 63 'location': 'remote', 64 'type': 'text'}, 65 {'name': 'greek_text_first1kgreek', 66 'origin': 'https://github.com/cltk/First1KGreek', 67 'location': 'remote', 68 'type': 'text'}, 69 {'name': 'greek_text_tesserae', 70 'encoding': 'utf-8', 71 'markup': 'plaintext', #modified plaintext with Tesserae-style citations 72 'origin': 'https://github.com/cltk/greek_text_tesserae.git', 73 'location': 'remote', 74 'type': 'text'}, 75 ] 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/cltk/corpus/greek/corpora.py b/cltk/corpus/greek/corpora.py --- a/cltk/corpus/greek/corpora.py +++ b/cltk/corpus/greek/corpora.py @@ -42,6 +42,12 @@ 'name': 'greek_treebank_perseus', 'location': 'remote', 'type': 'treebank'}, + {'encoding': 'utf-8', + 'markup': 'xml', + 'origin': 'https://github.com/vgorman1/Greek-Dependency-Trees.git', + 'name': 'greek_treebank_gorman', + 'location': 'remote', + 'type': 'treebank'}, {'encoding': 'xml', 'markup': 'plaintext', 'origin': 'https://github.com/cltk/greek_lexica_perseus.git',
{"golden_diff": "diff --git a/cltk/corpus/greek/corpora.py b/cltk/corpus/greek/corpora.py\n--- a/cltk/corpus/greek/corpora.py\n+++ b/cltk/corpus/greek/corpora.py\n@@ -42,6 +42,12 @@\n 'name': 'greek_treebank_perseus',\n 'location': 'remote',\n 'type': 'treebank'},\n+ {'encoding': 'utf-8',\n+ 'markup': 'xml',\n+ 'origin': 'https://github.com/vgorman1/Greek-Dependency-Trees.git',\n+ 'name': 'greek_treebank_gorman',\n+ 'location': 'remote',\n+ 'type': 'treebank'},\n {'encoding': 'xml',\n 'markup': 'plaintext',\n 'origin': 'https://github.com/cltk/greek_lexica_perseus.git',\n", "issue": "Add \"Gorman Trees\" corpus for Greek\nhttps://github.com/perseids-publications/gorman-trees = https://perseids-publications.github.io/gorman-trees/\r\n\r\n~500,000 tokens of parsed Ancient Greek.\n", "before_files": [{"content": "\"\"\"Greek language corpora available for download or loading locally.\nAll remote corpora hosted by github on the cltk organization account, eg:\n'http://github.com/cltk' + name\n\"\"\"\n\nGREEK_CORPORA = [\n {'name': 'greek_software_tlgu',\n 'origin': 'https://github.com/cltk/greek_software_tlgu.git',\n 'location': 'remote',\n 'type': 'software'},\n {'encoding': 'utf-8',\n 'markup': 'tei_xml',\n 'origin': 'https://github.com/cltk/greek_text_perseus.git',\n 'name': 'greek_text_perseus',\n 'location': 'remote',\n 'type': 'text'},\n {'encoding': 'latin-1',\n 'markup': 'beta_code',\n 'origin': None,\n 'name': 'phi7',\n 'location': 'local',\n 'type': 'text'},\n {'encoding': 'latin-1',\n 'markup': 'beta_code',\n 'name': 'tlg',\n 'origin': None,\n 'location': 'local',\n 'type': 'text'},\n {'encoding': 'utf-8',\n 'markup': 'plaintext',\n 'name': 'greek_proper_names_cltk',\n 'origin': 'https://github.com/cltk/greek_proper_names_cltk.git',\n 'location': 'remote',\n 'type': 'lexicon'},\n {'name': 'greek_models_cltk',\n 'origin': 'https://github.com/cltk/greek_models_cltk.git',\n 'location': 'remote',\n 'type': 'model'},\n {'encoding': 'utf-8',\n 'markup': 'xml',\n 'origin': 'https://github.com/cltk/greek_treebank_perseus.git',\n 'name': 'greek_treebank_perseus',\n 'location': 'remote',\n 'type': 'treebank'},\n {'encoding': 'xml',\n 'markup': 'plaintext',\n 'origin': 'https://github.com/cltk/greek_lexica_perseus.git',\n 'name': 'greek_lexica_perseus',\n 'location': 'remote',\n 'type': 'lexicon'},\n {'encoding': 'utf-8',\n 'markup': 'plaintext',\n 'origin': 'https://github.com/cltk/greek_training_set_sentence_cltk.git',\n 'name': 'greek_training_set_sentence_cltk',\n 'location': 'remote',\n 'type': 'training_set'},\n {'name': 'greek_word2vec_cltk',\n 'origin': 'https://github.com/cltk/greek_word2vec_cltk.git',\n 'location': 'remote',\n 'type': 'model'},\n {'name': 'greek_text_lacus_curtius',\n 'origin': 'https://github.com/cltk/greek_text_lacus_curtius.git',\n 'location': 'remote',\n 'type': 'text'},\n {'name': 'greek_text_first1kgreek',\n 'origin': 'https://github.com/cltk/First1KGreek',\n 'location': 'remote',\n 'type': 'text'},\n {'name': 'greek_text_tesserae',\n 'encoding': 'utf-8',\n 'markup': 'plaintext', #modified plaintext with Tesserae-style citations\n 'origin': 'https://github.com/cltk/greek_text_tesserae.git',\n 'location': 'remote',\n 'type': 'text'},\n]\n", "path": "cltk/corpus/greek/corpora.py"}], "after_files": [{"content": "\"\"\"Greek language corpora available for download or loading locally.\nAll remote corpora hosted by github on the cltk organization account, eg:\n'http://github.com/cltk' + name\n\"\"\"\n\nGREEK_CORPORA = [\n {'name': 'greek_software_tlgu',\n 'origin': 'https://github.com/cltk/greek_software_tlgu.git',\n 'location': 'remote',\n 'type': 'software'},\n {'encoding': 'utf-8',\n 'markup': 'tei_xml',\n 'origin': 'https://github.com/cltk/greek_text_perseus.git',\n 'name': 'greek_text_perseus',\n 'location': 'remote',\n 'type': 'text'},\n {'encoding': 'latin-1',\n 'markup': 'beta_code',\n 'origin': None,\n 'name': 'phi7',\n 'location': 'local',\n 'type': 'text'},\n {'encoding': 'latin-1',\n 'markup': 'beta_code',\n 'name': 'tlg',\n 'origin': None,\n 'location': 'local',\n 'type': 'text'},\n {'encoding': 'utf-8',\n 'markup': 'plaintext',\n 'name': 'greek_proper_names_cltk',\n 'origin': 'https://github.com/cltk/greek_proper_names_cltk.git',\n 'location': 'remote',\n 'type': 'lexicon'},\n {'name': 'greek_models_cltk',\n 'origin': 'https://github.com/cltk/greek_models_cltk.git',\n 'location': 'remote',\n 'type': 'model'},\n {'encoding': 'utf-8',\n 'markup': 'xml',\n 'origin': 'https://github.com/cltk/greek_treebank_perseus.git',\n 'name': 'greek_treebank_perseus',\n 'location': 'remote',\n 'type': 'treebank'},\n {'encoding': 'utf-8',\n 'markup': 'xml',\n 'origin': 'https://github.com/vgorman1/Greek-Dependency-Trees.git',\n 'name': 'greek_treebank_gorman',\n 'location': 'remote',\n 'type': 'treebank'},\n {'encoding': 'xml',\n 'markup': 'plaintext',\n 'origin': 'https://github.com/cltk/greek_lexica_perseus.git',\n 'name': 'greek_lexica_perseus',\n 'location': 'remote',\n 'type': 'lexicon'},\n {'encoding': 'utf-8',\n 'markup': 'plaintext',\n 'origin': 'https://github.com/cltk/greek_training_set_sentence_cltk.git',\n 'name': 'greek_training_set_sentence_cltk',\n 'location': 'remote',\n 'type': 'training_set'},\n {'name': 'greek_word2vec_cltk',\n 'origin': 'https://github.com/cltk/greek_word2vec_cltk.git',\n 'location': 'remote',\n 'type': 'model'},\n {'name': 'greek_text_lacus_curtius',\n 'origin': 'https://github.com/cltk/greek_text_lacus_curtius.git',\n 'location': 'remote',\n 'type': 'text'},\n {'name': 'greek_text_first1kgreek',\n 'origin': 'https://github.com/cltk/First1KGreek',\n 'location': 'remote',\n 'type': 'text'},\n {'name': 'greek_text_tesserae',\n 'encoding': 'utf-8',\n 'markup': 'plaintext', #modified plaintext with Tesserae-style citations\n 'origin': 'https://github.com/cltk/greek_text_tesserae.git',\n 'location': 'remote',\n 'type': 'text'},\n]\n", "path": "cltk/corpus/greek/corpora.py"}]}
1,217
201
gh_patches_debug_1199
rasdani/github-patches
git_diff
OpenNMT__OpenNMT-tf-6
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Poor translation results with the Transformer The Transformer model produces very bad translation results. Its implementation should be revised and fixed. See also the reference implementation at https://github.com/tensorflow/tensor2tensor. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `opennmt/utils/transformer.py` Content: ``` 1 """Define functions related to the Google's Transformer model.""" 2 3 import tensorflow as tf 4 5 6 def scaled_dot_attention(queries, 7 keys, 8 values, 9 mode, 10 values_length=None, 11 mask_future=False, 12 dropout=0.0): 13 """Computes the scaled dot-product attention as described 14 in https://arxiv.org/abs/1706.03762. 15 16 Args: 17 queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`. 18 keys: The sequence use to calculate attention scores. A tensor of shape 19 :math:`[B, T_2, ...]`. 20 values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`. 21 mode: A ``tf.estimator.ModeKeys`` mode. 22 values_length: The length of the values to attend. 23 mask_future: Mask attention to future positions. 24 dropout: The probability to drop units from the inputs. 25 26 Returns: 27 A tuple ``(context vector, attention vector)``. 28 """ 29 # Scaled dot-product between queries and keys. 30 dot = tf.matmul(queries, keys, transpose_b=True) 31 dot = tf.div(dot, tf.sqrt(tf.cast(tf.shape(keys)[-1], tf.float32))) 32 33 if values_length is not None: 34 # Give no weight to illegal connections. 35 if mask_future: 36 # When masking the future, a position can only attend to previous timesteps. 37 mask = tf.map_fn( 38 lambda x: tf.sequence_mask( 39 tf.minimum(tf.range(tf.shape(values)[1]) + 1, x), 40 maxlen=tf.shape(values)[1], 41 dtype=tf.float32), 42 values_length, 43 dtype=tf.float32) 44 else: 45 # Otherwise, simply prevent attention on out-of-range positions. 46 mask = tf.sequence_mask( 47 values_length, 48 maxlen=tf.shape(values)[1], 49 dtype=tf.float32) 50 mask = tf.expand_dims(mask, axis=1) 51 52 dot = dot * mask + ((1.0 - mask) * tf.float32.min) 53 54 # Compute attention weights. 55 attn = tf.nn.softmax(dot) 56 attn = tf.layers.dropout( 57 attn, 58 rate=dropout, 59 training=mode == tf.estimator.ModeKeys.TRAIN) 60 61 # Compute attention context. 62 context = tf.matmul(attn, values) 63 64 return context, attn 65 66 67 def multi_head_attention(num_heads, 68 queries, 69 keys, 70 values, 71 mode, 72 values_length=None, 73 mask_future=False, 74 dropout=0.0): 75 """Computes the multi-head attention as described in 76 https://arxiv.org/abs/1706.03762. 77 78 Args: 79 num_heads: The number of attention heads. 80 queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`. 81 keys: The sequence use to calculate attention scores. A tensor of shape 82 :math:`[B, T_2, ...]`. 83 values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`. 84 mode: A ``tf.estimator.ModeKeys`` mode. 85 values_length: The length of the values to attend. 86 mask_future: Mask attention to future positions. 87 dropout: The probability to drop units from the inputs. 88 89 Returns: 90 The concatenated attention context of each head. 91 """ 92 input_dim = keys.get_shape().as_list()[-1] 93 94 if input_dim % num_heads != 0: 95 raise ValueError("Multi head attention requires the input dimension to be a" 96 " multiple of {}".format(num_heads)) 97 98 head_dim = input_dim / num_heads 99 heads = [] 100 101 for i in range(num_heads): 102 with tf.variable_scope("head_{}".format(i)): 103 # Project queries, keys and values to different and smaller subspaces. 104 queries_proj = tf.layers.conv1d(queries, head_dim, 1) 105 keys_proj = tf.layers.conv1d(keys, head_dim, 1) 106 values_proj = tf.layers.conv1d(values, head_dim, 1) 107 108 head_i, _ = scaled_dot_attention( 109 queries_proj, 110 keys_proj, 111 values_proj, 112 mode, 113 values_length=values_length, 114 mask_future=mask_future, 115 dropout=dropout) 116 117 heads.append(head_i) 118 119 # Concatenate all heads output. 120 combined = tf.concat(heads, axis=2) 121 outputs = tf.layers.conv1d(combined, input_dim, 1) 122 123 return outputs 124 125 def feed_forward(x, inner_dim): 126 """Implements the Transformer's "Feed Forward" layer. 127 128 .. math:: 129 130 ffn(x) = max(0, x*W_1 + b_1)*W_2 + b_2 131 132 Args: 133 x: The input. 134 inner_dim: The number of units of the inner linear transformation. 135 136 Returns: 137 The transformed input. 138 """ 139 input_dim = x.get_shape().as_list()[-1] 140 141 inner = tf.layers.conv1d(x, inner_dim, 1, activation=tf.nn.relu) 142 outer = tf.layers.conv1d(inner, input_dim, 1) 143 144 return outer 145 146 def add_and_norm(inputs, 147 outputs, 148 mode, 149 dropout=0.1): 150 """Implements the Transformer's "Add & Norm" layer. 151 152 Args: 153 inputs: The input of the previous layer. 154 outputs: The output of the previous layer. 155 mode: A ``tf.estimator.ModeKeys`` mode. 156 dropout: The probability to drop units in :obj:`outputs`. 157 158 Returns: 159 The residual and normalized output. 160 """ 161 outputs = tf.layers.dropout( 162 outputs, 163 rate=dropout, 164 training=mode == tf.estimator.ModeKeys.TRAIN) 165 outputs += inputs 166 outputs = tf.contrib.layers.layer_norm(outputs) 167 return outputs 168 ``` --- 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/opennmt/utils/transformer.py b/opennmt/utils/transformer.py --- a/opennmt/utils/transformer.py +++ b/opennmt/utils/transformer.py @@ -163,5 +163,5 @@ rate=dropout, training=mode == tf.estimator.ModeKeys.TRAIN) outputs += inputs - outputs = tf.contrib.layers.layer_norm(outputs) + outputs = tf.contrib.layers.layer_norm(outputs, begin_norm_axis=-1) return outputs
{"golden_diff": "diff --git a/opennmt/utils/transformer.py b/opennmt/utils/transformer.py\n--- a/opennmt/utils/transformer.py\n+++ b/opennmt/utils/transformer.py\n@@ -163,5 +163,5 @@\n rate=dropout,\n training=mode == tf.estimator.ModeKeys.TRAIN)\n outputs += inputs\n- outputs = tf.contrib.layers.layer_norm(outputs)\n+ outputs = tf.contrib.layers.layer_norm(outputs, begin_norm_axis=-1)\n return outputs\n", "issue": "Poor translation results with the Transformer\nThe Transformer model produces very bad translation results. Its implementation should be revised and fixed.\r\n\r\nSee also the reference implementation at https://github.com/tensorflow/tensor2tensor.\n", "before_files": [{"content": "\"\"\"Define functions related to the Google's Transformer model.\"\"\"\n\nimport tensorflow as tf\n\n\ndef scaled_dot_attention(queries,\n keys,\n values,\n mode,\n values_length=None,\n mask_future=False,\n dropout=0.0):\n \"\"\"Computes the scaled dot-product attention as described\n in https://arxiv.org/abs/1706.03762.\n\n Args:\n queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`.\n keys: The sequence use to calculate attention scores. A tensor of shape\n :math:`[B, T_2, ...]`.\n values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`.\n mode: A ``tf.estimator.ModeKeys`` mode.\n values_length: The length of the values to attend.\n mask_future: Mask attention to future positions.\n dropout: The probability to drop units from the inputs.\n\n Returns:\n A tuple ``(context vector, attention vector)``.\n \"\"\"\n # Scaled dot-product between queries and keys.\n dot = tf.matmul(queries, keys, transpose_b=True)\n dot = tf.div(dot, tf.sqrt(tf.cast(tf.shape(keys)[-1], tf.float32)))\n\n if values_length is not None:\n # Give no weight to illegal connections.\n if mask_future:\n # When masking the future, a position can only attend to previous timesteps.\n mask = tf.map_fn(\n lambda x: tf.sequence_mask(\n tf.minimum(tf.range(tf.shape(values)[1]) + 1, x),\n maxlen=tf.shape(values)[1],\n dtype=tf.float32),\n values_length,\n dtype=tf.float32)\n else:\n # Otherwise, simply prevent attention on out-of-range positions.\n mask = tf.sequence_mask(\n values_length,\n maxlen=tf.shape(values)[1],\n dtype=tf.float32)\n mask = tf.expand_dims(mask, axis=1)\n\n dot = dot * mask + ((1.0 - mask) * tf.float32.min)\n\n # Compute attention weights.\n attn = tf.nn.softmax(dot)\n attn = tf.layers.dropout(\n attn,\n rate=dropout,\n training=mode == tf.estimator.ModeKeys.TRAIN)\n\n # Compute attention context.\n context = tf.matmul(attn, values)\n\n return context, attn\n\n\ndef multi_head_attention(num_heads,\n queries,\n keys,\n values,\n mode,\n values_length=None,\n mask_future=False,\n dropout=0.0):\n \"\"\"Computes the multi-head attention as described in\n https://arxiv.org/abs/1706.03762.\n\n Args:\n num_heads: The number of attention heads.\n queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`.\n keys: The sequence use to calculate attention scores. A tensor of shape\n :math:`[B, T_2, ...]`.\n values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`.\n mode: A ``tf.estimator.ModeKeys`` mode.\n values_length: The length of the values to attend.\n mask_future: Mask attention to future positions.\n dropout: The probability to drop units from the inputs.\n\n Returns:\n The concatenated attention context of each head.\n \"\"\"\n input_dim = keys.get_shape().as_list()[-1]\n\n if input_dim % num_heads != 0:\n raise ValueError(\"Multi head attention requires the input dimension to be a\"\n \" multiple of {}\".format(num_heads))\n\n head_dim = input_dim / num_heads\n heads = []\n\n for i in range(num_heads):\n with tf.variable_scope(\"head_{}\".format(i)):\n # Project queries, keys and values to different and smaller subspaces.\n queries_proj = tf.layers.conv1d(queries, head_dim, 1)\n keys_proj = tf.layers.conv1d(keys, head_dim, 1)\n values_proj = tf.layers.conv1d(values, head_dim, 1)\n\n head_i, _ = scaled_dot_attention(\n queries_proj,\n keys_proj,\n values_proj,\n mode,\n values_length=values_length,\n mask_future=mask_future,\n dropout=dropout)\n\n heads.append(head_i)\n\n # Concatenate all heads output.\n combined = tf.concat(heads, axis=2)\n outputs = tf.layers.conv1d(combined, input_dim, 1)\n\n return outputs\n\ndef feed_forward(x, inner_dim):\n \"\"\"Implements the Transformer's \"Feed Forward\" layer.\n\n .. math::\n\n ffn(x) = max(0, x*W_1 + b_1)*W_2 + b_2\n\n Args:\n x: The input.\n inner_dim: The number of units of the inner linear transformation.\n\n Returns:\n The transformed input.\n \"\"\"\n input_dim = x.get_shape().as_list()[-1]\n\n inner = tf.layers.conv1d(x, inner_dim, 1, activation=tf.nn.relu)\n outer = tf.layers.conv1d(inner, input_dim, 1)\n\n return outer\n\ndef add_and_norm(inputs,\n outputs,\n mode,\n dropout=0.1):\n \"\"\"Implements the Transformer's \"Add & Norm\" layer.\n\n Args:\n inputs: The input of the previous layer.\n outputs: The output of the previous layer.\n mode: A ``tf.estimator.ModeKeys`` mode.\n dropout: The probability to drop units in :obj:`outputs`.\n\n Returns:\n The residual and normalized output.\n \"\"\"\n outputs = tf.layers.dropout(\n outputs,\n rate=dropout,\n training=mode == tf.estimator.ModeKeys.TRAIN)\n outputs += inputs\n outputs = tf.contrib.layers.layer_norm(outputs)\n return outputs\n", "path": "opennmt/utils/transformer.py"}], "after_files": [{"content": "\"\"\"Define functions related to the Google's Transformer model.\"\"\"\n\nimport tensorflow as tf\n\n\ndef scaled_dot_attention(queries,\n keys,\n values,\n mode,\n values_length=None,\n mask_future=False,\n dropout=0.0):\n \"\"\"Computes the scaled dot-product attention as described\n in https://arxiv.org/abs/1706.03762.\n\n Args:\n queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`.\n keys: The sequence use to calculate attention scores. A tensor of shape\n :math:`[B, T_2, ...]`.\n values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`.\n mode: A ``tf.estimator.ModeKeys`` mode.\n values_length: The length of the values to attend.\n mask_future: Mask attention to future positions.\n dropout: The probability to drop units from the inputs.\n\n Returns:\n A tuple ``(context vector, attention vector)``.\n \"\"\"\n # Scaled dot-product between queries and keys.\n dot = tf.matmul(queries, keys, transpose_b=True)\n dot = tf.div(dot, tf.sqrt(tf.cast(tf.shape(keys)[-1], tf.float32)))\n\n if values_length is not None:\n # Give no weight to illegal connections.\n if mask_future:\n # When masking the future, a position can only attend to previous timesteps.\n mask = tf.map_fn(\n lambda x: tf.sequence_mask(\n tf.minimum(tf.range(tf.shape(values)[1]) + 1, x),\n maxlen=tf.shape(values)[1],\n dtype=tf.float32),\n values_length,\n dtype=tf.float32)\n else:\n # Otherwise, simply prevent attention on out-of-range positions.\n mask = tf.sequence_mask(\n values_length,\n maxlen=tf.shape(values)[1],\n dtype=tf.float32)\n mask = tf.expand_dims(mask, axis=1)\n\n dot = dot * mask + ((1.0 - mask) * tf.float32.min)\n\n # Compute attention weights.\n attn = tf.nn.softmax(dot)\n attn = tf.layers.dropout(\n attn,\n rate=dropout,\n training=mode == tf.estimator.ModeKeys.TRAIN)\n\n # Compute attention context.\n context = tf.matmul(attn, values)\n\n return context, attn\n\n\ndef multi_head_attention(num_heads,\n queries,\n keys,\n values,\n mode,\n values_length=None,\n mask_future=False,\n dropout=0.0):\n \"\"\"Computes the multi-head attention as described in\n https://arxiv.org/abs/1706.03762.\n\n Args:\n num_heads: The number of attention heads.\n queries: The sequence of queries. A tensor of shape :math:`[B, T_1, ...]`.\n keys: The sequence use to calculate attention scores. A tensor of shape\n :math:`[B, T_2, ...]`.\n values: The sequence to attend. A tensor of shape :math:`[B, T_2, ...]`.\n mode: A ``tf.estimator.ModeKeys`` mode.\n values_length: The length of the values to attend.\n mask_future: Mask attention to future positions.\n dropout: The probability to drop units from the inputs.\n\n Returns:\n The concatenated attention context of each head.\n \"\"\"\n input_dim = keys.get_shape().as_list()[-1]\n\n if input_dim % num_heads != 0:\n raise ValueError(\"Multi head attention requires the input dimension to be a\"\n \" multiple of {}\".format(num_heads))\n\n head_dim = input_dim / num_heads\n heads = []\n\n for i in range(num_heads):\n with tf.variable_scope(\"head_{}\".format(i)):\n # Project queries, keys and values to different and smaller subspaces.\n queries_proj = tf.layers.conv1d(queries, head_dim, 1)\n keys_proj = tf.layers.conv1d(keys, head_dim, 1)\n values_proj = tf.layers.conv1d(values, head_dim, 1)\n\n head_i, _ = scaled_dot_attention(\n queries_proj,\n keys_proj,\n values_proj,\n mode,\n values_length=values_length,\n mask_future=mask_future,\n dropout=dropout)\n\n heads.append(head_i)\n\n # Concatenate all heads output.\n combined = tf.concat(heads, axis=2)\n outputs = tf.layers.conv1d(combined, input_dim, 1)\n\n return outputs\n\ndef feed_forward(x, inner_dim):\n \"\"\"Implements the Transformer's \"Feed Forward\" layer.\n\n .. math::\n\n ffn(x) = max(0, x*W_1 + b_1)*W_2 + b_2\n\n Args:\n x: The input.\n inner_dim: The number of units of the inner linear transformation.\n\n Returns:\n The transformed input.\n \"\"\"\n input_dim = x.get_shape().as_list()[-1]\n\n inner = tf.layers.conv1d(x, inner_dim, 1, activation=tf.nn.relu)\n outer = tf.layers.conv1d(inner, input_dim, 1)\n\n return outer\n\ndef add_and_norm(inputs,\n outputs,\n mode,\n dropout=0.1):\n \"\"\"Implements the Transformer's \"Add & Norm\" layer.\n\n Args:\n inputs: The input of the previous layer.\n outputs: The output of the previous layer.\n mode: A ``tf.estimator.ModeKeys`` mode.\n dropout: The probability to drop units in :obj:`outputs`.\n\n Returns:\n The residual and normalized output.\n \"\"\"\n outputs = tf.layers.dropout(\n outputs,\n rate=dropout,\n training=mode == tf.estimator.ModeKeys.TRAIN)\n outputs += inputs\n outputs = tf.contrib.layers.layer_norm(outputs, begin_norm_axis=-1)\n return outputs\n", "path": "opennmt/utils/transformer.py"}]}
1,989
113
gh_patches_debug_11190
rasdani/github-patches
git_diff
freedomofpress__securedrop-4467
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add list of supported languages to the metadata API Whether or not a SecureDrop is available in one of the [supported languages](https://docs.securedrop.org/en/latest/admin.html#configuring-localization-for-the-source-interface-and-the-journalist-interface) is public information enumerated at the bottom of the source interface, but it's not currently exposed in the metadata API. Returning the list of supported languages along with the other instance metadata would be useful, including for the envisioned source interface scanner integrated with securedrop.org. # User Stories As a translator, I want to know which languages are currently used by SecureDrop users, so I know if and where my translations have real world impact. As a SecureDrop support team member, I want to know at a glance whether news organizations have configured supported languages, so I can point out to them if/when translations relevant to them are available. As a SecureDrop.org visitor, I'd like to know if a SecureDrop instance is available in the language I speak, so that I know if I can navigate it with confidence, and that it is likely to accept submissions in my language. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `securedrop/source_app/api.py` Content: ``` 1 import json 2 import platform 3 4 from flask import Blueprint, make_response 5 6 import version 7 8 9 def make_blueprint(config): 10 view = Blueprint('api', __name__) 11 12 @view.route('/metadata') 13 def metadata(): 14 meta = {'gpg_fpr': config.JOURNALIST_KEY, 15 'sd_version': version.__version__, 16 'server_os': platform.linux_distribution()[1], 17 } 18 resp = make_response(json.dumps(meta)) 19 resp.headers['Content-Type'] = 'application/json' 20 return resp 21 22 return view 23 ``` --- 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/securedrop/source_app/api.py b/securedrop/source_app/api.py --- a/securedrop/source_app/api.py +++ b/securedrop/source_app/api.py @@ -11,10 +11,12 @@ @view.route('/metadata') def metadata(): - meta = {'gpg_fpr': config.JOURNALIST_KEY, - 'sd_version': version.__version__, - 'server_os': platform.linux_distribution()[1], - } + meta = { + 'gpg_fpr': config.JOURNALIST_KEY, + 'sd_version': version.__version__, + 'server_os': platform.linux_distribution()[1], + 'supported_languages': config.SUPPORTED_LOCALES + } resp = make_response(json.dumps(meta)) resp.headers['Content-Type'] = 'application/json' return resp
{"golden_diff": "diff --git a/securedrop/source_app/api.py b/securedrop/source_app/api.py\n--- a/securedrop/source_app/api.py\n+++ b/securedrop/source_app/api.py\n@@ -11,10 +11,12 @@\n \n @view.route('/metadata')\n def metadata():\n- meta = {'gpg_fpr': config.JOURNALIST_KEY,\n- 'sd_version': version.__version__,\n- 'server_os': platform.linux_distribution()[1],\n- }\n+ meta = {\n+ 'gpg_fpr': config.JOURNALIST_KEY,\n+ 'sd_version': version.__version__,\n+ 'server_os': platform.linux_distribution()[1],\n+ 'supported_languages': config.SUPPORTED_LOCALES\n+ }\n resp = make_response(json.dumps(meta))\n resp.headers['Content-Type'] = 'application/json'\n return resp\n", "issue": "Add list of supported languages to the metadata API\nWhether or not a SecureDrop is available in one of the [supported languages](https://docs.securedrop.org/en/latest/admin.html#configuring-localization-for-the-source-interface-and-the-journalist-interface) is public information enumerated at the bottom of the source interface, but it's not currently exposed in the metadata API.\r\n\r\nReturning the list of supported languages along with the other instance metadata would be useful, including for the envisioned source interface scanner integrated with securedrop.org. \r\n\r\n# User Stories\r\n\r\nAs a translator, I want to know which languages are currently used by SecureDrop users, so I know if and where my translations have real world impact.\r\n\r\nAs a SecureDrop support team member, I want to know at a glance whether news organizations have configured supported languages, so I can point out to them if/when translations relevant to them are available.\r\n\r\nAs a SecureDrop.org visitor, I'd like to know if a SecureDrop instance is available in the language I speak, so that I know if I can navigate it with confidence, and that it is likely to accept submissions in my language.\n", "before_files": [{"content": "import json\nimport platform\n\nfrom flask import Blueprint, make_response\n\nimport version\n\n\ndef make_blueprint(config):\n view = Blueprint('api', __name__)\n\n @view.route('/metadata')\n def metadata():\n meta = {'gpg_fpr': config.JOURNALIST_KEY,\n 'sd_version': version.__version__,\n 'server_os': platform.linux_distribution()[1],\n }\n resp = make_response(json.dumps(meta))\n resp.headers['Content-Type'] = 'application/json'\n return resp\n\n return view\n", "path": "securedrop/source_app/api.py"}], "after_files": [{"content": "import json\nimport platform\n\nfrom flask import Blueprint, make_response\n\nimport version\n\n\ndef make_blueprint(config):\n view = Blueprint('api', __name__)\n\n @view.route('/metadata')\n def metadata():\n meta = {\n 'gpg_fpr': config.JOURNALIST_KEY,\n 'sd_version': version.__version__,\n 'server_os': platform.linux_distribution()[1],\n 'supported_languages': config.SUPPORTED_LOCALES\n }\n resp = make_response(json.dumps(meta))\n resp.headers['Content-Type'] = 'application/json'\n return resp\n\n return view\n", "path": "securedrop/source_app/api.py"}]}
643
191
gh_patches_debug_17916
rasdani/github-patches
git_diff
pex-tool__pex-556
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Release 1.4.7 docket of user-facing issues fixed: + #550: Pex 1.4.6 builds a failing pex --- 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__ = '1.4.6' 5 6 # Versions 34.0.0 through 35.0.2 (last pre-36.0.0) de-vendored dependencies which causes problems 7 # for pex code so we exclude that range. 8 SETUPTOOLS_REQUIREMENT = 'setuptools>=20.3,<41,!=34.*,!=35.*' 9 10 WHEEL_REQUIREMENT = 'wheel>=0.26.0,<0.32' 11 ``` Path: `setup.py` Content: ``` 1 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). 2 # Licensed under the Apache License, Version 2.0 (see LICENSE). 3 4 import os 5 6 from setuptools import setup 7 8 with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fp: 9 LONG_DESCRIPTION = fp.read() + '\n' 10 11 with open(os.path.join(os.path.dirname(__file__), 'CHANGES.rst')) as fp: 12 LONG_DESCRIPTION += fp.read() 13 14 15 # This seems to be a fairly standard version file pattern. 16 # 17 # Populates the following variables: 18 # __version__ 19 # __setuptools_requirement 20 # __wheel_requirement 21 __version__ = '' 22 version_py_file = os.path.join(os.path.dirname(__file__), 'pex', 'version.py') 23 with open(version_py_file) as version_py: 24 exec(compile(version_py.read(), version_py_file, 'exec')) 25 26 27 setup( 28 name = 'pex', 29 version = __version__, 30 description = "The PEX packaging toolchain.", 31 long_description = LONG_DESCRIPTION, 32 url = 'https://github.com/pantsbuild/pex', 33 license = 'Apache License, Version 2.0', 34 zip_safe = True, 35 classifiers = [ 36 'Intended Audience :: Developers', 37 'License :: OSI Approved :: Apache Software License', 38 'Operating System :: Unix', 39 'Operating System :: POSIX :: Linux', 40 'Operating System :: MacOS :: MacOS X', 41 'Programming Language :: Python', 42 'Programming Language :: Python :: 2', 43 'Programming Language :: Python :: 2.7', 44 'Programming Language :: Python :: 3', 45 'Programming Language :: Python :: 3.3', 46 'Programming Language :: Python :: 3.4', 47 'Programming Language :: Python :: 3.5', 48 'Programming Language :: Python :: 3.6', 49 ], 50 packages = [ 51 'pex', 52 'pex.bin', 53 'pex.commands', 54 ], 55 install_requires = [ 56 SETUPTOOLS_REQUIREMENT, 57 WHEEL_REQUIREMENT, 58 ], 59 extras_require={ 60 # For improved subprocess robustness under python2.7. 61 'subprocess': ['subprocess32>=3.2.7'], 62 # For improved requirement resolution and fetching robustness. 63 'requests': ['requests>=2.8.14'], 64 # For improved requirement resolution and fetching performance. 65 'cachecontrol': ['CacheControl>=0.12.3'], 66 }, 67 tests_require = [ 68 'mock', 69 'twitter.common.contextutil>=0.3.1,<0.4.0', 70 'twitter.common.lang>=0.3.1,<0.4.0', 71 'twitter.common.testing>=0.3.1,<0.4.0', 72 'twitter.common.dirutil>=0.3.1,<0.4.0', 73 'pytest', 74 ], 75 entry_points = { 76 'distutils.commands': [ 77 'bdist_pex = pex.commands.bdist_pex:bdist_pex', 78 ], 79 'console_scripts': [ 80 'pex = pex.bin.pex:main', 81 ], 82 }, 83 ) 84 ``` --- 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,7 +1,7 @@ # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). -__version__ = '1.4.6' +__version__ = '1.4.7' # Versions 34.0.0 through 35.0.2 (last pre-36.0.0) de-vendored dependencies which causes problems # for pex code so we exclude that range. diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -29,6 +29,7 @@ version = __version__, description = "The PEX packaging toolchain.", long_description = LONG_DESCRIPTION, + long_description_content_type="text/x-rst", url = 'https://github.com/pantsbuild/pex', license = 'Apache License, Version 2.0', zip_safe = True,
{"golden_diff": "diff --git a/pex/version.py b/pex/version.py\n--- a/pex/version.py\n+++ b/pex/version.py\n@@ -1,7 +1,7 @@\n # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n # Licensed under the Apache License, Version 2.0 (see LICENSE).\n \n-__version__ = '1.4.6'\n+__version__ = '1.4.7'\n \n # Versions 34.0.0 through 35.0.2 (last pre-36.0.0) de-vendored dependencies which causes problems\n # for pex code so we exclude that range.\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -29,6 +29,7 @@\n version = __version__,\n description = \"The PEX packaging toolchain.\",\n long_description = LONG_DESCRIPTION,\n+ long_description_content_type=\"text/x-rst\",\n url = 'https://github.com/pantsbuild/pex',\n license = 'Apache License, Version 2.0',\n zip_safe = True,\n", "issue": "Release 1.4.7\ndocket of user-facing issues fixed:\r\n+ #550: Pex 1.4.6 builds a failing pex\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__ = '1.4.6'\n\n# Versions 34.0.0 through 35.0.2 (last pre-36.0.0) de-vendored dependencies which causes problems\n# for pex code so we exclude that range.\nSETUPTOOLS_REQUIREMENT = 'setuptools>=20.3,<41,!=34.*,!=35.*'\n\nWHEEL_REQUIREMENT = 'wheel>=0.26.0,<0.32'\n", "path": "pex/version.py"}, {"content": "# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport os\n\nfrom setuptools import setup\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fp:\n LONG_DESCRIPTION = fp.read() + '\\n'\n\nwith open(os.path.join(os.path.dirname(__file__), 'CHANGES.rst')) as fp:\n LONG_DESCRIPTION += fp.read()\n\n\n# This seems to be a fairly standard version file pattern.\n#\n# Populates the following variables:\n# __version__\n# __setuptools_requirement\n# __wheel_requirement\n__version__ = ''\nversion_py_file = os.path.join(os.path.dirname(__file__), 'pex', 'version.py')\nwith open(version_py_file) as version_py:\n exec(compile(version_py.read(), version_py_file, 'exec'))\n\n\nsetup(\n name = 'pex',\n version = __version__,\n description = \"The PEX packaging toolchain.\",\n long_description = LONG_DESCRIPTION,\n url = 'https://github.com/pantsbuild/pex',\n license = 'Apache License, Version 2.0',\n zip_safe = True,\n classifiers = [\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: Unix',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: MacOS :: MacOS X',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n packages = [\n 'pex',\n 'pex.bin',\n 'pex.commands',\n ],\n install_requires = [\n SETUPTOOLS_REQUIREMENT,\n WHEEL_REQUIREMENT,\n ],\n extras_require={\n # For improved subprocess robustness under python2.7.\n 'subprocess': ['subprocess32>=3.2.7'],\n # For improved requirement resolution and fetching robustness.\n 'requests': ['requests>=2.8.14'],\n # For improved requirement resolution and fetching performance.\n 'cachecontrol': ['CacheControl>=0.12.3'],\n },\n tests_require = [\n 'mock',\n 'twitter.common.contextutil>=0.3.1,<0.4.0',\n 'twitter.common.lang>=0.3.1,<0.4.0',\n 'twitter.common.testing>=0.3.1,<0.4.0',\n 'twitter.common.dirutil>=0.3.1,<0.4.0',\n 'pytest',\n ],\n entry_points = {\n 'distutils.commands': [\n 'bdist_pex = pex.commands.bdist_pex:bdist_pex',\n ],\n 'console_scripts': [\n 'pex = pex.bin.pex:main',\n ],\n },\n)\n", "path": "setup.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__ = '1.4.7'\n\n# Versions 34.0.0 through 35.0.2 (last pre-36.0.0) de-vendored dependencies which causes problems\n# for pex code so we exclude that range.\nSETUPTOOLS_REQUIREMENT = 'setuptools>=20.3,<41,!=34.*,!=35.*'\n\nWHEEL_REQUIREMENT = 'wheel>=0.26.0,<0.32'\n", "path": "pex/version.py"}, {"content": "# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nimport os\n\nfrom setuptools import setup\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fp:\n LONG_DESCRIPTION = fp.read() + '\\n'\n\nwith open(os.path.join(os.path.dirname(__file__), 'CHANGES.rst')) as fp:\n LONG_DESCRIPTION += fp.read()\n\n\n# This seems to be a fairly standard version file pattern.\n#\n# Populates the following variables:\n# __version__\n# __setuptools_requirement\n# __wheel_requirement\n__version__ = ''\nversion_py_file = os.path.join(os.path.dirname(__file__), 'pex', 'version.py')\nwith open(version_py_file) as version_py:\n exec(compile(version_py.read(), version_py_file, 'exec'))\n\n\nsetup(\n name = 'pex',\n version = __version__,\n description = \"The PEX packaging toolchain.\",\n long_description = LONG_DESCRIPTION,\n long_description_content_type=\"text/x-rst\",\n url = 'https://github.com/pantsbuild/pex',\n license = 'Apache License, Version 2.0',\n zip_safe = True,\n classifiers = [\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: Unix',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: MacOS :: MacOS X',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n packages = [\n 'pex',\n 'pex.bin',\n 'pex.commands',\n ],\n install_requires = [\n SETUPTOOLS_REQUIREMENT,\n WHEEL_REQUIREMENT,\n ],\n extras_require={\n # For improved subprocess robustness under python2.7.\n 'subprocess': ['subprocess32>=3.2.7'],\n # For improved requirement resolution and fetching robustness.\n 'requests': ['requests>=2.8.14'],\n # For improved requirement resolution and fetching performance.\n 'cachecontrol': ['CacheControl>=0.12.3'],\n },\n tests_require = [\n 'mock',\n 'twitter.common.contextutil>=0.3.1,<0.4.0',\n 'twitter.common.lang>=0.3.1,<0.4.0',\n 'twitter.common.testing>=0.3.1,<0.4.0',\n 'twitter.common.dirutil>=0.3.1,<0.4.0',\n 'pytest',\n ],\n entry_points = {\n 'distutils.commands': [\n 'bdist_pex = pex.commands.bdist_pex:bdist_pex',\n ],\n 'console_scripts': [\n 'pex = pex.bin.pex:main',\n ],\n },\n)\n", "path": "setup.py"}]}
1,299
244
gh_patches_debug_2
rasdani/github-patches
git_diff
CTFd__CTFd-598
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Docker startup getting stuck on mysqladmin ping **Environment**: - CTFd Version/Commit: ctfd/ctfd:latest from Docker hub (17 days old) - Operating System: Amazon Linux AMI 2017.09.j x86_64 ECS HVM GP2 - Web Browser and Version: N/A **What happened?** Trying to setup CTFd with AWS ECS and RDS Aurora. If I don't set the DATABASE_URL env variable, it works fine and starts. If I do set the DATABASE_URL to mysql+pymysql://ctfd:<MYPASSWORD>@ctfd.<resource-id>i.eu-west-1.rds.amazonaws.com/ctfd I get stuck on docker-entrypoint.sh:7 `while ! mysqladmin ping -h db --silent; do` **What did you expect to happen?** That the ping should succeed and startup continue **How to reproduce your issue** Create an ECS task with ctfd/ctfd as image source, set env variable SECRET_KEY and DATABASE_URL. Start container. I have made sure the container can access the database by running `docker exec container-id mysql -h ctfd.<resource-id>.eu-west-1.rds.amazonaws.com -p<SECRET PASSWORD>` which works. **Any associated stack traces or error logs** Just stuck on "Waiting on MySQL" My question is basically: am I doing something wrong and should somehow make that "db" resolve to the database or is the script incorrect and should take the value of DATABASE_URL into account? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `wsgi.py` Content: ``` 1 from CTFd import create_app 2 3 app = create_app() 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/wsgi.py b/wsgi.py deleted file mode 100644 --- a/wsgi.py +++ /dev/null @@ -1,3 +0,0 @@ -from CTFd import create_app - -app = create_app()
{"golden_diff": "diff --git a/wsgi.py b/wsgi.py\ndeleted file mode 100644\n--- a/wsgi.py\n+++ /dev/null\n@@ -1,3 +0,0 @@\n-from CTFd import create_app\n-\n-app = create_app()\n", "issue": "Docker startup getting stuck on mysqladmin ping\n**Environment**:\r\n\r\n - CTFd Version/Commit: ctfd/ctfd:latest from Docker hub (17 days old)\r\n - Operating System: Amazon Linux AMI 2017.09.j x86_64 ECS HVM GP2\r\n - Web Browser and Version: N/A\r\n\r\n**What happened?**\r\n\r\nTrying to setup CTFd with AWS ECS and RDS Aurora.\r\nIf I don't set the DATABASE_URL env variable, it works fine and starts.\r\nIf I do set the DATABASE_URL to mysql+pymysql://ctfd:<MYPASSWORD>@ctfd.<resource-id>i.eu-west-1.rds.amazonaws.com/ctfd I get stuck on docker-entrypoint.sh:7 `while ! mysqladmin ping -h db --silent; do`\r\n\r\n**What did you expect to happen?**\r\n\r\nThat the ping should succeed and startup continue\r\n\r\n**How to reproduce your issue**\r\n\r\nCreate an ECS task with ctfd/ctfd as image source, set env variable SECRET_KEY and DATABASE_URL. Start container.\r\n\r\nI have made sure the container can access the database by running `docker exec container-id mysql -h ctfd.<resource-id>.eu-west-1.rds.amazonaws.com -p<SECRET PASSWORD>` which works.\r\n\r\n**Any associated stack traces or error logs**\r\n\r\nJust stuck on \"Waiting on MySQL\"\r\n\r\n\r\nMy question is basically: am I doing something wrong and should somehow make that \"db\" resolve to the database or is the script incorrect and should take the value of DATABASE_URL into account?\n", "before_files": [{"content": "from CTFd import create_app\n\napp = create_app()\n", "path": "wsgi.py"}], "after_files": [{"content": null, "path": "wsgi.py"}]}
605
58
gh_patches_debug_48613
rasdani/github-patches
git_diff
OpenEnergyPlatform__oeplatform-1475
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Scenario bundles: Output datasets render weirdly ## Description of the issue I added an output dataset for the WAM scenario for this factsheet: https://openenergy-platform.org/scenario-bundles/id/95a65aca-6915-b64a-cac7-3831c12885b4 ![grafik](https://github.com/OpenEnergyPlatform/oeplatform/assets/36844029/fa43133d-3cd7-4a22-80a0-384cbf6514e3) It reads wrongly and shows more than only the title of the dataset, i.e. it should only be rendered as: Rahmendaten für den Projektionsbericht 2023 (Datentabelle) - as it does for the WEM scenario (this was already existing before the new release). ## Steps to Reproduce 1. Add a dataset to a scenario 2. 3. ## Ideas of solution Describe possible ideas for solution and evaluate advantages and disadvantages. ## Context and Environment * Version used: * Operating system: * Environment setup and (python) version: ## Workflow checklist - [ ] I am aware of the workflow in [CONTRIBUTING.md](https://github.com/OpenEnergyPlatform/oeplatform/blob/develop/CONTRIBUTING.md) --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `oeplatform/__init__.py` Content: ``` 1 __version__ = "0.16.1" 2 ``` --- 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/oeplatform/__init__.py b/oeplatform/__init__.py --- a/oeplatform/__init__.py +++ b/oeplatform/__init__.py @@ -1 +1 @@ -__version__ = "0.16.1" +__version__ = "0.16.2"
{"golden_diff": "diff --git a/oeplatform/__init__.py b/oeplatform/__init__.py\n--- a/oeplatform/__init__.py\n+++ b/oeplatform/__init__.py\n@@ -1 +1 @@\n-__version__ = \"0.16.1\"\n+__version__ = \"0.16.2\"\n", "issue": "Scenario bundles: Output datasets render weirdly\n## Description of the issue\r\n\r\nI added an output dataset for the WAM scenario for this factsheet: https://openenergy-platform.org/scenario-bundles/id/95a65aca-6915-b64a-cac7-3831c12885b4\r\n\r\n![grafik](https://github.com/OpenEnergyPlatform/oeplatform/assets/36844029/fa43133d-3cd7-4a22-80a0-384cbf6514e3)\r\n\r\nIt reads wrongly and shows more than only the title of the dataset, i.e. it should only be rendered as: Rahmendaten f\u00fcr den Projektionsbericht 2023 (Datentabelle) - as it does for the WEM scenario (this was already existing before the new release). \r\n\r\n\r\n## Steps to Reproduce\r\n1. Add a dataset to a scenario\r\n2.\r\n3.\r\n\r\n## Ideas of solution\r\n\r\nDescribe possible ideas for solution and evaluate advantages and disadvantages.\r\n\r\n## Context and Environment\r\n* Version used: \r\n* Operating system: \r\n* Environment setup and (python) version: \r\n\r\n## Workflow checklist\r\n- [ ] I am aware of the workflow in [CONTRIBUTING.md](https://github.com/OpenEnergyPlatform/oeplatform/blob/develop/CONTRIBUTING.md)\r\n\n", "before_files": [{"content": "__version__ = \"0.16.1\"\n", "path": "oeplatform/__init__.py"}], "after_files": [{"content": "__version__ = \"0.16.2\"\n", "path": "oeplatform/__init__.py"}]}
574
72
gh_patches_debug_15901
rasdani/github-patches
git_diff
sql-machine-learning__elasticdl-322
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- build local docker image using docker python api for the edl client to build docker image locally, we need a wrapper for docker python sdk: https://pypi.org/project/docker firstly. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `elasticdl/client/client.py` Content: ``` 1 import os 2 import inspect 3 import shutil 4 import time 5 import getpass 6 from string import Template 7 8 def run(model_class, train_data_dir=None, 9 num_epoch=1, minibatch_size=10, 10 record_per_task=100, num_worker=1, grads_to_wait=2): 11 m_path, m_file = _getModelFile() 12 m_file_in_docker = "/model/" + m_file 13 timestamp = int(round(time.time() * 1000)) 14 _build_docker_image(m_path, m_file, m_file_in_docker, timestamp) 15 yaml_file = _generate_yaml(m_file_in_docker, model_class.__name__, train_data_dir=train_data_dir, 16 num_epoch=num_epoch, minibatch_size=minibatch_size, 17 record_per_task=record_per_task, num_worker=num_worker, 18 grads_to_wait=grads_to_wait, timestamp=timestamp) 19 _submit(yaml_file) 20 21 def _getModelFile(): 22 m_file = inspect.currentframe().f_back.f_back.f_code.co_filename 23 m_path = os.path.abspath(os.path.dirname(m_file)) 24 return m_path, m_file 25 26 def _build_docker_image(m_path, m_file, m_file_in_docker, timestamp): 27 d_path = os.path.abspath(os.path.dirname( 28 inspect.currentframe().f_back.f_code.co_filename)) 29 new_dfile = m_path + "/Dockerfile" 30 shutil.copyfile(d_path + "/../Dockerfile.dev", new_dfile) 31 32 with open(new_dfile, 'a') as df: 33 df.write("COPY " + m_file + " " + m_file_in_docker) 34 val = os.system('docker build -t elasticdl:dev_' + str(timestamp) + ' -f Dockerfile .') 35 36 # TODO: upload docker image to docker hub. 37 38 def _generate_yaml(m_file, m_class, 39 train_data_dir=None, num_epoch=1, 40 minibatch_size=10, record_per_task=100, 41 num_worker=1, grads_to_wait=2, timestamp=1): 42 YAML_TEMPLATE = """ 43 apiVersion: v1 44 kind: Pod 45 metadata: 46 name: elasticdl-master-$timestamp 47 labels: 48 purpose: test-command 49 spec: 50 containers: 51 - name: elasticdl-master-$timestamp 52 image: elasticdl:dev_$timestamp 53 command: ["python"] 54 args: ["-m", "elasticdl.master.main", 55 "--model-file", "$m_file", 56 "--num_worker", "$num_worker", 57 "--worker_image", "elasticdl:dev_$timestamp", 58 "--job_name", "elasticdl-$timestamp", 59 "--model-class", "$m_class", 60 "--train_data_dir", "$train_data_dir", 61 "--num_epoch", "$num_epoch", 62 "--grads_to_wait", "$grads_to_wait", 63 "--minibatch_size", "$minibatch_size", 64 "--record_per_task", "$record_per_task"] 65 imagePullPolicy: Never 66 env: 67 - name: MY_POD_IP 68 valueFrom: 69 fieldRef: 70 fieldPath: status.podIP 71 restartPolicy: Never 72 """ 73 t = Template(YAML_TEMPLATE) 74 yaml_file = 'job_desc.yaml' 75 with open(yaml_file, "w") as yaml: 76 yaml.write(t.substitute(m_file=m_file, m_class=m_class, 77 train_data_dir=train_data_dir, 78 timestamp=timestamp, num_worker=num_worker, num_epoch=num_epoch, 79 minibatch_size=minibatch_size, record_per_task=record_per_task, 80 user=getpass.getuser(), grads_to_wait=grads_to_wait)) 81 return yaml_file 82 83 def _submit(yaml_file): 84 os.system('kubectl create -f ' + yaml_file) 85 ``` --- 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/elasticdl/client/client.py b/elasticdl/client/client.py --- a/elasticdl/client/client.py +++ b/elasticdl/client/client.py @@ -4,6 +4,8 @@ import time import getpass from string import Template +import docker + def run(model_class, train_data_dir=None, num_epoch=1, minibatch_size=10, @@ -31,7 +33,9 @@ with open(new_dfile, 'a') as df: df.write("COPY " + m_file + " " + m_file_in_docker) - val = os.system('docker build -t elasticdl:dev_' + str(timestamp) + ' -f Dockerfile .') + client = docker.APIClient(base_url='unix://var/run/docker.sock') + for line in client.build(dockerfile='Dockerfile', path='.', tag='elasticdl:dev_' + str(timestamp)): + print(str(line, encoding = "utf-8")) # TODO: upload docker image to docker hub.
{"golden_diff": "diff --git a/elasticdl/client/client.py b/elasticdl/client/client.py\n--- a/elasticdl/client/client.py\n+++ b/elasticdl/client/client.py\n@@ -4,6 +4,8 @@\n import time\n import getpass\n from string import Template\n+import docker\n+\n \n def run(model_class, train_data_dir=None, \n num_epoch=1, minibatch_size=10, \n@@ -31,7 +33,9 @@\n \n with open(new_dfile, 'a') as df:\n df.write(\"COPY \" + m_file + \" \" + m_file_in_docker)\n- val = os.system('docker build -t elasticdl:dev_' + str(timestamp) + ' -f Dockerfile .')\n+ client = docker.APIClient(base_url='unix://var/run/docker.sock') \n+ for line in client.build(dockerfile='Dockerfile', path='.', tag='elasticdl:dev_' + str(timestamp)):\n+ print(str(line, encoding = \"utf-8\"))\n \n # TODO: upload docker image to docker hub.\n", "issue": "build local docker image using docker python api\nfor the edl client to build docker image locally, we need a wrapper for docker python sdk: https://pypi.org/project/docker firstly.\n", "before_files": [{"content": "import os\nimport inspect\nimport shutil\nimport time\nimport getpass\nfrom string import Template\n\ndef run(model_class, train_data_dir=None, \n num_epoch=1, minibatch_size=10, \n record_per_task=100, num_worker=1, grads_to_wait=2):\n m_path, m_file = _getModelFile()\n m_file_in_docker = \"/model/\" + m_file \n timestamp = int(round(time.time() * 1000))\n _build_docker_image(m_path, m_file, m_file_in_docker, timestamp)\n yaml_file = _generate_yaml(m_file_in_docker, model_class.__name__, train_data_dir=train_data_dir, \n num_epoch=num_epoch, minibatch_size=minibatch_size, \n record_per_task=record_per_task, num_worker=num_worker, \n grads_to_wait=grads_to_wait, timestamp=timestamp)\n _submit(yaml_file)\n\ndef _getModelFile():\n m_file = inspect.currentframe().f_back.f_back.f_code.co_filename\n m_path = os.path.abspath(os.path.dirname(m_file))\n return m_path, m_file\n\ndef _build_docker_image(m_path, m_file, m_file_in_docker, timestamp):\n d_path = os.path.abspath(os.path.dirname(\n inspect.currentframe().f_back.f_code.co_filename))\n new_dfile = m_path + \"/Dockerfile\"\n shutil.copyfile(d_path + \"/../Dockerfile.dev\", new_dfile)\n\n with open(new_dfile, 'a') as df:\n df.write(\"COPY \" + m_file + \" \" + m_file_in_docker)\n val = os.system('docker build -t elasticdl:dev_' + str(timestamp) + ' -f Dockerfile .')\n\n # TODO: upload docker image to docker hub.\n\ndef _generate_yaml(m_file, m_class,\n train_data_dir=None, num_epoch=1,\n minibatch_size=10, record_per_task=100, \n num_worker=1, grads_to_wait=2, timestamp=1):\n YAML_TEMPLATE = \"\"\"\n apiVersion: v1\n kind: Pod\n metadata:\n name: elasticdl-master-$timestamp\n labels:\n purpose: test-command\n spec:\n containers:\n - name: elasticdl-master-$timestamp\n image: elasticdl:dev_$timestamp\n command: [\"python\"]\n args: [\"-m\", \"elasticdl.master.main\",\n \"--model-file\", \"$m_file\",\n \"--num_worker\", \"$num_worker\",\n \"--worker_image\", \"elasticdl:dev_$timestamp\",\n \"--job_name\", \"elasticdl-$timestamp\",\n \"--model-class\", \"$m_class\",\n \"--train_data_dir\", \"$train_data_dir\",\n \"--num_epoch\", \"$num_epoch\",\n \"--grads_to_wait\", \"$grads_to_wait\",\n \"--minibatch_size\", \"$minibatch_size\",\n \"--record_per_task\", \"$record_per_task\"]\n imagePullPolicy: Never\n env:\n - name: MY_POD_IP\n valueFrom:\n fieldRef:\n fieldPath: status.podIP\n restartPolicy: Never\n \"\"\"\n t = Template(YAML_TEMPLATE)\n yaml_file = 'job_desc.yaml'\n with open(yaml_file, \"w\") as yaml:\n yaml.write(t.substitute(m_file=m_file, m_class=m_class, \n train_data_dir=train_data_dir, \n timestamp=timestamp, num_worker=num_worker, num_epoch=num_epoch,\n minibatch_size=minibatch_size, record_per_task=record_per_task,\n user=getpass.getuser(), grads_to_wait=grads_to_wait))\n return yaml_file\n\ndef _submit(yaml_file):\n os.system('kubectl create -f ' + yaml_file)\n", "path": "elasticdl/client/client.py"}], "after_files": [{"content": "import os\nimport inspect\nimport shutil\nimport time\nimport getpass\nfrom string import Template\nimport docker\n\n\ndef run(model_class, train_data_dir=None, \n num_epoch=1, minibatch_size=10, \n record_per_task=100, num_worker=1, grads_to_wait=2):\n m_path, m_file = _getModelFile()\n m_file_in_docker = \"/model/\" + m_file \n timestamp = int(round(time.time() * 1000))\n _build_docker_image(m_path, m_file, m_file_in_docker, timestamp)\n yaml_file = _generate_yaml(m_file_in_docker, model_class.__name__, train_data_dir=train_data_dir, \n num_epoch=num_epoch, minibatch_size=minibatch_size, \n record_per_task=record_per_task, num_worker=num_worker, \n grads_to_wait=grads_to_wait, timestamp=timestamp)\n _submit(yaml_file)\n\ndef _getModelFile():\n m_file = inspect.currentframe().f_back.f_back.f_code.co_filename\n m_path = os.path.abspath(os.path.dirname(m_file))\n return m_path, m_file\n\ndef _build_docker_image(m_path, m_file, m_file_in_docker, timestamp):\n d_path = os.path.abspath(os.path.dirname(\n inspect.currentframe().f_back.f_code.co_filename))\n new_dfile = m_path + \"/Dockerfile\"\n shutil.copyfile(d_path + \"/../Dockerfile.dev\", new_dfile)\n\n with open(new_dfile, 'a') as df:\n df.write(\"COPY \" + m_file + \" \" + m_file_in_docker)\n client = docker.APIClient(base_url='unix://var/run/docker.sock') \n for line in client.build(dockerfile='Dockerfile', path='.', tag='elasticdl:dev_' + str(timestamp)):\n print(str(line, encoding = \"utf-8\"))\n\n # TODO: upload docker image to docker hub.\n\ndef _generate_yaml(m_file, m_class,\n train_data_dir=None, num_epoch=1,\n minibatch_size=10, record_per_task=100, \n num_worker=1, grads_to_wait=2, timestamp=1):\n YAML_TEMPLATE = \"\"\"\n apiVersion: v1\n kind: Pod\n metadata:\n name: elasticdl-master-$timestamp\n labels:\n purpose: test-command\n spec:\n containers:\n - name: elasticdl-master-$timestamp\n image: elasticdl:dev_$timestamp\n command: [\"python\"]\n args: [\"-m\", \"elasticdl.master.main\",\n \"--model-file\", \"$m_file\",\n \"--num_worker\", \"$num_worker\",\n \"--worker_image\", \"elasticdl:dev_$timestamp\",\n \"--job_name\", \"elasticdl-$timestamp\",\n \"--model-class\", \"$m_class\",\n \"--train_data_dir\", \"$train_data_dir\",\n \"--num_epoch\", \"$num_epoch\",\n \"--grads_to_wait\", \"$grads_to_wait\",\n \"--minibatch_size\", \"$minibatch_size\",\n \"--record_per_task\", \"$record_per_task\"]\n imagePullPolicy: Never\n env:\n - name: MY_POD_IP\n valueFrom:\n fieldRef:\n fieldPath: status.podIP\n restartPolicy: Never\n \"\"\"\n t = Template(YAML_TEMPLATE)\n yaml_file = 'job_desc.yaml'\n with open(yaml_file, \"w\") as yaml:\n yaml.write(t.substitute(m_file=m_file, m_class=m_class, \n train_data_dir=train_data_dir, \n timestamp=timestamp, num_worker=num_worker, num_epoch=num_epoch,\n minibatch_size=minibatch_size, record_per_task=record_per_task,\n user=getpass.getuser(), grads_to_wait=grads_to_wait))\n return yaml_file\n\ndef _submit(yaml_file):\n os.system('kubectl create -f ' + yaml_file)\n", "path": "elasticdl/client/client.py"}]}
1,274
234
gh_patches_debug_34012
rasdani/github-patches
git_diff
deeppavlov__DeepPavlov-545
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Why Levenshtein Corrector make strange inserts inplace of punctuation marks? ``` from deeppavlov.deep import find_config, deep_download from deeppavlov.core.commands.infer import build_model_from_config config = find_config('levenshtein_corrector_ru') deep_download(config) model = build_model_from_config(config) print(model(['Сегодня.'])) print(model(['в 3 . Сегодня.'])) ``` Gives me > ['сегодня в'] > ['в 3 и сегодня и'] There are strange "." --> "в" and "." --> "и" inserts. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `deeppavlov/models/spelling_correction/levenshtein/searcher_component.py` Content: ``` 1 # Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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 math import log10 16 from typing import Iterable, List, Tuple 17 18 from deeppavlov.core.common.registry import register 19 from deeppavlov.core.models.component import Component 20 from deeppavlov.core.common.log import get_logger 21 22 from .levenshtein_searcher import LevenshteinSearcher 23 24 25 logger = get_logger(__name__) 26 27 28 @register('spelling_levenshtein') 29 class LevenshteinSearcherComponent(Component): 30 """Component that finds replacement candidates for tokens at a set Damerau-Levenshtein distance 31 32 Args: 33 words: list of every correct word 34 max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates 35 error_probability: assigned probability for every edit 36 37 Attributes: 38 max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates 39 error_probability: assigned logarithmic probability for every edit 40 vocab_penalty: assigned logarithmic probability of an out of vocabulary token being the correct one without 41 changes 42 """ 43 44 def __init__(self, words: Iterable[str], max_distance: int=1, error_probability: float=1e-4, *args, **kwargs): 45 words = list({word.strip().lower().replace('ё', 'е') for word in words}) 46 alphabet = sorted({letter for word in words for letter in word}) 47 self.max_distance = max_distance 48 self.error_probability = log10(error_probability) 49 self.vocab_penalty = self.error_probability * 2 50 self.searcher = LevenshteinSearcher(alphabet, words, allow_spaces=True, euristics=2) 51 52 def _infer_instance(self, tokens: Iterable[str]) -> List[List[Tuple[float, str]]]: 53 candidates = [] 54 for word in tokens: 55 c = {candidate: self.error_probability * distance 56 for candidate, distance in self.searcher.search(word, d=self.max_distance)} 57 c[word] = c.get(word, self.vocab_penalty) 58 candidates.append([(score, candidate) for candidate, score in c.items()]) 59 return candidates 60 61 def __call__(self, batch: Iterable[Iterable[str]], *args, **kwargs) -> List[List[List[Tuple[float, str]]]]: 62 """Propose candidates for tokens in sentences 63 64 Args: 65 batch: batch of tokenized sentences 66 67 Returns: 68 batch of lists of probabilities and candidates for every token 69 """ 70 return [self._infer_instance(tokens) for tokens in batch] 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/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py b/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py --- a/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py +++ b/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - +import string from math import log10 from typing import Iterable, List, Tuple @@ -41,6 +41,8 @@ changes """ + _punctuation = frozenset(string.punctuation) + def __init__(self, words: Iterable[str], max_distance: int=1, error_probability: float=1e-4, *args, **kwargs): words = list({word.strip().lower().replace('ё', 'е') for word in words}) alphabet = sorted({letter for word in words for letter in word}) @@ -52,10 +54,13 @@ def _infer_instance(self, tokens: Iterable[str]) -> List[List[Tuple[float, str]]]: candidates = [] for word in tokens: - c = {candidate: self.error_probability * distance - for candidate, distance in self.searcher.search(word, d=self.max_distance)} - c[word] = c.get(word, self.vocab_penalty) - candidates.append([(score, candidate) for candidate, score in c.items()]) + if word in self._punctuation: + candidates.append([(0, word)]) + else: + c = {candidate: self.error_probability * distance + for candidate, distance in self.searcher.search(word, d=self.max_distance)} + c[word] = c.get(word, self.vocab_penalty) + candidates.append([(score, candidate) for candidate, score in c.items()]) return candidates def __call__(self, batch: Iterable[Iterable[str]], *args, **kwargs) -> List[List[List[Tuple[float, str]]]]:
{"golden_diff": "diff --git a/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py b/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py\n--- a/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py\n+++ b/deeppavlov/models/spelling_correction/levenshtein/searcher_component.py\n@@ -11,7 +11,7 @@\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+import string\n from math import log10\n from typing import Iterable, List, Tuple\n \n@@ -41,6 +41,8 @@\n changes\n \"\"\"\n \n+ _punctuation = frozenset(string.punctuation)\n+\n def __init__(self, words: Iterable[str], max_distance: int=1, error_probability: float=1e-4, *args, **kwargs):\n words = list({word.strip().lower().replace('\u0451', '\u0435') for word in words})\n alphabet = sorted({letter for word in words for letter in word})\n@@ -52,10 +54,13 @@\n def _infer_instance(self, tokens: Iterable[str]) -> List[List[Tuple[float, str]]]:\n candidates = []\n for word in tokens:\n- c = {candidate: self.error_probability * distance\n- for candidate, distance in self.searcher.search(word, d=self.max_distance)}\n- c[word] = c.get(word, self.vocab_penalty)\n- candidates.append([(score, candidate) for candidate, score in c.items()])\n+ if word in self._punctuation:\n+ candidates.append([(0, word)])\n+ else:\n+ c = {candidate: self.error_probability * distance\n+ for candidate, distance in self.searcher.search(word, d=self.max_distance)}\n+ c[word] = c.get(word, self.vocab_penalty)\n+ candidates.append([(score, candidate) for candidate, score in c.items()])\n return candidates\n \n def __call__(self, batch: Iterable[Iterable[str]], *args, **kwargs) -> List[List[List[Tuple[float, str]]]]:\n", "issue": "Why Levenshtein Corrector make strange inserts inplace of punctuation marks?\n```\r\nfrom deeppavlov.deep import find_config, deep_download\r\nfrom deeppavlov.core.commands.infer import build_model_from_config\r\nconfig = find_config('levenshtein_corrector_ru')\r\ndeep_download(config)\r\nmodel = build_model_from_config(config)\r\nprint(model(['\u0421\u0435\u0433\u043e\u0434\u043d\u044f.']))\r\nprint(model(['\u0432 3 . \u0421\u0435\u0433\u043e\u0434\u043d\u044f.']))\r\n```\r\nGives me\r\n> ['\u0441\u0435\u0433\u043e\u0434\u043d\u044f \u0432']\r\n> ['\u0432 3 \u0438 \u0441\u0435\u0433\u043e\u0434\u043d\u044f \u0438']\r\n\r\nThere are strange \".\" --> \"\u0432\" and \".\" --> \"\u0438\" inserts.\n", "before_files": [{"content": "# Copyright 2017 Neural Networks and Deep Learning lab, MIPT\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 math import log10\nfrom typing import Iterable, List, Tuple\n\nfrom deeppavlov.core.common.registry import register\nfrom deeppavlov.core.models.component import Component\nfrom deeppavlov.core.common.log import get_logger\n\nfrom .levenshtein_searcher import LevenshteinSearcher\n\n\nlogger = get_logger(__name__)\n\n\n@register('spelling_levenshtein')\nclass LevenshteinSearcherComponent(Component):\n \"\"\"Component that finds replacement candidates for tokens at a set Damerau-Levenshtein distance\n\n Args:\n words: list of every correct word\n max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates\n error_probability: assigned probability for every edit\n\n Attributes:\n max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates\n error_probability: assigned logarithmic probability for every edit\n vocab_penalty: assigned logarithmic probability of an out of vocabulary token being the correct one without\n changes\n \"\"\"\n\n def __init__(self, words: Iterable[str], max_distance: int=1, error_probability: float=1e-4, *args, **kwargs):\n words = list({word.strip().lower().replace('\u0451', '\u0435') for word in words})\n alphabet = sorted({letter for word in words for letter in word})\n self.max_distance = max_distance\n self.error_probability = log10(error_probability)\n self.vocab_penalty = self.error_probability * 2\n self.searcher = LevenshteinSearcher(alphabet, words, allow_spaces=True, euristics=2)\n\n def _infer_instance(self, tokens: Iterable[str]) -> List[List[Tuple[float, str]]]:\n candidates = []\n for word in tokens:\n c = {candidate: self.error_probability * distance\n for candidate, distance in self.searcher.search(word, d=self.max_distance)}\n c[word] = c.get(word, self.vocab_penalty)\n candidates.append([(score, candidate) for candidate, score in c.items()])\n return candidates\n\n def __call__(self, batch: Iterable[Iterable[str]], *args, **kwargs) -> List[List[List[Tuple[float, str]]]]:\n \"\"\"Propose candidates for tokens in sentences\n\n Args:\n batch: batch of tokenized sentences\n\n Returns:\n batch of lists of probabilities and candidates for every token\n \"\"\"\n return [self._infer_instance(tokens) for tokens in batch]\n", "path": "deeppavlov/models/spelling_correction/levenshtein/searcher_component.py"}], "after_files": [{"content": "# Copyright 2017 Neural Networks and Deep Learning lab, MIPT\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.\nimport string\nfrom math import log10\nfrom typing import Iterable, List, Tuple\n\nfrom deeppavlov.core.common.registry import register\nfrom deeppavlov.core.models.component import Component\nfrom deeppavlov.core.common.log import get_logger\n\nfrom .levenshtein_searcher import LevenshteinSearcher\n\n\nlogger = get_logger(__name__)\n\n\n@register('spelling_levenshtein')\nclass LevenshteinSearcherComponent(Component):\n \"\"\"Component that finds replacement candidates for tokens at a set Damerau-Levenshtein distance\n\n Args:\n words: list of every correct word\n max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates\n error_probability: assigned probability for every edit\n\n Attributes:\n max_distance: maximum allowed Damerau-Levenshtein distance between source words and candidates\n error_probability: assigned logarithmic probability for every edit\n vocab_penalty: assigned logarithmic probability of an out of vocabulary token being the correct one without\n changes\n \"\"\"\n\n _punctuation = frozenset(string.punctuation)\n\n def __init__(self, words: Iterable[str], max_distance: int=1, error_probability: float=1e-4, *args, **kwargs):\n words = list({word.strip().lower().replace('\u0451', '\u0435') for word in words})\n alphabet = sorted({letter for word in words for letter in word})\n self.max_distance = max_distance\n self.error_probability = log10(error_probability)\n self.vocab_penalty = self.error_probability * 2\n self.searcher = LevenshteinSearcher(alphabet, words, allow_spaces=True, euristics=2)\n\n def _infer_instance(self, tokens: Iterable[str]) -> List[List[Tuple[float, str]]]:\n candidates = []\n for word in tokens:\n if word in self._punctuation:\n candidates.append([(0, word)])\n else:\n c = {candidate: self.error_probability * distance\n for candidate, distance in self.searcher.search(word, d=self.max_distance)}\n c[word] = c.get(word, self.vocab_penalty)\n candidates.append([(score, candidate) for candidate, score in c.items()])\n return candidates\n\n def __call__(self, batch: Iterable[Iterable[str]], *args, **kwargs) -> List[List[List[Tuple[float, str]]]]:\n \"\"\"Propose candidates for tokens in sentences\n\n Args:\n batch: batch of tokenized sentences\n\n Returns:\n batch of lists of probabilities and candidates for every token\n \"\"\"\n return [self._infer_instance(tokens) for tokens in batch]\n", "path": "deeppavlov/models/spelling_correction/levenshtein/searcher_component.py"}]}
1,203
481
gh_patches_debug_42258
rasdani/github-patches
git_diff
getsentry__sentry-61362
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Streamline issue platfrom message processing for non-Kafka envs From https://github.com/getsentry/sentry/pull/59330#pullrequestreview-1713484895, We can simplify the logic and make our tests more meaningful by not duplicating the message processing logic in dev environments. Instead, we can massage the message format to match a Kafka payloads and directly call `process_message`. --- 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/sentry/issues/producer.py` Content: ``` 1 from __future__ import annotations 2 3 import logging 4 from typing import Any, Dict, MutableMapping, Optional, cast 5 6 from arroyo import Topic 7 from arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration 8 from django.conf import settings 9 10 from sentry import features 11 from sentry.issues.issue_occurrence import IssueOccurrence 12 from sentry.issues.status_change_consumer import bulk_get_groups_from_fingerprints, update_status 13 from sentry.issues.status_change_message import StatusChangeMessage 14 from sentry.models.project import Project 15 from sentry.services.hybrid_cloud import ValueEqualityEnum 16 from sentry.utils import json 17 from sentry.utils.arroyo_producer import SingletonProducer 18 from sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition 19 20 logger = logging.getLogger(__name__) 21 22 23 class PayloadType(ValueEqualityEnum): 24 OCCURRENCE = "occurrence" 25 STATUS_CHANGE = "status_change" 26 27 28 def _get_occurrence_producer() -> KafkaProducer: 29 cluster_name = get_topic_definition(settings.KAFKA_INGEST_OCCURRENCES)["cluster"] 30 producer_config = get_kafka_producer_cluster_options(cluster_name) 31 producer_config.pop("compression.type", None) 32 producer_config.pop("message.max.bytes", None) 33 return KafkaProducer(build_kafka_configuration(default_config=producer_config)) 34 35 36 _occurrence_producer = SingletonProducer( 37 _get_occurrence_producer, max_futures=settings.SENTRY_ISSUE_PLATFORM_FUTURES_MAX_LIMIT 38 ) 39 40 41 def produce_occurrence_to_kafka( 42 payload_type: PayloadType | None = PayloadType.OCCURRENCE, 43 occurrence: IssueOccurrence | None = None, 44 status_change: StatusChangeMessage | None = None, 45 event_data: Optional[Dict[str, Any]] = None, 46 ) -> None: 47 payload_data = None 48 if payload_type == PayloadType.OCCURRENCE: 49 payload_data = _prepare_occurrence_message(occurrence, event_data) 50 elif payload_type == PayloadType.STATUS_CHANGE: 51 payload_data = _prepare_status_change_message(status_change) 52 else: 53 raise NotImplementedError(f"Unknown payload type: {payload_type}") 54 55 if payload_data is None: 56 return 57 58 payload = KafkaPayload(None, json.dumps(payload_data).encode("utf-8"), []) 59 _occurrence_producer.produce(Topic(settings.KAFKA_INGEST_OCCURRENCES), payload) 60 61 62 def _prepare_occurrence_message( 63 occurrence: IssueOccurrence | None, event_data: Optional[Dict[str, Any]] 64 ) -> MutableMapping[str, Any] | None: 65 if not occurrence: 66 raise ValueError("occurrence must be provided") 67 if event_data and occurrence.event_id != event_data["event_id"]: 68 raise ValueError("Event id on occurrence and event_data must be the same") 69 if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream": 70 # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just 71 # write to the issue platform directly 72 from sentry.issues.ingest import process_occurrence_data 73 from sentry.issues.occurrence_consumer import ( 74 lookup_event_and_process_issue_occurrence, 75 process_event_and_issue_occurrence, 76 ) 77 78 occurrence_dict = occurrence.to_dict() 79 process_occurrence_data(occurrence_dict) 80 if event_data: 81 process_event_and_issue_occurrence(occurrence_dict, event_data) 82 else: 83 lookup_event_and_process_issue_occurrence(occurrence_dict) 84 return None 85 86 payload_data = cast(MutableMapping[str, Any], occurrence.to_dict()) 87 payload_data["payload_type"] = PayloadType.OCCURRENCE.value 88 if event_data: 89 payload_data["event"] = event_data 90 91 return payload_data 92 93 94 def _prepare_status_change_message( 95 status_change: StatusChangeMessage | None, 96 ) -> MutableMapping[str, Any] | None: 97 if not status_change: 98 raise ValueError("status_change must be provided") 99 100 organization = Project.objects.get(id=status_change.project_id).organization 101 if not features.has("organizations:issue-platform-api-crons-sd", organization): 102 return None 103 104 if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream": 105 # Do the change 106 # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just 107 # write to the issue platform directly 108 from sentry.issues.ingest import process_occurrence_data 109 110 process_occurrence_data(status_change.to_dict()) 111 fingerprint = status_change.fingerprint 112 groups_by_fingerprints = bulk_get_groups_from_fingerprints( 113 [(status_change.project_id, fingerprint)] 114 ) 115 116 key = (status_change.project_id, fingerprint[0]) 117 group = groups_by_fingerprints.get(key, None) 118 if not group: 119 return None 120 update_status(group, status_change.to_dict()) 121 return None 122 123 payload_data = cast(MutableMapping[str, Any], status_change.to_dict()) 124 payload_data["payload_type"] = PayloadType.STATUS_CHANGE.value 125 return payload_data 126 ``` --- 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/sentry/issues/producer.py b/src/sentry/issues/producer.py --- a/src/sentry/issues/producer.py +++ b/src/sentry/issues/producer.py @@ -5,11 +5,12 @@ from arroyo import Topic from arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration +from arroyo.types import Message, Value from django.conf import settings from sentry import features from sentry.issues.issue_occurrence import IssueOccurrence -from sentry.issues.status_change_consumer import bulk_get_groups_from_fingerprints, update_status +from sentry.issues.run import process_message from sentry.issues.status_change_message import StatusChangeMessage from sentry.models.project import Project from sentry.services.hybrid_cloud import ValueEqualityEnum @@ -56,6 +57,12 @@ return payload = KafkaPayload(None, json.dumps(payload_data).encode("utf-8"), []) + if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream": + # If we're not running Kafka then we're just in dev. + # Skip producing to Kafka and just process the message directly + process_message(Message(Value(payload=payload, committable={}))) + return + _occurrence_producer.produce(Topic(settings.KAFKA_INGEST_OCCURRENCES), payload) @@ -66,22 +73,6 @@ raise ValueError("occurrence must be provided") if event_data and occurrence.event_id != event_data["event_id"]: raise ValueError("Event id on occurrence and event_data must be the same") - if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream": - # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just - # write to the issue platform directly - from sentry.issues.ingest import process_occurrence_data - from sentry.issues.occurrence_consumer import ( - lookup_event_and_process_issue_occurrence, - process_event_and_issue_occurrence, - ) - - occurrence_dict = occurrence.to_dict() - process_occurrence_data(occurrence_dict) - if event_data: - process_event_and_issue_occurrence(occurrence_dict, event_data) - else: - lookup_event_and_process_issue_occurrence(occurrence_dict) - return None payload_data = cast(MutableMapping[str, Any], occurrence.to_dict()) payload_data["payload_type"] = PayloadType.OCCURRENCE.value @@ -101,25 +92,6 @@ if not features.has("organizations:issue-platform-api-crons-sd", organization): return None - if settings.SENTRY_EVENTSTREAM != "sentry.eventstream.kafka.KafkaEventStream": - # Do the change - # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just - # write to the issue platform directly - from sentry.issues.ingest import process_occurrence_data - - process_occurrence_data(status_change.to_dict()) - fingerprint = status_change.fingerprint - groups_by_fingerprints = bulk_get_groups_from_fingerprints( - [(status_change.project_id, fingerprint)] - ) - - key = (status_change.project_id, fingerprint[0]) - group = groups_by_fingerprints.get(key, None) - if not group: - return None - update_status(group, status_change.to_dict()) - return None - payload_data = cast(MutableMapping[str, Any], status_change.to_dict()) payload_data["payload_type"] = PayloadType.STATUS_CHANGE.value return payload_data
{"golden_diff": "diff --git a/src/sentry/issues/producer.py b/src/sentry/issues/producer.py\n--- a/src/sentry/issues/producer.py\n+++ b/src/sentry/issues/producer.py\n@@ -5,11 +5,12 @@\n \n from arroyo import Topic\n from arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration\n+from arroyo.types import Message, Value\n from django.conf import settings\n \n from sentry import features\n from sentry.issues.issue_occurrence import IssueOccurrence\n-from sentry.issues.status_change_consumer import bulk_get_groups_from_fingerprints, update_status\n+from sentry.issues.run import process_message\n from sentry.issues.status_change_message import StatusChangeMessage\n from sentry.models.project import Project\n from sentry.services.hybrid_cloud import ValueEqualityEnum\n@@ -56,6 +57,12 @@\n return\n \n payload = KafkaPayload(None, json.dumps(payload_data).encode(\"utf-8\"), [])\n+ if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n+ # If we're not running Kafka then we're just in dev.\n+ # Skip producing to Kafka and just process the message directly\n+ process_message(Message(Value(payload=payload, committable={})))\n+ return\n+\n _occurrence_producer.produce(Topic(settings.KAFKA_INGEST_OCCURRENCES), payload)\n \n \n@@ -66,22 +73,6 @@\n raise ValueError(\"occurrence must be provided\")\n if event_data and occurrence.event_id != event_data[\"event_id\"]:\n raise ValueError(\"Event id on occurrence and event_data must be the same\")\n- if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n- # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just\n- # write to the issue platform directly\n- from sentry.issues.ingest import process_occurrence_data\n- from sentry.issues.occurrence_consumer import (\n- lookup_event_and_process_issue_occurrence,\n- process_event_and_issue_occurrence,\n- )\n-\n- occurrence_dict = occurrence.to_dict()\n- process_occurrence_data(occurrence_dict)\n- if event_data:\n- process_event_and_issue_occurrence(occurrence_dict, event_data)\n- else:\n- lookup_event_and_process_issue_occurrence(occurrence_dict)\n- return None\n \n payload_data = cast(MutableMapping[str, Any], occurrence.to_dict())\n payload_data[\"payload_type\"] = PayloadType.OCCURRENCE.value\n@@ -101,25 +92,6 @@\n if not features.has(\"organizations:issue-platform-api-crons-sd\", organization):\n return None\n \n- if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n- # Do the change\n- # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just\n- # write to the issue platform directly\n- from sentry.issues.ingest import process_occurrence_data\n-\n- process_occurrence_data(status_change.to_dict())\n- fingerprint = status_change.fingerprint\n- groups_by_fingerprints = bulk_get_groups_from_fingerprints(\n- [(status_change.project_id, fingerprint)]\n- )\n-\n- key = (status_change.project_id, fingerprint[0])\n- group = groups_by_fingerprints.get(key, None)\n- if not group:\n- return None\n- update_status(group, status_change.to_dict())\n- return None\n-\n payload_data = cast(MutableMapping[str, Any], status_change.to_dict())\n payload_data[\"payload_type\"] = PayloadType.STATUS_CHANGE.value\n return payload_data\n", "issue": "Streamline issue platfrom message processing for non-Kafka envs\nFrom https://github.com/getsentry/sentry/pull/59330#pullrequestreview-1713484895, \n\nWe can simplify the logic and make our tests more meaningful by not duplicating the message processing logic in dev environments. Instead, we can massage the message format to match a Kafka payloads and directly call `process_message`. \n", "before_files": [{"content": "from __future__ import annotations\n\nimport logging\nfrom typing import Any, Dict, MutableMapping, Optional, cast\n\nfrom arroyo import Topic\nfrom arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration\nfrom django.conf import settings\n\nfrom sentry import features\nfrom sentry.issues.issue_occurrence import IssueOccurrence\nfrom sentry.issues.status_change_consumer import bulk_get_groups_from_fingerprints, update_status\nfrom sentry.issues.status_change_message import StatusChangeMessage\nfrom sentry.models.project import Project\nfrom sentry.services.hybrid_cloud import ValueEqualityEnum\nfrom sentry.utils import json\nfrom sentry.utils.arroyo_producer import SingletonProducer\nfrom sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition\n\nlogger = logging.getLogger(__name__)\n\n\nclass PayloadType(ValueEqualityEnum):\n OCCURRENCE = \"occurrence\"\n STATUS_CHANGE = \"status_change\"\n\n\ndef _get_occurrence_producer() -> KafkaProducer:\n cluster_name = get_topic_definition(settings.KAFKA_INGEST_OCCURRENCES)[\"cluster\"]\n producer_config = get_kafka_producer_cluster_options(cluster_name)\n producer_config.pop(\"compression.type\", None)\n producer_config.pop(\"message.max.bytes\", None)\n return KafkaProducer(build_kafka_configuration(default_config=producer_config))\n\n\n_occurrence_producer = SingletonProducer(\n _get_occurrence_producer, max_futures=settings.SENTRY_ISSUE_PLATFORM_FUTURES_MAX_LIMIT\n)\n\n\ndef produce_occurrence_to_kafka(\n payload_type: PayloadType | None = PayloadType.OCCURRENCE,\n occurrence: IssueOccurrence | None = None,\n status_change: StatusChangeMessage | None = None,\n event_data: Optional[Dict[str, Any]] = None,\n) -> None:\n payload_data = None\n if payload_type == PayloadType.OCCURRENCE:\n payload_data = _prepare_occurrence_message(occurrence, event_data)\n elif payload_type == PayloadType.STATUS_CHANGE:\n payload_data = _prepare_status_change_message(status_change)\n else:\n raise NotImplementedError(f\"Unknown payload type: {payload_type}\")\n\n if payload_data is None:\n return\n\n payload = KafkaPayload(None, json.dumps(payload_data).encode(\"utf-8\"), [])\n _occurrence_producer.produce(Topic(settings.KAFKA_INGEST_OCCURRENCES), payload)\n\n\ndef _prepare_occurrence_message(\n occurrence: IssueOccurrence | None, event_data: Optional[Dict[str, Any]]\n) -> MutableMapping[str, Any] | None:\n if not occurrence:\n raise ValueError(\"occurrence must be provided\")\n if event_data and occurrence.event_id != event_data[\"event_id\"]:\n raise ValueError(\"Event id on occurrence and event_data must be the same\")\n if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just\n # write to the issue platform directly\n from sentry.issues.ingest import process_occurrence_data\n from sentry.issues.occurrence_consumer import (\n lookup_event_and_process_issue_occurrence,\n process_event_and_issue_occurrence,\n )\n\n occurrence_dict = occurrence.to_dict()\n process_occurrence_data(occurrence_dict)\n if event_data:\n process_event_and_issue_occurrence(occurrence_dict, event_data)\n else:\n lookup_event_and_process_issue_occurrence(occurrence_dict)\n return None\n\n payload_data = cast(MutableMapping[str, Any], occurrence.to_dict())\n payload_data[\"payload_type\"] = PayloadType.OCCURRENCE.value\n if event_data:\n payload_data[\"event\"] = event_data\n\n return payload_data\n\n\ndef _prepare_status_change_message(\n status_change: StatusChangeMessage | None,\n) -> MutableMapping[str, Any] | None:\n if not status_change:\n raise ValueError(\"status_change must be provided\")\n\n organization = Project.objects.get(id=status_change.project_id).organization\n if not features.has(\"organizations:issue-platform-api-crons-sd\", organization):\n return None\n\n if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n # Do the change\n # If we're not running Kafka then we're just in dev. Skip producing to Kafka and just\n # write to the issue platform directly\n from sentry.issues.ingest import process_occurrence_data\n\n process_occurrence_data(status_change.to_dict())\n fingerprint = status_change.fingerprint\n groups_by_fingerprints = bulk_get_groups_from_fingerprints(\n [(status_change.project_id, fingerprint)]\n )\n\n key = (status_change.project_id, fingerprint[0])\n group = groups_by_fingerprints.get(key, None)\n if not group:\n return None\n update_status(group, status_change.to_dict())\n return None\n\n payload_data = cast(MutableMapping[str, Any], status_change.to_dict())\n payload_data[\"payload_type\"] = PayloadType.STATUS_CHANGE.value\n return payload_data\n", "path": "src/sentry/issues/producer.py"}], "after_files": [{"content": "from __future__ import annotations\n\nimport logging\nfrom typing import Any, Dict, MutableMapping, Optional, cast\n\nfrom arroyo import Topic\nfrom arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration\nfrom arroyo.types import Message, Value\nfrom django.conf import settings\n\nfrom sentry import features\nfrom sentry.issues.issue_occurrence import IssueOccurrence\nfrom sentry.issues.run import process_message\nfrom sentry.issues.status_change_message import StatusChangeMessage\nfrom sentry.models.project import Project\nfrom sentry.services.hybrid_cloud import ValueEqualityEnum\nfrom sentry.utils import json\nfrom sentry.utils.arroyo_producer import SingletonProducer\nfrom sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition\n\nlogger = logging.getLogger(__name__)\n\n\nclass PayloadType(ValueEqualityEnum):\n OCCURRENCE = \"occurrence\"\n STATUS_CHANGE = \"status_change\"\n\n\ndef _get_occurrence_producer() -> KafkaProducer:\n cluster_name = get_topic_definition(settings.KAFKA_INGEST_OCCURRENCES)[\"cluster\"]\n producer_config = get_kafka_producer_cluster_options(cluster_name)\n producer_config.pop(\"compression.type\", None)\n producer_config.pop(\"message.max.bytes\", None)\n return KafkaProducer(build_kafka_configuration(default_config=producer_config))\n\n\n_occurrence_producer = SingletonProducer(\n _get_occurrence_producer, max_futures=settings.SENTRY_ISSUE_PLATFORM_FUTURES_MAX_LIMIT\n)\n\n\ndef produce_occurrence_to_kafka(\n payload_type: PayloadType | None = PayloadType.OCCURRENCE,\n occurrence: IssueOccurrence | None = None,\n status_change: StatusChangeMessage | None = None,\n event_data: Optional[Dict[str, Any]] = None,\n) -> None:\n payload_data = None\n if payload_type == PayloadType.OCCURRENCE:\n payload_data = _prepare_occurrence_message(occurrence, event_data)\n elif payload_type == PayloadType.STATUS_CHANGE:\n payload_data = _prepare_status_change_message(status_change)\n else:\n raise NotImplementedError(f\"Unknown payload type: {payload_type}\")\n\n if payload_data is None:\n return\n\n payload = KafkaPayload(None, json.dumps(payload_data).encode(\"utf-8\"), [])\n if settings.SENTRY_EVENTSTREAM != \"sentry.eventstream.kafka.KafkaEventStream\":\n # If we're not running Kafka then we're just in dev.\n # Skip producing to Kafka and just process the message directly\n process_message(Message(Value(payload=payload, committable={})))\n return\n\n _occurrence_producer.produce(Topic(settings.KAFKA_INGEST_OCCURRENCES), payload)\n\n\ndef _prepare_occurrence_message(\n occurrence: IssueOccurrence | None, event_data: Optional[Dict[str, Any]]\n) -> MutableMapping[str, Any] | None:\n if not occurrence:\n raise ValueError(\"occurrence must be provided\")\n if event_data and occurrence.event_id != event_data[\"event_id\"]:\n raise ValueError(\"Event id on occurrence and event_data must be the same\")\n\n payload_data = cast(MutableMapping[str, Any], occurrence.to_dict())\n payload_data[\"payload_type\"] = PayloadType.OCCURRENCE.value\n if event_data:\n payload_data[\"event\"] = event_data\n\n return payload_data\n\n\ndef _prepare_status_change_message(\n status_change: StatusChangeMessage | None,\n) -> MutableMapping[str, Any] | None:\n if not status_change:\n raise ValueError(\"status_change must be provided\")\n\n organization = Project.objects.get(id=status_change.project_id).organization\n if not features.has(\"organizations:issue-platform-api-crons-sd\", organization):\n return None\n\n payload_data = cast(MutableMapping[str, Any], status_change.to_dict())\n payload_data[\"payload_type\"] = PayloadType.STATUS_CHANGE.value\n return payload_data\n", "path": "src/sentry/issues/producer.py"}]}
1,723
819
gh_patches_debug_2711
rasdani/github-patches
git_diff
getmoto__moto-1462
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add opsworks app mocks Add the mocks of OpsWork create_app and describe_apps calls. This is part of #1477 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `moto/__init__.py` Content: ``` 1 from __future__ import unicode_literals 2 import logging 3 # logging.getLogger('boto').setLevel(logging.CRITICAL) 4 5 __title__ = 'moto' 6 __version__ = '1.2.0', 7 8 from .acm import mock_acm # flake8: noqa 9 from .apigateway import mock_apigateway, mock_apigateway_deprecated # flake8: noqa 10 from .autoscaling import mock_autoscaling, mock_autoscaling_deprecated # flake8: noqa 11 from .awslambda import mock_lambda, mock_lambda_deprecated # flake8: noqa 12 from .cloudformation import mock_cloudformation, mock_cloudformation_deprecated # flake8: noqa 13 from .cloudwatch import mock_cloudwatch, mock_cloudwatch_deprecated # flake8: noqa 14 from .datapipeline import mock_datapipeline, mock_datapipeline_deprecated # flake8: noqa 15 from .dynamodb import mock_dynamodb, mock_dynamodb_deprecated # flake8: noqa 16 from .dynamodb2 import mock_dynamodb2, mock_dynamodb2_deprecated # flake8: noqa 17 from .ec2 import mock_ec2, mock_ec2_deprecated # flake8: noqa 18 from .ecr import mock_ecr, mock_ecr_deprecated # flake8: noqa 19 from .ecs import mock_ecs, mock_ecs_deprecated # flake8: noqa 20 from .elb import mock_elb, mock_elb_deprecated # flake8: noqa 21 from .elbv2 import mock_elbv2 # flake8: noqa 22 from .emr import mock_emr, mock_emr_deprecated # flake8: noqa 23 from .events import mock_events # flake8: noqa 24 from .glacier import mock_glacier, mock_glacier_deprecated # flake8: noqa 25 from .iam import mock_iam, mock_iam_deprecated # flake8: noqa 26 from .kinesis import mock_kinesis, mock_kinesis_deprecated # flake8: noqa 27 from .kms import mock_kms, mock_kms_deprecated # flake8: noqa 28 from .opsworks import mock_opsworks, mock_opsworks_deprecated # flake8: noqa 29 from .polly import mock_polly # flake8: noqa 30 from .rds import mock_rds, mock_rds_deprecated # flake8: noqa 31 from .rds2 import mock_rds2, mock_rds2_deprecated # flake8: noqa 32 from .redshift import mock_redshift, mock_redshift_deprecated # flake8: noqa 33 from .s3 import mock_s3, mock_s3_deprecated # flake8: noqa 34 from .ses import mock_ses, mock_ses_deprecated # flake8: noqa 35 from .sns import mock_sns, mock_sns_deprecated # flake8: noqa 36 from .sqs import mock_sqs, mock_sqs_deprecated # flake8: noqa 37 from .sts import mock_sts, mock_sts_deprecated # flake8: noqa 38 from .ssm import mock_ssm # flake8: noqa 39 from .route53 import mock_route53, mock_route53_deprecated # flake8: noqa 40 from .swf import mock_swf, mock_swf_deprecated # flake8: noqa 41 from .xray import mock_xray, mock_xray_client, XRaySegment # flake8: noqa 42 from .logs import mock_logs, mock_logs_deprecated # flake8: noqa 43 from .batch import mock_batch # flake8: noqa 44 from .resourcegroupstaggingapi import mock_resourcegroupstaggingapi # flake8: noqa 45 from .iot import mock_iot # flake8: noqa 46 from .iotdata import mock_iotdata # flake8: noqa 47 48 49 try: 50 # Need to monkey-patch botocore requests back to underlying urllib3 classes 51 from botocore.awsrequest import HTTPSConnectionPool, HTTPConnectionPool, HTTPConnection, VerifiedHTTPSConnection 52 except ImportError: 53 pass 54 else: 55 HTTPSConnectionPool.ConnectionCls = VerifiedHTTPSConnection 56 HTTPConnectionPool.ConnectionCls = HTTPConnection 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/moto/__init__.py b/moto/__init__.py --- a/moto/__init__.py +++ b/moto/__init__.py @@ -3,7 +3,7 @@ # logging.getLogger('boto').setLevel(logging.CRITICAL) __title__ = 'moto' -__version__ = '1.2.0', +__version__ = '1.2.0' from .acm import mock_acm # flake8: noqa from .apigateway import mock_apigateway, mock_apigateway_deprecated # flake8: noqa
{"golden_diff": "diff --git a/moto/__init__.py b/moto/__init__.py\n--- a/moto/__init__.py\n+++ b/moto/__init__.py\n@@ -3,7 +3,7 @@\n # logging.getLogger('boto').setLevel(logging.CRITICAL)\n \n __title__ = 'moto'\n-__version__ = '1.2.0',\n+__version__ = '1.2.0'\n \n from .acm import mock_acm # flake8: noqa\n from .apigateway import mock_apigateway, mock_apigateway_deprecated # flake8: noqa\n", "issue": "Add opsworks app mocks\nAdd the mocks of OpsWork create_app and describe_apps calls. This is part of #1477 \n", "before_files": [{"content": "from __future__ import unicode_literals\nimport logging\n# logging.getLogger('boto').setLevel(logging.CRITICAL)\n\n__title__ = 'moto'\n__version__ = '1.2.0',\n\nfrom .acm import mock_acm # flake8: noqa\nfrom .apigateway import mock_apigateway, mock_apigateway_deprecated # flake8: noqa\nfrom .autoscaling import mock_autoscaling, mock_autoscaling_deprecated # flake8: noqa\nfrom .awslambda import mock_lambda, mock_lambda_deprecated # flake8: noqa\nfrom .cloudformation import mock_cloudformation, mock_cloudformation_deprecated # flake8: noqa\nfrom .cloudwatch import mock_cloudwatch, mock_cloudwatch_deprecated # flake8: noqa\nfrom .datapipeline import mock_datapipeline, mock_datapipeline_deprecated # flake8: noqa\nfrom .dynamodb import mock_dynamodb, mock_dynamodb_deprecated # flake8: noqa\nfrom .dynamodb2 import mock_dynamodb2, mock_dynamodb2_deprecated # flake8: noqa\nfrom .ec2 import mock_ec2, mock_ec2_deprecated # flake8: noqa\nfrom .ecr import mock_ecr, mock_ecr_deprecated # flake8: noqa\nfrom .ecs import mock_ecs, mock_ecs_deprecated # flake8: noqa\nfrom .elb import mock_elb, mock_elb_deprecated # flake8: noqa\nfrom .elbv2 import mock_elbv2 # flake8: noqa\nfrom .emr import mock_emr, mock_emr_deprecated # flake8: noqa\nfrom .events import mock_events # flake8: noqa\nfrom .glacier import mock_glacier, mock_glacier_deprecated # flake8: noqa\nfrom .iam import mock_iam, mock_iam_deprecated # flake8: noqa\nfrom .kinesis import mock_kinesis, mock_kinesis_deprecated # flake8: noqa\nfrom .kms import mock_kms, mock_kms_deprecated # flake8: noqa\nfrom .opsworks import mock_opsworks, mock_opsworks_deprecated # flake8: noqa\nfrom .polly import mock_polly # flake8: noqa\nfrom .rds import mock_rds, mock_rds_deprecated # flake8: noqa\nfrom .rds2 import mock_rds2, mock_rds2_deprecated # flake8: noqa\nfrom .redshift import mock_redshift, mock_redshift_deprecated # flake8: noqa\nfrom .s3 import mock_s3, mock_s3_deprecated # flake8: noqa\nfrom .ses import mock_ses, mock_ses_deprecated # flake8: noqa\nfrom .sns import mock_sns, mock_sns_deprecated # flake8: noqa\nfrom .sqs import mock_sqs, mock_sqs_deprecated # flake8: noqa\nfrom .sts import mock_sts, mock_sts_deprecated # flake8: noqa\nfrom .ssm import mock_ssm # flake8: noqa\nfrom .route53 import mock_route53, mock_route53_deprecated # flake8: noqa\nfrom .swf import mock_swf, mock_swf_deprecated # flake8: noqa\nfrom .xray import mock_xray, mock_xray_client, XRaySegment # flake8: noqa\nfrom .logs import mock_logs, mock_logs_deprecated # flake8: noqa\nfrom .batch import mock_batch # flake8: noqa\nfrom .resourcegroupstaggingapi import mock_resourcegroupstaggingapi # flake8: noqa\nfrom .iot import mock_iot # flake8: noqa\nfrom .iotdata import mock_iotdata # flake8: noqa\n\n\ntry:\n # Need to monkey-patch botocore requests back to underlying urllib3 classes\n from botocore.awsrequest import HTTPSConnectionPool, HTTPConnectionPool, HTTPConnection, VerifiedHTTPSConnection\nexcept ImportError:\n pass\nelse:\n HTTPSConnectionPool.ConnectionCls = VerifiedHTTPSConnection\n HTTPConnectionPool.ConnectionCls = HTTPConnection\n", "path": "moto/__init__.py"}], "after_files": [{"content": "from __future__ import unicode_literals\nimport logging\n# logging.getLogger('boto').setLevel(logging.CRITICAL)\n\n__title__ = 'moto'\n__version__ = '1.2.0'\n\nfrom .acm import mock_acm # flake8: noqa\nfrom .apigateway import mock_apigateway, mock_apigateway_deprecated # flake8: noqa\nfrom .autoscaling import mock_autoscaling, mock_autoscaling_deprecated # flake8: noqa\nfrom .awslambda import mock_lambda, mock_lambda_deprecated # flake8: noqa\nfrom .cloudformation import mock_cloudformation, mock_cloudformation_deprecated # flake8: noqa\nfrom .cloudwatch import mock_cloudwatch, mock_cloudwatch_deprecated # flake8: noqa\nfrom .datapipeline import mock_datapipeline, mock_datapipeline_deprecated # flake8: noqa\nfrom .dynamodb import mock_dynamodb, mock_dynamodb_deprecated # flake8: noqa\nfrom .dynamodb2 import mock_dynamodb2, mock_dynamodb2_deprecated # flake8: noqa\nfrom .ec2 import mock_ec2, mock_ec2_deprecated # flake8: noqa\nfrom .ecr import mock_ecr, mock_ecr_deprecated # flake8: noqa\nfrom .ecs import mock_ecs, mock_ecs_deprecated # flake8: noqa\nfrom .elb import mock_elb, mock_elb_deprecated # flake8: noqa\nfrom .elbv2 import mock_elbv2 # flake8: noqa\nfrom .emr import mock_emr, mock_emr_deprecated # flake8: noqa\nfrom .events import mock_events # flake8: noqa\nfrom .glacier import mock_glacier, mock_glacier_deprecated # flake8: noqa\nfrom .iam import mock_iam, mock_iam_deprecated # flake8: noqa\nfrom .kinesis import mock_kinesis, mock_kinesis_deprecated # flake8: noqa\nfrom .kms import mock_kms, mock_kms_deprecated # flake8: noqa\nfrom .opsworks import mock_opsworks, mock_opsworks_deprecated # flake8: noqa\nfrom .polly import mock_polly # flake8: noqa\nfrom .rds import mock_rds, mock_rds_deprecated # flake8: noqa\nfrom .rds2 import mock_rds2, mock_rds2_deprecated # flake8: noqa\nfrom .redshift import mock_redshift, mock_redshift_deprecated # flake8: noqa\nfrom .s3 import mock_s3, mock_s3_deprecated # flake8: noqa\nfrom .ses import mock_ses, mock_ses_deprecated # flake8: noqa\nfrom .sns import mock_sns, mock_sns_deprecated # flake8: noqa\nfrom .sqs import mock_sqs, mock_sqs_deprecated # flake8: noqa\nfrom .sts import mock_sts, mock_sts_deprecated # flake8: noqa\nfrom .ssm import mock_ssm # flake8: noqa\nfrom .route53 import mock_route53, mock_route53_deprecated # flake8: noqa\nfrom .swf import mock_swf, mock_swf_deprecated # flake8: noqa\nfrom .xray import mock_xray, mock_xray_client, XRaySegment # flake8: noqa\nfrom .logs import mock_logs, mock_logs_deprecated # flake8: noqa\nfrom .batch import mock_batch # flake8: noqa\nfrom .resourcegroupstaggingapi import mock_resourcegroupstaggingapi # flake8: noqa\nfrom .iot import mock_iot # flake8: noqa\nfrom .iotdata import mock_iotdata # flake8: noqa\n\n\ntry:\n # Need to monkey-patch botocore requests back to underlying urllib3 classes\n from botocore.awsrequest import HTTPSConnectionPool, HTTPConnectionPool, HTTPConnection, VerifiedHTTPSConnection\nexcept ImportError:\n pass\nelse:\n HTTPSConnectionPool.ConnectionCls = VerifiedHTTPSConnection\n HTTPConnectionPool.ConnectionCls = HTTPConnection\n", "path": "moto/__init__.py"}]}
1,330
134
gh_patches_debug_3787
rasdani/github-patches
git_diff
zigpy__zha-device-handlers-506
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [BUG] Osram switch mini **Describe the bug** Adding a OSRAM Lightify Switch Mini to my network is not working out after quirk was added some time ago. Before quirk: I picked up zha_events. After quirk: The remote switches everything(switched bulbs cover) in my network on and off. **To Reproduce** Steps to reproduce the behavior: Removed remote, deletes entries from zha.storage and other HA files I could find the remote. Device signature: { "node_descriptor": "NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4364, maximum_buffer_size=82, maximum_incoming_transfer_size=82, server_mask=0, maximum_outgoing_transfer_size=82, descriptor_capability_field=0)", "endpoints": {}, "manufacturer": "OSRAM", "model": "Lightify Switch Mini", "class": "zhaquirks.osram.switchmini.OsramSwitchMini" } Manage cluster is empty. ![osrammini](https://user-images.githubusercontent.com/11892538/94000737-deea2f80-fd97-11ea-88a2-83301b6584a0.png) **Expected behavior** A remote that switches the stuff I want, not everything(via zha_event for my usage) **Screenshots** If applicable, add screenshots to help explain your problem. **Additional context** [osramminiadd.txt](https://github.com/zigpy/zha-device-handlers/files/5267371/osramminiadd.txt) --- 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/osram/switchmini.py` Content: ``` 1 """Osram Smart+ Switch Mini 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 PollControl, 14 ) 15 from zigpy.zcl.clusters.lighting import Color 16 from zigpy.zcl.clusters.lightlink import LightLink 17 18 from . import OSRAM 19 from ..const import ( 20 DEVICE_TYPE, 21 ENDPOINTS, 22 INPUT_CLUSTERS, 23 OUTPUT_CLUSTERS, 24 PROFILE_ID, 25 SHORT_PRESS, 26 COMMAND, 27 COMMAND_ON, 28 MODELS_INFO, 29 BUTTON_1, 30 ENDPOINT_ID, 31 COMMAND_STEP_ON_OFF, 32 COMMAND_STOP, 33 BUTTON_2, 34 BUTTON_3, 35 LONG_RELEASE, 36 LONG_PRESS, 37 COMMAND_MOVE_TO_LEVEL_ON_OFF, 38 COMMAND_OFF, 39 COMMAND_MOVE, 40 ) 41 42 OSRAM_CLUSTER = 0xFD00 43 44 45 class OsramSwitchMini(CustomDevice): 46 """Osram Smart+ Switch Mini device.""" 47 48 signature = { 49 MODELS_INFO: [(OSRAM, "Lightify Switch Mini")], 50 ENDPOINTS: { 51 # <SimpleDescriptor endpoint=1 profile=260 device_type=2064 52 # device_version=1 53 # input_clusters=[0, 1, 20, 4096, 64758] 54 # output_clusters=[3, 4, 5, 6, 8, 25, 768, 4096]> 55 1: { 56 PROFILE_ID: zha.PROFILE_ID, 57 DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER, 58 INPUT_CLUSTERS: [ 59 Basic.cluster_id, 60 PowerConfiguration.cluster_id, 61 PollControl.cluster_id, 62 LightLink.cluster_id, 63 OSRAM_CLUSTER, 64 ], 65 OUTPUT_CLUSTERS: [ 66 Identify.cluster_id, 67 Groups.cluster_id, 68 Scenes.cluster_id, 69 OnOff.cluster_id, 70 LevelControl.cluster_id, 71 Ota.cluster_id, 72 Color.cluster_id, 73 LightLink.cluster_id, 74 ], 75 }, 76 # <SimpleDescriptor endpoint=2 profile=260 device_type=2064 77 # device_version=1 78 # input_clusters=[0, 4096, 64768] 79 # output_clusters=[3, 4, 5, 6, 8, 768, 4096]> 80 2: { 81 PROFILE_ID: zha.PROFILE_ID, 82 DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER, 83 INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER], 84 OUTPUT_CLUSTERS: [ 85 Identify.cluster_id, 86 Groups.cluster_id, 87 Scenes.cluster_id, 88 OnOff.cluster_id, 89 LevelControl.cluster_id, 90 Color.cluster_id, 91 LightLink.cluster_id, 92 ], 93 }, 94 # <SimpleDescriptor endpoint=2 profile=260 device_type=2064 95 # device_version=1 96 # input_clusters=[0, 4096, 64768] 97 # output_clusters=[3, 4, 5, 6, 8, 768, 4096]> 98 3: { 99 PROFILE_ID: zha.PROFILE_ID, 100 DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER, 101 INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER], 102 OUTPUT_CLUSTERS: [ 103 Identify.cluster_id, 104 Groups.cluster_id, 105 Scenes.cluster_id, 106 OnOff.cluster_id, 107 LevelControl.cluster_id, 108 Color.cluster_id, 109 LightLink.cluster_id, 110 ], 111 }, 112 }, 113 } 114 115 device_automation_triggers = { 116 (SHORT_PRESS, BUTTON_1): {COMMAND: COMMAND_ON, ENDPOINT_ID: 1}, 117 (LONG_PRESS, BUTTON_1): {COMMAND: COMMAND_STEP_ON_OFF, ENDPOINT_ID: 1}, 118 (LONG_RELEASE, BUTTON_1): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 1}, 119 (SHORT_PRESS, BUTTON_2): { 120 COMMAND: COMMAND_MOVE_TO_LEVEL_ON_OFF, 121 ENDPOINT_ID: 3, 122 }, 123 (LONG_PRESS, BUTTON_2): {COMMAND: "move_to_saturation", ENDPOINT_ID: 3}, 124 (LONG_RELEASE, BUTTON_2): {COMMAND: "move_hue", ENDPOINT_ID: 3}, 125 (SHORT_PRESS, BUTTON_3): {COMMAND: COMMAND_OFF, ENDPOINT_ID: 2}, 126 (LONG_PRESS, BUTTON_3): {COMMAND: COMMAND_MOVE, ENDPOINT_ID: 2}, 127 (LONG_RELEASE, BUTTON_3): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 2}, 128 } 129 ``` --- 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/osram/switchmini.py b/zhaquirks/osram/switchmini.py --- a/zhaquirks/osram/switchmini.py +++ b/zhaquirks/osram/switchmini.py @@ -112,6 +112,9 @@ }, } + replacement = {**signature} + replacement.pop(MODELS_INFO) + device_automation_triggers = { (SHORT_PRESS, BUTTON_1): {COMMAND: COMMAND_ON, ENDPOINT_ID: 1}, (LONG_PRESS, BUTTON_1): {COMMAND: COMMAND_STEP_ON_OFF, ENDPOINT_ID: 1},
{"golden_diff": "diff --git a/zhaquirks/osram/switchmini.py b/zhaquirks/osram/switchmini.py\n--- a/zhaquirks/osram/switchmini.py\n+++ b/zhaquirks/osram/switchmini.py\n@@ -112,6 +112,9 @@\n },\n }\n \n+ replacement = {**signature}\n+ replacement.pop(MODELS_INFO)\n+\n device_automation_triggers = {\n (SHORT_PRESS, BUTTON_1): {COMMAND: COMMAND_ON, ENDPOINT_ID: 1},\n (LONG_PRESS, BUTTON_1): {COMMAND: COMMAND_STEP_ON_OFF, ENDPOINT_ID: 1},\n", "issue": "[BUG] Osram switch mini\n**Describe the bug**\r\nAdding a OSRAM Lightify Switch Mini to my network is not working out after quirk was added some time ago.\r\n\r\nBefore quirk: I picked up zha_events.\r\n\r\nAfter quirk: The remote switches everything(switched bulbs cover) in my network on and off.\r\n\r\n\r\n \r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\nRemoved remote, deletes entries from zha.storage and other HA files I could find the remote.\r\n\r\nDevice signature:\r\n{\r\n \"node_descriptor\": \"NodeDescriptor(byte1=2, byte2=64, mac_capability_flags=128, manufacturer_code=4364, maximum_buffer_size=82, maximum_incoming_transfer_size=82, server_mask=0, maximum_outgoing_transfer_size=82, descriptor_capability_field=0)\",\r\n \"endpoints\": {},\r\n \"manufacturer\": \"OSRAM\",\r\n \"model\": \"Lightify Switch Mini\",\r\n \"class\": \"zhaquirks.osram.switchmini.OsramSwitchMini\"\r\n}\r\n\r\nManage cluster is empty.\r\n![osrammini](https://user-images.githubusercontent.com/11892538/94000737-deea2f80-fd97-11ea-88a2-83301b6584a0.png)\r\n\r\n**Expected behavior**\r\nA remote that switches the stuff I want, not everything(via zha_event for my usage)\r\n\r\n**Screenshots**\r\nIf applicable, add screenshots to help explain your problem.\r\n\r\n**Additional context**\r\n[osramminiadd.txt](https://github.com/zigpy/zha-device-handlers/files/5267371/osramminiadd.txt)\r\n\n", "before_files": [{"content": "\"\"\"Osram Smart+ Switch Mini 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 PollControl,\n)\nfrom zigpy.zcl.clusters.lighting import Color\nfrom zigpy.zcl.clusters.lightlink import LightLink\n\nfrom . import OSRAM\nfrom ..const import (\n DEVICE_TYPE,\n ENDPOINTS,\n INPUT_CLUSTERS,\n OUTPUT_CLUSTERS,\n PROFILE_ID,\n SHORT_PRESS,\n COMMAND,\n COMMAND_ON,\n MODELS_INFO,\n BUTTON_1,\n ENDPOINT_ID,\n COMMAND_STEP_ON_OFF,\n COMMAND_STOP,\n BUTTON_2,\n BUTTON_3,\n LONG_RELEASE,\n LONG_PRESS,\n COMMAND_MOVE_TO_LEVEL_ON_OFF,\n COMMAND_OFF,\n COMMAND_MOVE,\n)\n\nOSRAM_CLUSTER = 0xFD00\n\n\nclass OsramSwitchMini(CustomDevice):\n \"\"\"Osram Smart+ Switch Mini device.\"\"\"\n\n signature = {\n MODELS_INFO: [(OSRAM, \"Lightify Switch Mini\")],\n ENDPOINTS: {\n # <SimpleDescriptor endpoint=1 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 1, 20, 4096, 64758]\n # output_clusters=[3, 4, 5, 6, 8, 25, 768, 4096]>\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n Basic.cluster_id,\n PowerConfiguration.cluster_id,\n PollControl.cluster_id,\n LightLink.cluster_id,\n OSRAM_CLUSTER,\n ],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Ota.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n # <SimpleDescriptor endpoint=2 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 4096, 64768]\n # output_clusters=[3, 4, 5, 6, 8, 768, 4096]>\n 2: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n # <SimpleDescriptor endpoint=2 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 4096, 64768]\n # output_clusters=[3, 4, 5, 6, 8, 768, 4096]>\n 3: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n },\n }\n\n device_automation_triggers = {\n (SHORT_PRESS, BUTTON_1): {COMMAND: COMMAND_ON, ENDPOINT_ID: 1},\n (LONG_PRESS, BUTTON_1): {COMMAND: COMMAND_STEP_ON_OFF, ENDPOINT_ID: 1},\n (LONG_RELEASE, BUTTON_1): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 1},\n (SHORT_PRESS, BUTTON_2): {\n COMMAND: COMMAND_MOVE_TO_LEVEL_ON_OFF,\n ENDPOINT_ID: 3,\n },\n (LONG_PRESS, BUTTON_2): {COMMAND: \"move_to_saturation\", ENDPOINT_ID: 3},\n (LONG_RELEASE, BUTTON_2): {COMMAND: \"move_hue\", ENDPOINT_ID: 3},\n (SHORT_PRESS, BUTTON_3): {COMMAND: COMMAND_OFF, ENDPOINT_ID: 2},\n (LONG_PRESS, BUTTON_3): {COMMAND: COMMAND_MOVE, ENDPOINT_ID: 2},\n (LONG_RELEASE, BUTTON_3): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 2},\n }\n", "path": "zhaquirks/osram/switchmini.py"}], "after_files": [{"content": "\"\"\"Osram Smart+ Switch Mini 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 PollControl,\n)\nfrom zigpy.zcl.clusters.lighting import Color\nfrom zigpy.zcl.clusters.lightlink import LightLink\n\nfrom . import OSRAM\nfrom ..const import (\n DEVICE_TYPE,\n ENDPOINTS,\n INPUT_CLUSTERS,\n OUTPUT_CLUSTERS,\n PROFILE_ID,\n SHORT_PRESS,\n COMMAND,\n COMMAND_ON,\n MODELS_INFO,\n BUTTON_1,\n ENDPOINT_ID,\n COMMAND_STEP_ON_OFF,\n COMMAND_STOP,\n BUTTON_2,\n BUTTON_3,\n LONG_RELEASE,\n LONG_PRESS,\n COMMAND_MOVE_TO_LEVEL_ON_OFF,\n COMMAND_OFF,\n COMMAND_MOVE,\n)\n\nOSRAM_CLUSTER = 0xFD00\n\n\nclass OsramSwitchMini(CustomDevice):\n \"\"\"Osram Smart+ Switch Mini device.\"\"\"\n\n signature = {\n MODELS_INFO: [(OSRAM, \"Lightify Switch Mini\")],\n ENDPOINTS: {\n # <SimpleDescriptor endpoint=1 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 1, 20, 4096, 64758]\n # output_clusters=[3, 4, 5, 6, 8, 25, 768, 4096]>\n 1: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [\n Basic.cluster_id,\n PowerConfiguration.cluster_id,\n PollControl.cluster_id,\n LightLink.cluster_id,\n OSRAM_CLUSTER,\n ],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Ota.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n # <SimpleDescriptor endpoint=2 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 4096, 64768]\n # output_clusters=[3, 4, 5, 6, 8, 768, 4096]>\n 2: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n # <SimpleDescriptor endpoint=2 profile=260 device_type=2064\n # device_version=1\n # input_clusters=[0, 4096, 64768]\n # output_clusters=[3, 4, 5, 6, 8, 768, 4096]>\n 3: {\n PROFILE_ID: zha.PROFILE_ID,\n DEVICE_TYPE: zha.DeviceType.COLOR_SCENE_CONTROLLER,\n INPUT_CLUSTERS: [Basic.cluster_id, LightLink.cluster_id, OSRAM_CLUSTER],\n OUTPUT_CLUSTERS: [\n Identify.cluster_id,\n Groups.cluster_id,\n Scenes.cluster_id,\n OnOff.cluster_id,\n LevelControl.cluster_id,\n Color.cluster_id,\n LightLink.cluster_id,\n ],\n },\n },\n }\n\n replacement = {**signature}\n replacement.pop(MODELS_INFO)\n\n device_automation_triggers = {\n (SHORT_PRESS, BUTTON_1): {COMMAND: COMMAND_ON, ENDPOINT_ID: 1},\n (LONG_PRESS, BUTTON_1): {COMMAND: COMMAND_STEP_ON_OFF, ENDPOINT_ID: 1},\n (LONG_RELEASE, BUTTON_1): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 1},\n (SHORT_PRESS, BUTTON_2): {\n COMMAND: COMMAND_MOVE_TO_LEVEL_ON_OFF,\n ENDPOINT_ID: 3,\n },\n (LONG_PRESS, BUTTON_2): {COMMAND: \"move_to_saturation\", ENDPOINT_ID: 3},\n (LONG_RELEASE, BUTTON_2): {COMMAND: \"move_hue\", ENDPOINT_ID: 3},\n (SHORT_PRESS, BUTTON_3): {COMMAND: COMMAND_OFF, ENDPOINT_ID: 2},\n (LONG_PRESS, BUTTON_3): {COMMAND: COMMAND_MOVE, ENDPOINT_ID: 2},\n (LONG_RELEASE, BUTTON_3): {COMMAND: COMMAND_STOP, ENDPOINT_ID: 2},\n }\n", "path": "zhaquirks/osram/switchmini.py"}]}
1,956
143
gh_patches_debug_27558
rasdani/github-patches
git_diff
fossasia__open-event-server-5311
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Wrong Mail Statistics which troubles it to work completely **Describe the bug** <!-- A clear and concise description of what the bug is. --> Wrong Mail Statistics which troubles it to work completely **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> **Stacktrace** <!-- If applicable, add stacktrace to help explain your problem. --> **Additional details (please complete the following information):** - OS: [e.g. MacOS, Ubuntu, CentOS] - Python Version [e.g. `3.5`, `3.6`] - `HEAD` Commit hash [e.g. `4629c62`] **Additional context** <!-- Add any other context about the problem here. --> **Wanna work on this issue** --- 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/admin_statistics_api/mails.py` Content: ``` 1 from flask_rest_jsonapi import ResourceDetail 2 from marshmallow_jsonapi.flask import Schema 3 from marshmallow_jsonapi import fields 4 from datetime import datetime, timedelta 5 import pytz 6 7 from app.api.helpers.utilities import dasherize 8 from app.api.bootstrap import api 9 from app.models import db 10 from app.models.mail import Mail 11 from app.api.data_layers.NoModelLayer import NoModelLayer 12 from app.api.helpers.db import get_count 13 14 15 class AdminStatisticsMailSchema(Schema): 16 """ 17 Api schema 18 """ 19 class Meta: 20 """ 21 Meta class 22 """ 23 type_ = 'admin-statistics-mail' 24 self_view = 'v1.admin_statistics_mail_detail' 25 inflect = dasherize 26 27 id = fields.String() 28 one_day = fields.Method("mail_last_1_day") 29 three_days = fields.Method("mail_last_3_days") 30 seven_days = fields.Method("mail_last_7_days") 31 thirty_days = fields.Method("mail_last_30_days") 32 33 def mail_last_1_day(self, obj): 34 return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1))) 35 36 def mail_last_3_days(self, obj): 37 return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3))) 38 39 def mail_last_7_days(self, obj): 40 return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7))) 41 42 def mail_last_30_days(self, obj): 43 return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30))) 44 45 46 class AdminStatisticsMailDetail(ResourceDetail): 47 """ 48 Detail by id 49 """ 50 methods = ['GET'] 51 decorators = (api.has_permission('is_admin'),) 52 schema = AdminStatisticsMailSchema 53 data_layer = { 54 'class': NoModelLayer, 55 'session': db.session 56 } 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/app/api/admin_statistics_api/mails.py b/app/api/admin_statistics_api/mails.py --- a/app/api/admin_statistics_api/mails.py +++ b/app/api/admin_statistics_api/mails.py @@ -31,16 +31,24 @@ thirty_days = fields.Method("mail_last_30_days") def mail_last_1_day(self, obj): - return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1))) + all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc))) + mails_till_last_1_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=1))) + return all_mails - mails_till_last_1_day def mail_last_3_days(self, obj): - return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3))) + all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc))) + mails_till_last_3_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=3))) + return all_mails - mails_till_last_3_day def mail_last_7_days(self, obj): - return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7))) + all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc))) + mails_till_last_7_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=7))) + return all_mails - mails_till_last_7_day def mail_last_30_days(self, obj): - return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30))) + all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc))) + mails_till_last_30_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=30))) + return all_mails - mails_till_last_30_day class AdminStatisticsMailDetail(ResourceDetail):
{"golden_diff": "diff --git a/app/api/admin_statistics_api/mails.py b/app/api/admin_statistics_api/mails.py\n--- a/app/api/admin_statistics_api/mails.py\n+++ b/app/api/admin_statistics_api/mails.py\n@@ -31,16 +31,24 @@\n thirty_days = fields.Method(\"mail_last_30_days\")\n \n def mail_last_1_day(self, obj):\n- return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1)))\n+ all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n+ mails_till_last_1_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=1)))\n+ return all_mails - mails_till_last_1_day\n \n def mail_last_3_days(self, obj):\n- return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3)))\n+ all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n+ mails_till_last_3_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=3)))\n+ return all_mails - mails_till_last_3_day\n \n def mail_last_7_days(self, obj):\n- return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7)))\n+ all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n+ mails_till_last_7_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=7)))\n+ return all_mails - mails_till_last_7_day\n \n def mail_last_30_days(self, obj):\n- return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30)))\n+ all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n+ mails_till_last_30_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=30)))\n+ return all_mails - mails_till_last_30_day\n \n \n class AdminStatisticsMailDetail(ResourceDetail):\n", "issue": "Wrong Mail Statistics which troubles it to work completely\n**Describe the bug**\r\n<!-- A clear and concise description of what the bug is. -->\r\nWrong Mail Statistics which troubles it to work completely\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Go to '...'\r\n2. Click on '....'\r\n3. Scroll down to '....'\r\n4. See error\r\n\r\n**Expected behavior**\r\n<!-- A clear and concise description of what you expected to happen. -->\r\n\r\n**Stacktrace**\r\n<!-- If applicable, add stacktrace to help explain your problem. -->\r\n\r\n**Additional details (please complete the following information):**\r\n - OS: [e.g. MacOS, Ubuntu, CentOS]\r\n - Python Version [e.g. `3.5`, `3.6`]\r\n - `HEAD` Commit hash [e.g. `4629c62`]\r\n\r\n**Additional context**\r\n<!-- Add any other context about the problem here. -->\r\n**Wanna work on this issue**\n", "before_files": [{"content": "from flask_rest_jsonapi import ResourceDetail\nfrom marshmallow_jsonapi.flask import Schema\nfrom marshmallow_jsonapi import fields\nfrom datetime import datetime, timedelta\nimport pytz\n\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.bootstrap import api\nfrom app.models import db\nfrom app.models.mail import Mail\nfrom app.api.data_layers.NoModelLayer import NoModelLayer\nfrom app.api.helpers.db import get_count\n\n\nclass AdminStatisticsMailSchema(Schema):\n \"\"\"\n Api schema\n \"\"\"\n class Meta:\n \"\"\"\n Meta class\n \"\"\"\n type_ = 'admin-statistics-mail'\n self_view = 'v1.admin_statistics_mail_detail'\n inflect = dasherize\n\n id = fields.String()\n one_day = fields.Method(\"mail_last_1_day\")\n three_days = fields.Method(\"mail_last_3_days\")\n seven_days = fields.Method(\"mail_last_7_days\")\n thirty_days = fields.Method(\"mail_last_30_days\")\n\n def mail_last_1_day(self, obj):\n return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1)))\n\n def mail_last_3_days(self, obj):\n return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3)))\n\n def mail_last_7_days(self, obj):\n return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7)))\n\n def mail_last_30_days(self, obj):\n return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30)))\n\n\nclass AdminStatisticsMailDetail(ResourceDetail):\n \"\"\"\n Detail by id\n \"\"\"\n methods = ['GET']\n decorators = (api.has_permission('is_admin'),)\n schema = AdminStatisticsMailSchema\n data_layer = {\n 'class': NoModelLayer,\n 'session': db.session\n }\n", "path": "app/api/admin_statistics_api/mails.py"}], "after_files": [{"content": "from flask_rest_jsonapi import ResourceDetail\nfrom marshmallow_jsonapi.flask import Schema\nfrom marshmallow_jsonapi import fields\nfrom datetime import datetime, timedelta\nimport pytz\n\nfrom app.api.helpers.utilities import dasherize\nfrom app.api.bootstrap import api\nfrom app.models import db\nfrom app.models.mail import Mail\nfrom app.api.data_layers.NoModelLayer import NoModelLayer\nfrom app.api.helpers.db import get_count\n\n\nclass AdminStatisticsMailSchema(Schema):\n \"\"\"\n Api schema\n \"\"\"\n class Meta:\n \"\"\"\n Meta class\n \"\"\"\n type_ = 'admin-statistics-mail'\n self_view = 'v1.admin_statistics_mail_detail'\n inflect = dasherize\n\n id = fields.String()\n one_day = fields.Method(\"mail_last_1_day\")\n three_days = fields.Method(\"mail_last_3_days\")\n seven_days = fields.Method(\"mail_last_7_days\")\n thirty_days = fields.Method(\"mail_last_30_days\")\n\n def mail_last_1_day(self, obj):\n all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n mails_till_last_1_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=1)))\n return all_mails - mails_till_last_1_day\n\n def mail_last_3_days(self, obj):\n all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n mails_till_last_3_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=3)))\n return all_mails - mails_till_last_3_day\n\n def mail_last_7_days(self, obj):\n all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n mails_till_last_7_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=7)))\n return all_mails - mails_till_last_7_day\n\n def mail_last_30_days(self, obj):\n all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))\n mails_till_last_30_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=30)))\n return all_mails - mails_till_last_30_day\n\n\nclass AdminStatisticsMailDetail(ResourceDetail):\n \"\"\"\n Detail by id\n \"\"\"\n methods = ['GET']\n decorators = (api.has_permission('is_admin'),)\n schema = AdminStatisticsMailSchema\n data_layer = {\n 'class': NoModelLayer,\n 'session': db.session\n }\n", "path": "app/api/admin_statistics_api/mails.py"}]}
988
507
gh_patches_debug_14292
rasdani/github-patches
git_diff
secdev__scapy-855
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- test_pyx problem I have a unit test that uses scapy library like this: ``` $ cat ut.py from scapy.all import * def test_foo(): pass ``` The problem is that testing framework (pytest) detects internal scapy function test_pyx as a test: ``` ut.py::test_foo PASSED ut.py::test_pyx <- venv/src/scapy/scapy/consts.py PASSED ``` This is because test_pyx function from scapy/consts.py is unnecessarily imported from scapy.all and pytest treats all test_* functions as tests. Scapy from current master branch. --- 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/consts.py` Content: ``` 1 ## This file is part of Scapy 2 ## See http://www.secdev.org/projects/scapy for more informations 3 ## Copyright (C) Philippe Biondi <[email protected]> 4 ## This program is published under a GPLv2 license 5 6 import os, inspect 7 from sys import platform, maxsize 8 import platform as platform_lib 9 from scapy.error import * 10 11 import subprocess 12 13 try: 14 from matplotlib import get_backend as matplotlib_get_backend 15 import matplotlib.pyplot as plt 16 MATPLOTLIB = 1 17 if "inline" in matplotlib_get_backend(): 18 MATPLOTLIB_INLINED = 1 19 else: 20 MATPLOTLIB_INLINED = 0 21 MATPLOTLIB_DEFAULT_PLOT_KARGS = {"marker": "+"} 22 # RuntimeError to catch gtk "Cannot open display" error 23 except (ImportError, RuntimeError): 24 plt = None 25 MATPLOTLIB = 0 26 MATPLOTLIB_INLINED = 0 27 MATPLOTLIB_DEFAULT_PLOT_KARGS = dict() 28 log_loading.info("Can't import matplotlib. Won't be able to plot.") 29 30 def test_pyx(): 31 """Returns if PyX is correctly installed or not""" 32 try: 33 with open(os.devnull, 'wb') as devnull: 34 r = subprocess.check_call(["pdflatex", "--version"], stdout=devnull, stderr=subprocess.STDOUT) 35 except: 36 return False 37 else: 38 return r == 0 39 40 try: 41 import pyx 42 if test_pyx(): 43 PYX = 1 44 else: 45 log_loading.warning("PyX dependencies are not installed ! Please install TexLive or MikTeX.") 46 PYX = 0 47 except ImportError: 48 log_loading.info("Can't import PyX. Won't be able to use psdump() or pdfdump().") 49 PYX = 0 50 51 52 LINUX = platform.startswith("linux") 53 OPENBSD = platform.startswith("openbsd") 54 FREEBSD = "freebsd" in platform 55 NETBSD = platform.startswith("netbsd") 56 DARWIN = platform.startswith("darwin") 57 SOLARIS = platform.startswith("sunos") 58 WINDOWS = platform.startswith("win32") 59 BSD = DARWIN or FREEBSD or OPENBSD or NETBSD 60 # See https://docs.python.org/3/library/platform.html#cross-platform 61 IS_64BITS = maxsize > 2**32 62 63 if WINDOWS: 64 try: 65 if float(platform_lib.release()) >= 8.1: 66 LOOPBACK_NAME = "Microsoft KM-TEST Loopback Adapter" 67 else: 68 LOOPBACK_NAME = "Microsoft Loopback Adapter" 69 except ValueError: 70 LOOPBACK_NAME = "Microsoft Loopback Adapter" 71 # Will be different on Windows 72 LOOPBACK_INTERFACE = None 73 else: 74 uname = os.uname() 75 LOOPBACK_NAME = "lo" if LINUX else "lo0" 76 LOOPBACK_INTERFACE = LOOPBACK_NAME 77 78 def parent_function(): 79 return inspect.getouterframes(inspect.currentframe()) 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/scapy/consts.py b/scapy/consts.py --- a/scapy/consts.py +++ b/scapy/consts.py @@ -27,7 +27,7 @@ MATPLOTLIB_DEFAULT_PLOT_KARGS = dict() log_loading.info("Can't import matplotlib. Won't be able to plot.") -def test_pyx(): +def _test_pyx(): """Returns if PyX is correctly installed or not""" try: with open(os.devnull, 'wb') as devnull: @@ -39,7 +39,7 @@ try: import pyx - if test_pyx(): + if _test_pyx(): PYX = 1 else: log_loading.warning("PyX dependencies are not installed ! Please install TexLive or MikTeX.")
{"golden_diff": "diff --git a/scapy/consts.py b/scapy/consts.py\n--- a/scapy/consts.py\n+++ b/scapy/consts.py\n@@ -27,7 +27,7 @@\n MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()\n log_loading.info(\"Can't import matplotlib. Won't be able to plot.\")\n \n-def test_pyx():\n+def _test_pyx():\n \"\"\"Returns if PyX is correctly installed or not\"\"\"\n try:\n with open(os.devnull, 'wb') as devnull:\n@@ -39,7 +39,7 @@\n \n try:\n import pyx\n- if test_pyx():\n+ if _test_pyx():\n PYX = 1\n else:\n log_loading.warning(\"PyX dependencies are not installed ! Please install TexLive or MikTeX.\")\n", "issue": "test_pyx problem\nI have a unit test that uses scapy library like this:\r\n```\r\n$ cat ut.py \r\nfrom scapy.all import *\r\n\r\ndef test_foo():\r\n pass\r\n```\r\nThe problem is that testing framework (pytest) detects internal scapy function test_pyx as a test:\r\n```\r\nut.py::test_foo PASSED\r\nut.py::test_pyx <- venv/src/scapy/scapy/consts.py PASSED\r\n```\r\nThis is because test_pyx function from scapy/consts.py is unnecessarily imported from scapy.all\r\nand pytest treats all test_* functions as tests.\r\n\r\nScapy from current master branch.\r\n\r\n\n", "before_files": [{"content": "## This file is part of Scapy\n## See http://www.secdev.org/projects/scapy for more informations\n## Copyright (C) Philippe Biondi <[email protected]>\n## This program is published under a GPLv2 license\n\nimport os, inspect\nfrom sys import platform, maxsize\nimport platform as platform_lib\nfrom scapy.error import *\n\nimport subprocess\n\ntry:\n from matplotlib import get_backend as matplotlib_get_backend\n import matplotlib.pyplot as plt\n MATPLOTLIB = 1\n if \"inline\" in matplotlib_get_backend():\n MATPLOTLIB_INLINED = 1\n else:\n MATPLOTLIB_INLINED = 0\n MATPLOTLIB_DEFAULT_PLOT_KARGS = {\"marker\": \"+\"}\n# RuntimeError to catch gtk \"Cannot open display\" error\nexcept (ImportError, RuntimeError):\n plt = None\n MATPLOTLIB = 0\n MATPLOTLIB_INLINED = 0\n MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()\n log_loading.info(\"Can't import matplotlib. Won't be able to plot.\")\n\ndef test_pyx():\n \"\"\"Returns if PyX is correctly installed or not\"\"\"\n try:\n with open(os.devnull, 'wb') as devnull:\n r = subprocess.check_call([\"pdflatex\", \"--version\"], stdout=devnull, stderr=subprocess.STDOUT)\n except:\n return False\n else:\n return r == 0\n\ntry:\n import pyx\n if test_pyx():\n PYX = 1\n else:\n log_loading.warning(\"PyX dependencies are not installed ! Please install TexLive or MikTeX.\")\n PYX = 0\nexcept ImportError:\n log_loading.info(\"Can't import PyX. Won't be able to use psdump() or pdfdump().\")\n PYX = 0\n\n\nLINUX = platform.startswith(\"linux\")\nOPENBSD = platform.startswith(\"openbsd\")\nFREEBSD = \"freebsd\" in platform\nNETBSD = platform.startswith(\"netbsd\")\nDARWIN = platform.startswith(\"darwin\")\nSOLARIS = platform.startswith(\"sunos\")\nWINDOWS = platform.startswith(\"win32\")\nBSD = DARWIN or FREEBSD or OPENBSD or NETBSD\n# See https://docs.python.org/3/library/platform.html#cross-platform\nIS_64BITS = maxsize > 2**32\n\nif WINDOWS:\n try:\n if float(platform_lib.release()) >= 8.1:\n LOOPBACK_NAME = \"Microsoft KM-TEST Loopback Adapter\"\n else:\n LOOPBACK_NAME = \"Microsoft Loopback Adapter\"\n except ValueError:\n LOOPBACK_NAME = \"Microsoft Loopback Adapter\"\n # Will be different on Windows\n LOOPBACK_INTERFACE = None\nelse:\n uname = os.uname()\n LOOPBACK_NAME = \"lo\" if LINUX else \"lo0\"\n LOOPBACK_INTERFACE = LOOPBACK_NAME\n\ndef parent_function():\n return inspect.getouterframes(inspect.currentframe())\n", "path": "scapy/consts.py"}], "after_files": [{"content": "## This file is part of Scapy\n## See http://www.secdev.org/projects/scapy for more informations\n## Copyright (C) Philippe Biondi <[email protected]>\n## This program is published under a GPLv2 license\n\nimport os, inspect\nfrom sys import platform, maxsize\nimport platform as platform_lib\nfrom scapy.error import *\n\nimport subprocess\n\ntry:\n from matplotlib import get_backend as matplotlib_get_backend\n import matplotlib.pyplot as plt\n MATPLOTLIB = 1\n if \"inline\" in matplotlib_get_backend():\n MATPLOTLIB_INLINED = 1\n else:\n MATPLOTLIB_INLINED = 0\n MATPLOTLIB_DEFAULT_PLOT_KARGS = {\"marker\": \"+\"}\n# RuntimeError to catch gtk \"Cannot open display\" error\nexcept (ImportError, RuntimeError):\n plt = None\n MATPLOTLIB = 0\n MATPLOTLIB_INLINED = 0\n MATPLOTLIB_DEFAULT_PLOT_KARGS = dict()\n log_loading.info(\"Can't import matplotlib. Won't be able to plot.\")\n\ndef _test_pyx():\n \"\"\"Returns if PyX is correctly installed or not\"\"\"\n try:\n with open(os.devnull, 'wb') as devnull:\n r = subprocess.check_call([\"pdflatex\", \"--version\"], stdout=devnull, stderr=subprocess.STDOUT)\n except:\n return False\n else:\n return r == 0\n\ntry:\n import pyx\n if _test_pyx():\n PYX = 1\n else:\n log_loading.warning(\"PyX dependencies are not installed ! Please install TexLive or MikTeX.\")\n PYX = 0\nexcept ImportError:\n log_loading.info(\"Can't import PyX. Won't be able to use psdump() or pdfdump().\")\n PYX = 0\n\n\nLINUX = platform.startswith(\"linux\")\nOPENBSD = platform.startswith(\"openbsd\")\nFREEBSD = \"freebsd\" in platform\nNETBSD = platform.startswith(\"netbsd\")\nDARWIN = platform.startswith(\"darwin\")\nSOLARIS = platform.startswith(\"sunos\")\nWINDOWS = platform.startswith(\"win32\")\nBSD = DARWIN or FREEBSD or OPENBSD or NETBSD\n# See https://docs.python.org/3/library/platform.html#cross-platform\nIS_64BITS = maxsize > 2**32\n\nif WINDOWS:\n try:\n if float(platform_lib.release()) >= 8.1:\n LOOPBACK_NAME = \"Microsoft KM-TEST Loopback Adapter\"\n else:\n LOOPBACK_NAME = \"Microsoft Loopback Adapter\"\n except ValueError:\n LOOPBACK_NAME = \"Microsoft Loopback Adapter\"\n # Will be different on Windows\n LOOPBACK_INTERFACE = None\nelse:\n uname = os.uname()\n LOOPBACK_NAME = \"lo\" if LINUX else \"lo0\"\n LOOPBACK_INTERFACE = LOOPBACK_NAME\n\ndef parent_function():\n return inspect.getouterframes(inspect.currentframe())\n", "path": "scapy/consts.py"}]}
1,191
182
gh_patches_debug_19624
rasdani/github-patches
git_diff
Cloud-CV__EvalAI-1979
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Search submissions by challenge name in submissions table Currently, we support searching the submissions by the `participant team name, challenge phase name, created by name and submission status`. We would like to add searching the submissions by `challenge name` and also add the same to default list filtering options. Search submissions by challenge name in submissions table Currently, we support searching the submissions by the `participant team name, challenge phase name, created by name and submission status`. We would like to add searching the submissions by `challenge name` and also add the same to default list filtering options. --- 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/jobs/admin.py` Content: ``` 1 import logging 2 3 from django.contrib import admin 4 5 from base.admin import ImportExportTimeStampedAdmin 6 7 from .models import Submission 8 from .sender import publish_submission_message 9 10 11 logger = logging.getLogger(__name__) 12 13 14 @admin.register(Submission) 15 class SubmissionAdmin(ImportExportTimeStampedAdmin): 16 actions = ['submit_job_to_worker'] 17 list_display = ('participant_team', 'get_challenge_name_and_id', 'challenge_phase', 18 'created_by', 'status', 'is_public', 'submission_number', 'submitted_at', 19 'execution_time', 'input_file', 'stdout_file', 'stderr_file', 20 'submission_result_file', 'submission_metadata_file',) 21 list_filter = ('participant_team', 'challenge_phase', 22 'status', 'is_public',) 23 search_fields = ('participant_team__team_name', 'challenge_phase__name', 24 'created_by__username', 'status',) 25 26 def get_challenge_name_and_id(self, obj): 27 """Return challenge name corresponding to phase""" 28 return "%s - %s" % (obj.challenge_phase.challenge.title, obj.challenge_phase.challenge.id) 29 get_challenge_name_and_id.short_description = 'Challenge' 30 get_challenge_name_and_id.admin_order_field = 'challenge_phase__challenge' 31 32 def submit_job_to_worker(self, request, queryset): 33 for submission in queryset: 34 challenge_id = submission.challenge_phase.challenge.id 35 challenge_phase_id = submission.challenge_phase.id 36 submission_id = submission.id 37 logger.info("[x] Received submission message with challenge id {}, challenge phase id {}, submission id {}" 38 .format(challenge_id, challenge_phase_id, submission_id)) 39 publish_submission_message(challenge_id, challenge_phase_id, submission.id) 40 queryset.update(status=Submission.SUBMITTED) 41 42 submit_job_to_worker.short_description = "Run selected submissions" 43 ``` --- 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/jobs/admin.py b/apps/jobs/admin.py --- a/apps/jobs/admin.py +++ b/apps/jobs/admin.py @@ -18,10 +18,9 @@ 'created_by', 'status', 'is_public', 'submission_number', 'submitted_at', 'execution_time', 'input_file', 'stdout_file', 'stderr_file', 'submission_result_file', 'submission_metadata_file',) - list_filter = ('participant_team', 'challenge_phase', - 'status', 'is_public',) + list_filter = ('challenge_phase__challenge', 'challenge_phase', 'status', 'is_public',) search_fields = ('participant_team__team_name', 'challenge_phase__name', - 'created_by__username', 'status',) + 'challenge_phase__challenge__title', 'created_by__username', 'status',) def get_challenge_name_and_id(self, obj): """Return challenge name corresponding to phase"""
{"golden_diff": "diff --git a/apps/jobs/admin.py b/apps/jobs/admin.py\n--- a/apps/jobs/admin.py\n+++ b/apps/jobs/admin.py\n@@ -18,10 +18,9 @@\n 'created_by', 'status', 'is_public', 'submission_number', 'submitted_at',\n 'execution_time', 'input_file', 'stdout_file', 'stderr_file',\n 'submission_result_file', 'submission_metadata_file',)\n- list_filter = ('participant_team', 'challenge_phase',\n- 'status', 'is_public',)\n+ list_filter = ('challenge_phase__challenge', 'challenge_phase', 'status', 'is_public',)\n search_fields = ('participant_team__team_name', 'challenge_phase__name',\n- 'created_by__username', 'status',)\n+ 'challenge_phase__challenge__title', 'created_by__username', 'status',)\n \n def get_challenge_name_and_id(self, obj):\n \"\"\"Return challenge name corresponding to phase\"\"\"\n", "issue": "Search submissions by challenge name in submissions table\nCurrently, we support searching the submissions by the `participant team name, challenge phase name, created by name and submission status`. We would like to add searching the submissions by `challenge name` and also add the same to default list filtering options.\nSearch submissions by challenge name in submissions table\nCurrently, we support searching the submissions by the `participant team name, challenge phase name, created by name and submission status`. We would like to add searching the submissions by `challenge name` and also add the same to default list filtering options.\n", "before_files": [{"content": "import logging\n\nfrom django.contrib import admin\n\nfrom base.admin import ImportExportTimeStampedAdmin\n\nfrom .models import Submission\nfrom .sender import publish_submission_message\n\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](Submission)\nclass SubmissionAdmin(ImportExportTimeStampedAdmin):\n actions = ['submit_job_to_worker']\n list_display = ('participant_team', 'get_challenge_name_and_id', 'challenge_phase',\n 'created_by', 'status', 'is_public', 'submission_number', 'submitted_at',\n 'execution_time', 'input_file', 'stdout_file', 'stderr_file',\n 'submission_result_file', 'submission_metadata_file',)\n list_filter = ('participant_team', 'challenge_phase',\n 'status', 'is_public',)\n search_fields = ('participant_team__team_name', 'challenge_phase__name',\n 'created_by__username', 'status',)\n\n def get_challenge_name_and_id(self, obj):\n \"\"\"Return challenge name corresponding to phase\"\"\"\n return \"%s - %s\" % (obj.challenge_phase.challenge.title, obj.challenge_phase.challenge.id)\n get_challenge_name_and_id.short_description = 'Challenge'\n get_challenge_name_and_id.admin_order_field = 'challenge_phase__challenge'\n\n def submit_job_to_worker(self, request, queryset):\n for submission in queryset:\n challenge_id = submission.challenge_phase.challenge.id\n challenge_phase_id = submission.challenge_phase.id\n submission_id = submission.id\n logger.info(\"[x] Received submission message with challenge id {}, challenge phase id {}, submission id {}\"\n .format(challenge_id, challenge_phase_id, submission_id))\n publish_submission_message(challenge_id, challenge_phase_id, submission.id)\n queryset.update(status=Submission.SUBMITTED)\n\n submit_job_to_worker.short_description = \"Run selected submissions\"\n", "path": "apps/jobs/admin.py"}], "after_files": [{"content": "import logging\n\nfrom django.contrib import admin\n\nfrom base.admin import ImportExportTimeStampedAdmin\n\nfrom .models import Submission\nfrom .sender import publish_submission_message\n\n\nlogger = logging.getLogger(__name__)\n\n\[email protected](Submission)\nclass SubmissionAdmin(ImportExportTimeStampedAdmin):\n actions = ['submit_job_to_worker']\n list_display = ('participant_team', 'get_challenge_name_and_id', 'challenge_phase',\n 'created_by', 'status', 'is_public', 'submission_number', 'submitted_at',\n 'execution_time', 'input_file', 'stdout_file', 'stderr_file',\n 'submission_result_file', 'submission_metadata_file',)\n list_filter = ('challenge_phase__challenge', 'challenge_phase', 'status', 'is_public',)\n search_fields = ('participant_team__team_name', 'challenge_phase__name',\n 'challenge_phase__challenge__title', 'created_by__username', 'status',)\n\n def get_challenge_name_and_id(self, obj):\n \"\"\"Return challenge name corresponding to phase\"\"\"\n return \"%s - %s\" % (obj.challenge_phase.challenge.title, obj.challenge_phase.challenge.id)\n get_challenge_name_and_id.short_description = 'Challenge'\n get_challenge_name_and_id.admin_order_field = 'challenge_phase__challenge'\n\n def submit_job_to_worker(self, request, queryset):\n for submission in queryset:\n challenge_id = submission.challenge_phase.challenge.id\n challenge_phase_id = submission.challenge_phase.id\n submission_id = submission.id\n logger.info(\"[x] Received submission message with challenge id {}, challenge phase id {}, submission id {}\"\n .format(challenge_id, challenge_phase_id, submission_id))\n publish_submission_message(challenge_id, challenge_phase_id, submission.id)\n queryset.update(status=Submission.SUBMITTED)\n\n submit_job_to_worker.short_description = \"Run selected submissions\"\n", "path": "apps/jobs/admin.py"}]}
835
205
gh_patches_debug_25771
rasdani/github-patches
git_diff
mne-tools__mne-python-5796
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- ENH: Allow retrieval of GFP #2538 added the ability to plot GFPs. Currently, the GFP is [only temporarily calculated for plotting](https://github.com/Eric89GXL/mne-python/blob/7f8c69bae49041bb4f0507539ccda1bda7f0b394/mne/viz/evoked.py#L397), and the user has no easy way to access the data. In our EEG workflow, we typically calculate GFPs for every single participant and condition, and average conditions across participants for plotting; or we compute statistics based on the GFP differences. It is therefore highly important for us to have easy access to the GFPs. We resorted to doing the calculations manually based on `Evoked.data`, but this is cumbersome as one has to "leave" the MNE sphere and implement the operations by hand via NumPy and/or Pandas -- which is not easy for beginners and error-prone, as Pandas by default [uses the unbiased estimator](http://stackoverflow.com/questions/24984178/different-std-in-pandas-vs-numpy) for standard deviation and NumPy doesn't. I can try to implement a GFP function, but I would need assistance in doing so. I don't really know where to start or where to put that code: should it be a method of the `Evoked` class? Potentially exposed as a property, so it could be accessed via `Evoked.gfp`? Or should it be an entirely new class? Would it have to have its own plotting method? etc. pp. Any help and suggestions would be greatly appreciated. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `tutorials/plot_object_evoked.py` Content: ``` 1 """ 2 .. _tut_evoked_objects: 3 4 The :class:`Evoked <mne.Evoked>` data structure: evoked/averaged data 5 ===================================================================== 6 7 The :class:`Evoked <mne.Evoked>` data structure is mainly used for storing 8 averaged data over trials. In MNE the evoked objects are usually created by 9 averaging epochs data with :func:`mne.Epochs.average`. 10 """ 11 12 import os.path as op 13 14 import mne 15 16 ############################################################################### 17 # Here for convenience we read the evoked dataset from a file. 18 data_path = mne.datasets.sample.data_path() 19 fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') 20 evokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True) 21 print(evokeds) 22 23 ############################################################################### 24 # Notice that the reader function returned a list of evoked instances. This is 25 # because you can store multiple categories into a single file. Here we have 26 # categories of 27 # ``['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual']``. 28 # We can also use ``condition`` parameter to read in only one category. 29 evoked = mne.read_evokeds(fname, condition='Left Auditory') 30 evoked.apply_baseline((None, 0)).apply_proj() 31 print(evoked) 32 33 ############################################################################### 34 # If you're gone through the tutorials of raw and epochs datasets, you're 35 # probably already familiar with the :class:`Info <mne.Info>` attribute. 36 # There is nothing new or special with the ``evoked.info``. All the relevant 37 # info is still there. 38 print(evoked.info) 39 print(evoked.times) 40 41 ############################################################################### 42 # The evoked data structure also contains some new attributes easily 43 # accessible: 44 print(evoked.nave) # Number of averaged epochs. 45 print(evoked.first) # First time sample. 46 print(evoked.last) # Last time sample. 47 print(evoked.comment) # Comment on dataset. Usually the condition. 48 print(evoked.kind) # Type of data, either average or standard_error. 49 50 ############################################################################### 51 # The data is also easily accessible. Since the evoked data arrays are usually 52 # much smaller than raw or epochs datasets, they are preloaded into the memory 53 # when the evoked object is constructed. You can access the data as a numpy 54 # array. 55 data = evoked.data 56 print(data.shape) 57 58 ############################################################################### 59 # The data is arranged in an array of shape `(n_channels, n_times)`. Notice 60 # that unlike epochs, evoked object does not support indexing. This means that 61 # to access the data of a specific channel you must use the data array 62 # directly. 63 print('Data from channel {0}:'.format(evoked.ch_names[10])) 64 print(data[10]) 65 66 ############################################################################### 67 # If you want to import evoked data from some other system and you have it in a 68 # numpy array you can use :class:`mne.EvokedArray` for that. All you need is 69 # the data and some info about the evoked data. For more information, see 70 # :ref:`tut_creating_data_structures`. 71 evoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0]) 72 evoked.plot(time_unit='s') 73 74 ############################################################################### 75 # To write an evoked dataset to a file, use the :meth:`mne.Evoked.save` method. 76 # To save multiple categories to a single file, see :func:`mne.write_evokeds`. 77 ``` --- 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/tutorials/plot_object_evoked.py b/tutorials/plot_object_evoked.py --- a/tutorials/plot_object_evoked.py +++ b/tutorials/plot_object_evoked.py @@ -8,9 +8,11 @@ averaged data over trials. In MNE the evoked objects are usually created by averaging epochs data with :func:`mne.Epochs.average`. """ +# sphinx_gallery_thumbnail_number = 2 import os.path as op +import matplotlib.pyplot as plt import mne ############################################################################### @@ -63,6 +65,16 @@ print('Data from channel {0}:'.format(evoked.ch_names[10])) print(data[10]) +############################################################################### +# In the same vein, we can quickly extract (and, e.g., plot) the GFP as the +# standard deviation across channels, here shown just for EEG. + +gfp = evoked.copy().pick_types(eeg=True, meg=False).data.std(axis=0) +fig, ax = plt.subplots(1) +ax.plot(evoked.times, gfp / 1e6) # scale to uV +ax.set(xlabel='Time (sec)', ylabel='GFP (uV)') +fig.tight_layout() + ############################################################################### # If you want to import evoked data from some other system and you have it in a # numpy array you can use :class:`mne.EvokedArray` for that. All you need is
{"golden_diff": "diff --git a/tutorials/plot_object_evoked.py b/tutorials/plot_object_evoked.py\n--- a/tutorials/plot_object_evoked.py\n+++ b/tutorials/plot_object_evoked.py\n@@ -8,9 +8,11 @@\n averaged data over trials. In MNE the evoked objects are usually created by\n averaging epochs data with :func:`mne.Epochs.average`.\n \"\"\"\n+# sphinx_gallery_thumbnail_number = 2\n \n import os.path as op\n \n+import matplotlib.pyplot as plt\n import mne\n \n ###############################################################################\n@@ -63,6 +65,16 @@\n print('Data from channel {0}:'.format(evoked.ch_names[10]))\n print(data[10])\n \n+###############################################################################\n+# In the same vein, we can quickly extract (and, e.g., plot) the GFP as the\n+# standard deviation across channels, here shown just for EEG.\n+\n+gfp = evoked.copy().pick_types(eeg=True, meg=False).data.std(axis=0)\n+fig, ax = plt.subplots(1)\n+ax.plot(evoked.times, gfp / 1e6) # scale to uV\n+ax.set(xlabel='Time (sec)', ylabel='GFP (uV)')\n+fig.tight_layout()\n+\n ###############################################################################\n # If you want to import evoked data from some other system and you have it in a\n # numpy array you can use :class:`mne.EvokedArray` for that. All you need is\n", "issue": "ENH: Allow retrieval of GFP\n#2538 added the ability to plot GFPs. Currently, the GFP is [only temporarily calculated for plotting](https://github.com/Eric89GXL/mne-python/blob/7f8c69bae49041bb4f0507539ccda1bda7f0b394/mne/viz/evoked.py#L397), and the user has no easy way to access the data. \r\n\r\n In our EEG workflow, we typically calculate GFPs for every single participant and condition, and average conditions across participants for plotting; or we compute statistics based on the GFP differences. It is therefore highly important for us to have easy access to the GFPs. We resorted to doing the calculations manually based on `Evoked.data`, but this is cumbersome as one has to \"leave\" the MNE sphere and implement the operations by hand via NumPy and/or Pandas -- which is not easy for beginners and error-prone, as Pandas by default [uses the unbiased estimator](http://stackoverflow.com/questions/24984178/different-std-in-pandas-vs-numpy) for standard deviation and NumPy doesn't.\r\n\r\nI can try to implement a GFP function, but I would need assistance in doing so. I don't really know where to start or where to put that code: should it be a method of the `Evoked` class? Potentially exposed as a property, so it could be accessed via `Evoked.gfp`? Or should it be an entirely new class? Would it have to have its own plotting method? etc. pp. Any help and suggestions would be greatly appreciated.\n", "before_files": [{"content": "\"\"\"\n.. _tut_evoked_objects:\n\nThe :class:`Evoked <mne.Evoked>` data structure: evoked/averaged data\n=====================================================================\n\nThe :class:`Evoked <mne.Evoked>` data structure is mainly used for storing\naveraged data over trials. In MNE the evoked objects are usually created by\naveraging epochs data with :func:`mne.Epochs.average`.\n\"\"\"\n\nimport os.path as op\n\nimport mne\n\n###############################################################################\n# Here for convenience we read the evoked dataset from a file.\ndata_path = mne.datasets.sample.data_path()\nfname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\nevokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)\nprint(evokeds)\n\n###############################################################################\n# Notice that the reader function returned a list of evoked instances. This is\n# because you can store multiple categories into a single file. Here we have\n# categories of\n# ``['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual']``.\n# We can also use ``condition`` parameter to read in only one category.\nevoked = mne.read_evokeds(fname, condition='Left Auditory')\nevoked.apply_baseline((None, 0)).apply_proj()\nprint(evoked)\n\n###############################################################################\n# If you're gone through the tutorials of raw and epochs datasets, you're\n# probably already familiar with the :class:`Info <mne.Info>` attribute.\n# There is nothing new or special with the ``evoked.info``. All the relevant\n# info is still there.\nprint(evoked.info)\nprint(evoked.times)\n\n###############################################################################\n# The evoked data structure also contains some new attributes easily\n# accessible:\nprint(evoked.nave) # Number of averaged epochs.\nprint(evoked.first) # First time sample.\nprint(evoked.last) # Last time sample.\nprint(evoked.comment) # Comment on dataset. Usually the condition.\nprint(evoked.kind) # Type of data, either average or standard_error.\n\n###############################################################################\n# The data is also easily accessible. Since the evoked data arrays are usually\n# much smaller than raw or epochs datasets, they are preloaded into the memory\n# when the evoked object is constructed. You can access the data as a numpy\n# array.\ndata = evoked.data\nprint(data.shape)\n\n###############################################################################\n# The data is arranged in an array of shape `(n_channels, n_times)`. Notice\n# that unlike epochs, evoked object does not support indexing. This means that\n# to access the data of a specific channel you must use the data array\n# directly.\nprint('Data from channel {0}:'.format(evoked.ch_names[10]))\nprint(data[10])\n\n###############################################################################\n# If you want to import evoked data from some other system and you have it in a\n# numpy array you can use :class:`mne.EvokedArray` for that. All you need is\n# the data and some info about the evoked data. For more information, see\n# :ref:`tut_creating_data_structures`.\nevoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])\nevoked.plot(time_unit='s')\n\n###############################################################################\n# To write an evoked dataset to a file, use the :meth:`mne.Evoked.save` method.\n# To save multiple categories to a single file, see :func:`mne.write_evokeds`.\n", "path": "tutorials/plot_object_evoked.py"}], "after_files": [{"content": "\"\"\"\n.. _tut_evoked_objects:\n\nThe :class:`Evoked <mne.Evoked>` data structure: evoked/averaged data\n=====================================================================\n\nThe :class:`Evoked <mne.Evoked>` data structure is mainly used for storing\naveraged data over trials. In MNE the evoked objects are usually created by\naveraging epochs data with :func:`mne.Epochs.average`.\n\"\"\"\n# sphinx_gallery_thumbnail_number = 2\n\nimport os.path as op\n\nimport matplotlib.pyplot as plt\nimport mne\n\n###############################################################################\n# Here for convenience we read the evoked dataset from a file.\ndata_path = mne.datasets.sample.data_path()\nfname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\nevokeds = mne.read_evokeds(fname, baseline=(None, 0), proj=True)\nprint(evokeds)\n\n###############################################################################\n# Notice that the reader function returned a list of evoked instances. This is\n# because you can store multiple categories into a single file. Here we have\n# categories of\n# ``['Left Auditory', 'Right Auditory', 'Left Visual', 'Right Visual']``.\n# We can also use ``condition`` parameter to read in only one category.\nevoked = mne.read_evokeds(fname, condition='Left Auditory')\nevoked.apply_baseline((None, 0)).apply_proj()\nprint(evoked)\n\n###############################################################################\n# If you're gone through the tutorials of raw and epochs datasets, you're\n# probably already familiar with the :class:`Info <mne.Info>` attribute.\n# There is nothing new or special with the ``evoked.info``. All the relevant\n# info is still there.\nprint(evoked.info)\nprint(evoked.times)\n\n###############################################################################\n# The evoked data structure also contains some new attributes easily\n# accessible:\nprint(evoked.nave) # Number of averaged epochs.\nprint(evoked.first) # First time sample.\nprint(evoked.last) # Last time sample.\nprint(evoked.comment) # Comment on dataset. Usually the condition.\nprint(evoked.kind) # Type of data, either average or standard_error.\n\n###############################################################################\n# The data is also easily accessible. Since the evoked data arrays are usually\n# much smaller than raw or epochs datasets, they are preloaded into the memory\n# when the evoked object is constructed. You can access the data as a numpy\n# array.\ndata = evoked.data\nprint(data.shape)\n\n###############################################################################\n# The data is arranged in an array of shape `(n_channels, n_times)`. Notice\n# that unlike epochs, evoked object does not support indexing. This means that\n# to access the data of a specific channel you must use the data array\n# directly.\nprint('Data from channel {0}:'.format(evoked.ch_names[10]))\nprint(data[10])\n\n###############################################################################\n# In the same vein, we can quickly extract (and, e.g., plot) the GFP as the\n# standard deviation across channels, here shown just for EEG.\n\ngfp = evoked.copy().pick_types(eeg=True, meg=False).data.std(axis=0)\nfig, ax = plt.subplots(1)\nax.plot(evoked.times, gfp / 1e6) # scale to uV\nax.set(xlabel='Time (sec)', ylabel='GFP (uV)')\nfig.tight_layout()\n\n###############################################################################\n# If you want to import evoked data from some other system and you have it in a\n# numpy array you can use :class:`mne.EvokedArray` for that. All you need is\n# the data and some info about the evoked data. For more information, see\n# :ref:`tut_creating_data_structures`.\nevoked = mne.EvokedArray(data, evoked.info, tmin=evoked.times[0])\nevoked.plot(time_unit='s')\n\n###############################################################################\n# To write an evoked dataset to a file, use the :meth:`mne.Evoked.save` method.\n# To save multiple categories to a single file, see :func:`mne.write_evokeds`.\n", "path": "tutorials/plot_object_evoked.py"}]}
1,525
318
gh_patches_debug_1665
rasdani/github-patches
git_diff
python-pillow__Pillow-1686
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Repeated looping over image stack shows last frame in place of first frame When looping through the frames in an animation or TIFF stack with `ImageSequence.Iterator`, the frame pointer is not reset for the first frame. Consequently, if the loop is run through a second time the final frame is shown again instead of the first frame. ### Demo Code ``` python from PIL import Image, ImageSequence import os # Make a test image os.system(( "convert -depth 8 -size 1x1 xc:'rgb(100,100,100)' xc:'rgb(121,121,121)'" " xc:'rgb(142,142,142)' xc:'rgb(163,163,163)' image.tif" )) # Open the image im = Image.open('image.tif') # Run through the image print('First run') for frame in ImageSequence.Iterator(im): print(list(frame.getdata())) # Run through the image again print('Second run') for frame in ImageSequence.Iterator(im): print(list(frame.getdata())) ``` Output ``` First run [100] [121] [142] [163] Second run [163] [121] [142] [163] ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `PIL/ImageSequence.py` Content: ``` 1 # 2 # The Python Imaging Library. 3 # $Id$ 4 # 5 # sequence support classes 6 # 7 # history: 8 # 1997-02-20 fl Created 9 # 10 # Copyright (c) 1997 by Secret Labs AB. 11 # Copyright (c) 1997 by Fredrik Lundh. 12 # 13 # See the README file for information on usage and redistribution. 14 # 15 16 ## 17 18 19 class Iterator(object): 20 """ 21 This class implements an iterator object that can be used to loop 22 over an image sequence. 23 24 You can use the ``[]`` operator to access elements by index. This operator 25 will raise an :py:exc:`IndexError` if you try to access a nonexistent 26 frame. 27 28 :param im: An image object. 29 """ 30 31 def __init__(self, im): 32 if not hasattr(im, "seek"): 33 raise AttributeError("im must have seek method") 34 self.im = im 35 36 def __getitem__(self, ix): 37 try: 38 if ix: 39 self.im.seek(ix) 40 return self.im 41 except EOFError: 42 raise IndexError # end of sequence 43 ``` --- 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/PIL/ImageSequence.py b/PIL/ImageSequence.py --- a/PIL/ImageSequence.py +++ b/PIL/ImageSequence.py @@ -35,8 +35,7 @@ def __getitem__(self, ix): try: - if ix: - self.im.seek(ix) + self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequence
{"golden_diff": "diff --git a/PIL/ImageSequence.py b/PIL/ImageSequence.py\n--- a/PIL/ImageSequence.py\n+++ b/PIL/ImageSequence.py\n@@ -35,8 +35,7 @@\n \n def __getitem__(self, ix):\n try:\n- if ix:\n- self.im.seek(ix)\n+ self.im.seek(ix)\n return self.im\n except EOFError:\n raise IndexError # end of sequence\n", "issue": "Repeated looping over image stack shows last frame in place of first frame\nWhen looping through the frames in an animation or TIFF stack with `ImageSequence.Iterator`, the frame pointer is not reset for the first frame. Consequently, if the loop is run through a second time the final frame is shown again instead of the first frame.\n### Demo\n\nCode\n\n``` python\nfrom PIL import Image, ImageSequence\nimport os\n# Make a test image\nos.system((\n \"convert -depth 8 -size 1x1 xc:'rgb(100,100,100)' xc:'rgb(121,121,121)'\"\n \" xc:'rgb(142,142,142)' xc:'rgb(163,163,163)' image.tif\"\n))\n# Open the image\nim = Image.open('image.tif')\n# Run through the image\nprint('First run')\nfor frame in ImageSequence.Iterator(im):\n print(list(frame.getdata()))\n# Run through the image again\nprint('Second run')\nfor frame in ImageSequence.Iterator(im):\n print(list(frame.getdata()))\n```\n\nOutput\n\n```\nFirst run\n[100]\n[121]\n[142]\n[163]\nSecond run\n[163]\n[121]\n[142]\n[163]\n```\n\n", "before_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# sequence support classes\n#\n# history:\n# 1997-02-20 fl Created\n#\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n\n\nclass Iterator(object):\n \"\"\"\n This class implements an iterator object that can be used to loop\n over an image sequence.\n\n You can use the ``[]`` operator to access elements by index. This operator\n will raise an :py:exc:`IndexError` if you try to access a nonexistent\n frame.\n\n :param im: An image object.\n \"\"\"\n\n def __init__(self, im):\n if not hasattr(im, \"seek\"):\n raise AttributeError(\"im must have seek method\")\n self.im = im\n\n def __getitem__(self, ix):\n try:\n if ix:\n self.im.seek(ix)\n return self.im\n except EOFError:\n raise IndexError # end of sequence\n", "path": "PIL/ImageSequence.py"}], "after_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# sequence support classes\n#\n# history:\n# 1997-02-20 fl Created\n#\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n\n\nclass Iterator(object):\n \"\"\"\n This class implements an iterator object that can be used to loop\n over an image sequence.\n\n You can use the ``[]`` operator to access elements by index. This operator\n will raise an :py:exc:`IndexError` if you try to access a nonexistent\n frame.\n\n :param im: An image object.\n \"\"\"\n\n def __init__(self, im):\n if not hasattr(im, \"seek\"):\n raise AttributeError(\"im must have seek method\")\n self.im = im\n\n def __getitem__(self, ix):\n try:\n self.im.seek(ix)\n return self.im\n except EOFError:\n raise IndexError # end of sequence\n", "path": "PIL/ImageSequence.py"}]}
877
95
gh_patches_debug_16844
rasdani/github-patches
git_diff
aws-cloudformation__cfn-lint-1227
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Warning Check on Unused Parameter hides Error Check about Missing Parameter Type *cfn-lint version: cfn-lint 0.25.3* Parameters defined in a template, but not directly used, are not validated for missing attributes like `Type`. For various reasons, we want to include parameters in our templates that are not used by resources in the templates and therefore disable `W2001` When this happens, the following template will not fail cfn-lint. If I uncomment the `Metadata` section, I will finally see the `E1012` failure. I should not have to resolve a Warning in order to unmask an Error. ```yaml Parameters: Foo: Description: "Foo?" Conditions: AlwaysFalse: !Equals [ true, false ] Resources: # Metadata: # Foo: !Ref Foo NullResource: Type: Custom::NullResource Condition: AlwaysFalse ``` --- 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/parameters/Configuration.py` Content: ``` 1 """ 2 Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 SPDX-License-Identifier: MIT-0 4 """ 5 from cfnlint.rules import CloudFormationLintRule 6 from cfnlint.rules import RuleMatch 7 8 9 class Configuration(CloudFormationLintRule): 10 """Check if Parameters are configured correctly""" 11 id = 'E2001' 12 shortdesc = 'Parameters have appropriate properties' 13 description = 'Making sure the parameters are properly configured' 14 source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html' 15 tags = ['parameters'] 16 17 valid_keys = [ 18 'AllowedPattern', 19 'AllowedValues', 20 'ConstraintDescription', 21 'Default', 22 'Description', 23 'MaxLength', 24 'MaxValue', 25 'MinLength', 26 'MinValue', 27 'NoEcho', 28 'Type', 29 ] 30 31 def match(self, cfn): 32 """Check CloudFormation Parameters""" 33 34 matches = [] 35 36 for paramname, paramvalue in cfn.get_parameters().items(): 37 for propname, _ in paramvalue.items(): 38 if propname not in self.valid_keys: 39 message = 'Parameter {0} has invalid property {1}' 40 matches.append(RuleMatch( 41 ['Parameters', paramname, propname], 42 message.format(paramname, propname) 43 )) 44 45 return matches 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/src/cfnlint/rules/parameters/Configuration.py b/src/cfnlint/rules/parameters/Configuration.py --- a/src/cfnlint/rules/parameters/Configuration.py +++ b/src/cfnlint/rules/parameters/Configuration.py @@ -28,6 +28,10 @@ 'Type', ] + required_keys = [ + 'Type' + ] + def match(self, cfn): """Check CloudFormation Parameters""" @@ -41,5 +45,12 @@ ['Parameters', paramname, propname], message.format(paramname, propname) )) + for reqname in self.required_keys: + if reqname not in paramvalue.keys(): + message = 'Parameter {0} is missing required property {1}' + matches.append(RuleMatch( + ['Parameters', paramname], + message.format(paramname, reqname) + )) return matches
{"golden_diff": "diff --git a/src/cfnlint/rules/parameters/Configuration.py b/src/cfnlint/rules/parameters/Configuration.py\n--- a/src/cfnlint/rules/parameters/Configuration.py\n+++ b/src/cfnlint/rules/parameters/Configuration.py\n@@ -28,6 +28,10 @@\n 'Type',\n ]\n \n+ required_keys = [\n+ 'Type'\n+ ]\n+\n def match(self, cfn):\n \"\"\"Check CloudFormation Parameters\"\"\"\n \n@@ -41,5 +45,12 @@\n ['Parameters', paramname, propname],\n message.format(paramname, propname)\n ))\n+ for reqname in self.required_keys:\n+ if reqname not in paramvalue.keys():\n+ message = 'Parameter {0} is missing required property {1}'\n+ matches.append(RuleMatch(\n+ ['Parameters', paramname],\n+ message.format(paramname, reqname)\n+ ))\n \n return matches\n", "issue": "Warning Check on Unused Parameter hides Error Check about Missing Parameter Type\n*cfn-lint version: cfn-lint 0.25.3*\r\n\r\nParameters defined in a template, but not directly used, are not validated for missing attributes like `Type`.\r\n\r\nFor various reasons, we want to include parameters in our templates that are not used by resources in the templates and therefore disable `W2001` When this happens, the following template will not fail cfn-lint. If I uncomment the `Metadata` section, I will finally see the `E1012` failure. I should not have to resolve a Warning in order to unmask an Error.\r\n\r\n```yaml\r\nParameters:\r\n Foo:\r\n Description: \"Foo?\"\r\nConditions:\r\n AlwaysFalse: !Equals [ true, false ]\r\nResources:\r\n # Metadata:\r\n # Foo: !Ref Foo\r\n NullResource:\r\n Type: Custom::NullResource\r\n Condition: AlwaysFalse\r\n```\r\n\n", "before_files": [{"content": "\"\"\"\nCopyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: MIT-0\n\"\"\"\nfrom cfnlint.rules import CloudFormationLintRule\nfrom cfnlint.rules import RuleMatch\n\n\nclass Configuration(CloudFormationLintRule):\n \"\"\"Check if Parameters are configured correctly\"\"\"\n id = 'E2001'\n shortdesc = 'Parameters have appropriate properties'\n description = 'Making sure the parameters are properly configured'\n source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html'\n tags = ['parameters']\n\n valid_keys = [\n 'AllowedPattern',\n 'AllowedValues',\n 'ConstraintDescription',\n 'Default',\n 'Description',\n 'MaxLength',\n 'MaxValue',\n 'MinLength',\n 'MinValue',\n 'NoEcho',\n 'Type',\n ]\n\n def match(self, cfn):\n \"\"\"Check CloudFormation Parameters\"\"\"\n\n matches = []\n\n for paramname, paramvalue in cfn.get_parameters().items():\n for propname, _ in paramvalue.items():\n if propname not in self.valid_keys:\n message = 'Parameter {0} has invalid property {1}'\n matches.append(RuleMatch(\n ['Parameters', paramname, propname],\n message.format(paramname, propname)\n ))\n\n return matches\n", "path": "src/cfnlint/rules/parameters/Configuration.py"}], "after_files": [{"content": "\"\"\"\nCopyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nSPDX-License-Identifier: MIT-0\n\"\"\"\nfrom cfnlint.rules import CloudFormationLintRule\nfrom cfnlint.rules import RuleMatch\n\n\nclass Configuration(CloudFormationLintRule):\n \"\"\"Check if Parameters are configured correctly\"\"\"\n id = 'E2001'\n shortdesc = 'Parameters have appropriate properties'\n description = 'Making sure the parameters are properly configured'\n source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html'\n tags = ['parameters']\n\n valid_keys = [\n 'AllowedPattern',\n 'AllowedValues',\n 'ConstraintDescription',\n 'Default',\n 'Description',\n 'MaxLength',\n 'MaxValue',\n 'MinLength',\n 'MinValue',\n 'NoEcho',\n 'Type',\n ]\n\n required_keys = [\n 'Type'\n ]\n\n def match(self, cfn):\n \"\"\"Check CloudFormation Parameters\"\"\"\n\n matches = []\n\n for paramname, paramvalue in cfn.get_parameters().items():\n for propname, _ in paramvalue.items():\n if propname not in self.valid_keys:\n message = 'Parameter {0} has invalid property {1}'\n matches.append(RuleMatch(\n ['Parameters', paramname, propname],\n message.format(paramname, propname)\n ))\n for reqname in self.required_keys:\n if reqname not in paramvalue.keys():\n message = 'Parameter {0} is missing required property {1}'\n matches.append(RuleMatch(\n ['Parameters', paramname],\n message.format(paramname, reqname)\n ))\n\n return matches\n", "path": "src/cfnlint/rules/parameters/Configuration.py"}]}
845
208
gh_patches_debug_31157
rasdani/github-patches
git_diff
alltheplaces__alltheplaces-3349
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Spider signet_jewelers is broken During the global build at 2021-07-14-14-42-22, spider **signet_jewelers** failed with **2353 features** and **6 errors**. Here's [the log](https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/logs/signet_jewelers.txt) and [the output](https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/output/signet_jewelers.geojson) ([on a map](https://data.alltheplaces.xyz/map.html?show=https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/output/signet_jewelers.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/signet_jewelers.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 import json 3 import re 4 5 import scrapy 6 7 from locations.items import GeojsonPointItem 8 from locations.hours import OpeningHours 9 10 11 class SignetJewelersSpider(scrapy.Spider): 12 name = "signet_jewelers" 13 allowed_domains = ['www.jared.com', 'www.kay.com', 'www.zales.com', 'www.pagoda.com', 'www.peoplesjewellers.com', 14 'www.ernestjones.co.uk', 'www.hsamuel.co.uk'] 15 download_delay = 0.5 # limit the delay to avoid 403 errors 16 17 ca_prov = ['Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador', 18 'Nova Scotia', 'Ontario', 'Saskatchewan'] 19 20 states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", 21 "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", 22 "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", 23 "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", 24 "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", 25 "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", 26 "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", 27 "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" 28 ] 29 30 def start_requests(self): 31 north_america_brands = ["jared", "kay", "zales", "pagoda", "peoplesjewellers"] 32 33 uk_urls = [ 34 'https://www.hsamuel.co.uk/scripts/dist/store-locator/functionality/store-details.min.js?sprint-17_20190911.3', 35 'https://www.ernestjones.co.uk/scripts/store-locator/storeLocationDetails.js'] 36 37 for url in uk_urls: 38 yield scrapy.Request(url=url, callback=self.parse_uk) 39 40 template = 'https://www.{brand}.com/store-finder/view-stores/{region}' 41 42 for brand in north_america_brands: 43 if brand == "peoplesjewellers": 44 for prov in SignetJewelersSpider.ca_prov: 45 url = template.format(brand=brand, region=prov) 46 yield scrapy.Request(url, callback=self.parse_cities) 47 else: 48 for state in SignetJewelersSpider.states: 49 url = template.format(brand=brand, region=state) 50 yield scrapy.Request(url, callback=self.parse_cities) 51 52 def parse_cities(self, response): 53 cities = response.xpath('//*[@class="viewstoreslist"]/a/@href').extract() 54 for i in cities: 55 yield scrapy.Request(response.urljoin(i), callback=self.parse) 56 57 def parse(self, response): 58 script = " ".join(response.xpath('//*[@id="js-store-details"]/div/script/text()').extract()) 59 data = re.search(r'storeInformation\s=\s((?s).*)', script).groups()[0] 60 data = data.replace(";", '') 61 data = eval(data) 62 63 if data["region"] in SignetJewelersSpider.ca_prov: 64 country = 'CA' 65 else: 66 country = 'US' 67 68 properties = { 69 'ref': data["name"], 70 'name': data["displayName"], 71 'addr_full': data["line1"], 72 'city': data["town"], 73 'state': data["region"], 74 'postcode': data["postalCode"], 75 'country': country, 76 'lat': data["latitude"], 77 'lon': data["longitude"], 78 'phone': data["phone"], 79 'website': response.url, 80 'brand': re.search(r'www.(\w+)', response.url)[1], 81 } 82 83 yield GeojsonPointItem(**properties) 84 85 def parse_uk(self, response): 86 data = re.search(r'Signet.allStoreDetails=((?s).*)', response.text)[1] 87 data = data.replace(';', '') 88 data = json.loads(data) 89 90 for store in data: 91 properties = { 92 'ref': store["number"], 93 'name': store["name"], 94 'addr_full': store["addressLine1"], 95 'city': store["town"], 96 'postcode': store["postcode"], 97 'country': 'GB', 98 'lat': store["latitude"], 99 'lon': store["longitude"], 100 'brand': re.search(r'www.(\w+)', response.url)[1], 101 } 102 103 yield GeojsonPointItem(**properties) 104 ``` --- 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/signet_jewelers.py b/locations/spiders/signet_jewelers.py --- a/locations/spiders/signet_jewelers.py +++ b/locations/spiders/signet_jewelers.py @@ -56,29 +56,38 @@ def parse(self, response): script = " ".join(response.xpath('//*[@id="js-store-details"]/div/script/text()').extract()) - data = re.search(r'storeInformation\s=\s((?s).*)', script).groups()[0] - data = data.replace(";", '') - data = eval(data) - - if data["region"] in SignetJewelersSpider.ca_prov: - country = 'CA' - else: - country = 'US' - - properties = { - 'ref': data["name"], - 'name': data["displayName"], - 'addr_full': data["line1"], - 'city': data["town"], - 'state': data["region"], - 'postcode': data["postalCode"], - 'country': country, - 'lat': data["latitude"], - 'lon': data["longitude"], - 'phone': data["phone"], - 'website': response.url, - 'brand': re.search(r'www.(\w+)', response.url)[1], - } + data = None + + if re.search(r'storeInformation\s=\s((?s).*)', script) is not None: + data = re.search(r'storeInformation\s=\s((?s).*)', script).groups() + + properties = {} + + if data is not None: + if len(data) > 0: + data = data[0] + data = data.replace(";", '') + data = eval(data) + + if data["region"] in SignetJewelersSpider.ca_prov: + country = 'CA' + else: + country = 'US' + + properties = { + 'ref': data["name"], + 'name': data["displayName"], + 'addr_full': data["line1"], + 'city': data["town"], + 'state': data["region"], + 'postcode': data["postalCode"], + 'country': country, + 'lat': data["latitude"], + 'lon': data["longitude"], + 'phone': data["phone"], + 'website': response.url, + 'brand': re.search(r'www.(\w+)', response.url)[1], + } yield GeojsonPointItem(**properties)
{"golden_diff": "diff --git a/locations/spiders/signet_jewelers.py b/locations/spiders/signet_jewelers.py\n--- a/locations/spiders/signet_jewelers.py\n+++ b/locations/spiders/signet_jewelers.py\n@@ -56,29 +56,38 @@\n \n def parse(self, response):\n script = \" \".join(response.xpath('//*[@id=\"js-store-details\"]/div/script/text()').extract())\n- data = re.search(r'storeInformation\\s=\\s((?s).*)', script).groups()[0]\n- data = data.replace(\";\", '')\n- data = eval(data)\n-\n- if data[\"region\"] in SignetJewelersSpider.ca_prov:\n- country = 'CA'\n- else:\n- country = 'US'\n-\n- properties = {\n- 'ref': data[\"name\"],\n- 'name': data[\"displayName\"],\n- 'addr_full': data[\"line1\"],\n- 'city': data[\"town\"],\n- 'state': data[\"region\"],\n- 'postcode': data[\"postalCode\"],\n- 'country': country,\n- 'lat': data[\"latitude\"],\n- 'lon': data[\"longitude\"],\n- 'phone': data[\"phone\"],\n- 'website': response.url,\n- 'brand': re.search(r'www.(\\w+)', response.url)[1],\n- }\n+ data = None\n+\n+ if re.search(r'storeInformation\\s=\\s((?s).*)', script) is not None:\n+ data = re.search(r'storeInformation\\s=\\s((?s).*)', script).groups()\n+\n+ properties = {}\n+\n+ if data is not None:\n+ if len(data) > 0:\n+ data = data[0]\n+ data = data.replace(\";\", '')\n+ data = eval(data)\n+\n+ if data[\"region\"] in SignetJewelersSpider.ca_prov:\n+ country = 'CA'\n+ else:\n+ country = 'US'\n+\n+ properties = {\n+ 'ref': data[\"name\"],\n+ 'name': data[\"displayName\"],\n+ 'addr_full': data[\"line1\"],\n+ 'city': data[\"town\"],\n+ 'state': data[\"region\"],\n+ 'postcode': data[\"postalCode\"],\n+ 'country': country,\n+ 'lat': data[\"latitude\"],\n+ 'lon': data[\"longitude\"],\n+ 'phone': data[\"phone\"],\n+ 'website': response.url,\n+ 'brand': re.search(r'www.(\\w+)', response.url)[1],\n+ }\n \n yield GeojsonPointItem(**properties)\n", "issue": "Spider signet_jewelers is broken\nDuring the global build at 2021-07-14-14-42-22, spider **signet_jewelers** failed with **2353 features** and **6 errors**.\n\nHere's [the log](https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/logs/signet_jewelers.txt) and [the output](https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/output/signet_jewelers.geojson) ([on a map](https://data.alltheplaces.xyz/map.html?show=https://data.alltheplaces.xyz/runs/2021-07-14-14-42-22/output/signet_jewelers.geojson))\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nimport json\nimport re\n\nimport scrapy\n\nfrom locations.items import GeojsonPointItem\nfrom locations.hours import OpeningHours\n\n\nclass SignetJewelersSpider(scrapy.Spider):\n name = \"signet_jewelers\"\n allowed_domains = ['www.jared.com', 'www.kay.com', 'www.zales.com', 'www.pagoda.com', 'www.peoplesjewellers.com',\n 'www.ernestjones.co.uk', 'www.hsamuel.co.uk']\n download_delay = 0.5 # limit the delay to avoid 403 errors\n\n ca_prov = ['Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador',\n 'Nova Scotia', 'Ontario', 'Saskatchewan']\n\n states = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\", \"California\", \"Colorado\",\n \"Connecticut\", \"Delaware\", \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\",\n \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\",\n \"Massachusetts\", \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\", \"New York\",\n \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\",\n \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\",\n \"Vermont\", \"Virginia\", \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n ]\n\n def start_requests(self):\n north_america_brands = [\"jared\", \"kay\", \"zales\", \"pagoda\", \"peoplesjewellers\"]\n\n uk_urls = [\n 'https://www.hsamuel.co.uk/scripts/dist/store-locator/functionality/store-details.min.js?sprint-17_20190911.3',\n 'https://www.ernestjones.co.uk/scripts/store-locator/storeLocationDetails.js']\n\n for url in uk_urls:\n yield scrapy.Request(url=url, callback=self.parse_uk)\n\n template = 'https://www.{brand}.com/store-finder/view-stores/{region}'\n\n for brand in north_america_brands:\n if brand == \"peoplesjewellers\":\n for prov in SignetJewelersSpider.ca_prov:\n url = template.format(brand=brand, region=prov)\n yield scrapy.Request(url, callback=self.parse_cities)\n else:\n for state in SignetJewelersSpider.states:\n url = template.format(brand=brand, region=state)\n yield scrapy.Request(url, callback=self.parse_cities)\n\n def parse_cities(self, response):\n cities = response.xpath('//*[@class=\"viewstoreslist\"]/a/@href').extract()\n for i in cities:\n yield scrapy.Request(response.urljoin(i), callback=self.parse)\n\n def parse(self, response):\n script = \" \".join(response.xpath('//*[@id=\"js-store-details\"]/div/script/text()').extract())\n data = re.search(r'storeInformation\\s=\\s((?s).*)', script).groups()[0]\n data = data.replace(\";\", '')\n data = eval(data)\n\n if data[\"region\"] in SignetJewelersSpider.ca_prov:\n country = 'CA'\n else:\n country = 'US'\n\n properties = {\n 'ref': data[\"name\"],\n 'name': data[\"displayName\"],\n 'addr_full': data[\"line1\"],\n 'city': data[\"town\"],\n 'state': data[\"region\"],\n 'postcode': data[\"postalCode\"],\n 'country': country,\n 'lat': data[\"latitude\"],\n 'lon': data[\"longitude\"],\n 'phone': data[\"phone\"],\n 'website': response.url,\n 'brand': re.search(r'www.(\\w+)', response.url)[1],\n }\n\n yield GeojsonPointItem(**properties)\n\n def parse_uk(self, response):\n data = re.search(r'Signet.allStoreDetails=((?s).*)', response.text)[1]\n data = data.replace(';', '')\n data = json.loads(data)\n\n for store in data:\n properties = {\n 'ref': store[\"number\"],\n 'name': store[\"name\"],\n 'addr_full': store[\"addressLine1\"],\n 'city': store[\"town\"],\n 'postcode': store[\"postcode\"],\n 'country': 'GB',\n 'lat': store[\"latitude\"],\n 'lon': store[\"longitude\"],\n 'brand': re.search(r'www.(\\w+)', response.url)[1],\n }\n\n yield GeojsonPointItem(**properties)\n", "path": "locations/spiders/signet_jewelers.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nimport json\nimport re\n\nimport scrapy\n\nfrom locations.items import GeojsonPointItem\nfrom locations.hours import OpeningHours\n\n\nclass SignetJewelersSpider(scrapy.Spider):\n name = \"signet_jewelers\"\n allowed_domains = ['www.jared.com', 'www.kay.com', 'www.zales.com', 'www.pagoda.com', 'www.peoplesjewellers.com',\n 'www.ernestjones.co.uk', 'www.hsamuel.co.uk']\n download_delay = 0.5 # limit the delay to avoid 403 errors\n\n ca_prov = ['Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador',\n 'Nova Scotia', 'Ontario', 'Saskatchewan']\n\n states = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\", \"California\", \"Colorado\",\n \"Connecticut\", \"Delaware\", \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\",\n \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\", \"Maine\", \"Maryland\",\n \"Massachusetts\", \"Michigan\", \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\", \"New Mexico\", \"New York\",\n \"North Carolina\", \"North Dakota\", \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\",\n \"Rhode Island\", \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\", \"Utah\",\n \"Vermont\", \"Virginia\", \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n ]\n\n def start_requests(self):\n north_america_brands = [\"jared\", \"kay\", \"zales\", \"pagoda\", \"peoplesjewellers\"]\n\n uk_urls = [\n 'https://www.hsamuel.co.uk/scripts/dist/store-locator/functionality/store-details.min.js?sprint-17_20190911.3',\n 'https://www.ernestjones.co.uk/scripts/store-locator/storeLocationDetails.js']\n\n for url in uk_urls:\n yield scrapy.Request(url=url, callback=self.parse_uk)\n\n template = 'https://www.{brand}.com/store-finder/view-stores/{region}'\n\n for brand in north_america_brands:\n if brand == \"peoplesjewellers\":\n for prov in SignetJewelersSpider.ca_prov:\n url = template.format(brand=brand, region=prov)\n yield scrapy.Request(url, callback=self.parse_cities)\n else:\n for state in SignetJewelersSpider.states:\n url = template.format(brand=brand, region=state)\n yield scrapy.Request(url, callback=self.parse_cities)\n\n def parse_cities(self, response):\n cities = response.xpath('//*[@class=\"viewstoreslist\"]/a/@href').extract()\n for i in cities:\n yield scrapy.Request(response.urljoin(i), callback=self.parse)\n\n def parse(self, response):\n script = \" \".join(response.xpath('//*[@id=\"js-store-details\"]/div/script/text()').extract())\n data = None\n\n if re.search(r'storeInformation\\s=\\s((?s).*)', script) is not None:\n data = re.search(r'storeInformation\\s=\\s((?s).*)', script).groups()\n\n properties = {}\n\n if data is not None:\n if len(data) > 0:\n data = data[0]\n data = data.replace(\";\", '')\n data = eval(data)\n\n if data[\"region\"] in SignetJewelersSpider.ca_prov:\n country = 'CA'\n else:\n country = 'US'\n\n properties = {\n 'ref': data[\"name\"],\n 'name': data[\"displayName\"],\n 'addr_full': data[\"line1\"],\n 'city': data[\"town\"],\n 'state': data[\"region\"],\n 'postcode': data[\"postalCode\"],\n 'country': country,\n 'lat': data[\"latitude\"],\n 'lon': data[\"longitude\"],\n 'phone': data[\"phone\"],\n 'website': response.url,\n 'brand': re.search(r'www.(\\w+)', response.url)[1],\n }\n\n yield GeojsonPointItem(**properties)\n\n def parse_uk(self, response):\n data = re.search(r'Signet.allStoreDetails=((?s).*)', response.text)[1]\n data = data.replace(';', '')\n data = json.loads(data)\n\n for store in data:\n properties = {\n 'ref': store[\"number\"],\n 'name': store[\"name\"],\n 'addr_full': store[\"addressLine1\"],\n 'city': store[\"town\"],\n 'postcode': store[\"postcode\"],\n 'country': 'GB',\n 'lat': store[\"latitude\"],\n 'lon': store[\"longitude\"],\n 'brand': re.search(r'www.(\\w+)', response.url)[1],\n }\n\n yield GeojsonPointItem(**properties)\n", "path": "locations/spiders/signet_jewelers.py"}]}
1,731
587
gh_patches_debug_37852
rasdani/github-patches
git_diff
akvo__akvo-rsr-5268
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Feature Request: Document the results framework ### What are you trying to do? Understand how the results framework functions ### Describe the solution you'd like A technical documentation of how it works. ### Have you consider alternatives? _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: `akvo/rsr/models/project_hierarchy.py` Content: ``` 1 # -*- coding: utf-8 -*- 2 3 # Akvo RSR is covered by the GNU Affero General Public License. 4 # See more details in the license.txt file located at the root folder of the Akvo RSR module. 5 # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. 6 7 from django.db import models 8 from django.utils.translation import ugettext_lazy as _ 9 10 11 class ProjectHierarchy(models.Model): 12 project_relation = 'projecthierarchy__in' 13 root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True) 14 max_depth = models.PositiveSmallIntegerField() 15 is_master = models.BooleanField(_('is master program'), default=False) 16 17 class Meta: 18 app_label = 'rsr' 19 verbose_name = _('program') 20 verbose_name_plural = _('programs') 21 ordering = ['-id'] 22 23 @property 24 def descendants(self): 25 return self.root_project.descendants(max_depth=self.max_depth) 26 27 @property 28 def project_count(self): 29 return self.descendants.count() - 1 # remove root_project from count 30 31 @property 32 def project_ids(self): 33 return self.descendants.values_list('id', flat=True) 34 35 @property 36 def organisation(self): 37 return self.root_project.reporting_org 38 39 def __str__(self): 40 return self.root_project.title 41 ``` Path: `doc/conf.py` Content: ``` 1 # Configuration file for the Sphinx documentation builder. 2 # 3 # For the full list of built-in configuration values, see the documentation: 4 # https://www.sphinx-doc.org/en/master/usage/configuration.html 5 6 # -- Project information ----------------------------------------------------- 7 # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 8 9 import os 10 import sys 11 import django 12 sys.path.insert(0, os.path.abspath('..')) 13 os.environ['DJANGO_SETTINGS_MODULE'] = 'akvo.settings' 14 django.setup() 15 16 project = 'Akvo RSR' 17 copyright = '2023, Akvo Foundation' 18 author = 'Akvo Foundation' 19 20 # -- General configuration --------------------------------------------------- 21 # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 22 23 extensions = [ 24 'sphinx.ext.autodoc', 25 'sphinx.ext.autosummary', 26 'sphinx.ext.viewcode', 27 'myst_parser', 28 ] 29 30 templates_path = ['_templates'] 31 exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 32 33 34 35 # -- Options for HTML output ------------------------------------------------- 36 # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 37 38 html_theme = 'cloud' 39 html_static_path = ['_static'] 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/akvo/rsr/models/project_hierarchy.py b/akvo/rsr/models/project_hierarchy.py --- a/akvo/rsr/models/project_hierarchy.py +++ b/akvo/rsr/models/project_hierarchy.py @@ -9,10 +9,22 @@ class ProjectHierarchy(models.Model): + """ + The actual "Program" with a project hierarchy. + """ project_relation = 'projecthierarchy__in' + root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True) + """ + The root of the program + It can be used to create subprograms / a program tree + """ + max_depth = models.PositiveSmallIntegerField() + """TODO: It is unclear why this field currently exists""" + is_master = models.BooleanField(_('is master program'), default=False) + """Used when an organisation has one program under which they would like to create subprograms""" class Meta: app_label = 'rsr' @@ -22,10 +34,15 @@ @property def descendants(self): + """ + The entire tree in a list. + No order is guaranteed + """ return self.root_project.descendants(max_depth=self.max_depth) @property def project_count(self): + """The number of children without counting the root project""" return self.descendants.count() - 1 # remove root_project from count @property @@ -34,6 +51,7 @@ @property def organisation(self): + """The reporting organisation of the tree""" return self.root_project.reporting_org def __str__(self): diff --git a/doc/conf.py b/doc/conf.py --- a/doc/conf.py +++ b/doc/conf.py @@ -21,6 +21,7 @@ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [ + 'sphinxcontrib.plantuml', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', @@ -30,7 +31,9 @@ templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - +myst_enable_extensions = [ + "colon_fence", # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#syntax-colon-fence +] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
{"golden_diff": "diff --git a/akvo/rsr/models/project_hierarchy.py b/akvo/rsr/models/project_hierarchy.py\n--- a/akvo/rsr/models/project_hierarchy.py\n+++ b/akvo/rsr/models/project_hierarchy.py\n@@ -9,10 +9,22 @@\n \n \n class ProjectHierarchy(models.Model):\n+ \"\"\"\n+ The actual \"Program\" with a project hierarchy.\n+ \"\"\"\n project_relation = 'projecthierarchy__in'\n+\n root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True)\n+ \"\"\"\n+ The root of the program\n+ It can be used to create subprograms / a program tree\n+ \"\"\"\n+\n max_depth = models.PositiveSmallIntegerField()\n+ \"\"\"TODO: It is unclear why this field currently exists\"\"\"\n+\n is_master = models.BooleanField(_('is master program'), default=False)\n+ \"\"\"Used when an organisation has one program under which they would like to create subprograms\"\"\"\n \n class Meta:\n app_label = 'rsr'\n@@ -22,10 +34,15 @@\n \n @property\n def descendants(self):\n+ \"\"\"\n+ The entire tree in a list.\n+ No order is guaranteed\n+ \"\"\"\n return self.root_project.descendants(max_depth=self.max_depth)\n \n @property\n def project_count(self):\n+ \"\"\"The number of children without counting the root project\"\"\"\n return self.descendants.count() - 1 # remove root_project from count\n \n @property\n@@ -34,6 +51,7 @@\n \n @property\n def organisation(self):\n+ \"\"\"The reporting organisation of the tree\"\"\"\n return self.root_project.reporting_org\n \n def __str__(self):\ndiff --git a/doc/conf.py b/doc/conf.py\n--- a/doc/conf.py\n+++ b/doc/conf.py\n@@ -21,6 +21,7 @@\n # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n \n extensions = [\n+ 'sphinxcontrib.plantuml',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.viewcode',\n@@ -30,7 +31,9 @@\n templates_path = ['_templates']\n exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n \n-\n+myst_enable_extensions = [\n+ \"colon_fence\", # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#syntax-colon-fence\n+]\n \n # -- Options for HTML output -------------------------------------------------\n # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n", "issue": "Feature Request: Document the results framework\n### What are you trying to do?\n\nUnderstand how the results framework functions\n\n### Describe the solution you'd like\n\nA technical documentation of how it works.\n\n### Have you consider alternatives?\n\n_No response_\n\n### Additional context\n\n_No response_\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass ProjectHierarchy(models.Model):\n project_relation = 'projecthierarchy__in'\n root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True)\n max_depth = models.PositiveSmallIntegerField()\n is_master = models.BooleanField(_('is master program'), default=False)\n\n class Meta:\n app_label = 'rsr'\n verbose_name = _('program')\n verbose_name_plural = _('programs')\n ordering = ['-id']\n\n @property\n def descendants(self):\n return self.root_project.descendants(max_depth=self.max_depth)\n\n @property\n def project_count(self):\n return self.descendants.count() - 1 # remove root_project from count\n\n @property\n def project_ids(self):\n return self.descendants.values_list('id', flat=True)\n\n @property\n def organisation(self):\n return self.root_project.reporting_org\n\n def __str__(self):\n return self.root_project.title\n", "path": "akvo/rsr/models/project_hierarchy.py"}, {"content": "# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nimport os\nimport sys\nimport django\nsys.path.insert(0, os.path.abspath('..'))\nos.environ['DJANGO_SETTINGS_MODULE'] = 'akvo.settings'\ndjango.setup()\n\nproject = 'Akvo RSR'\ncopyright = '2023, Akvo Foundation'\nauthor = 'Akvo Foundation'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.viewcode',\n 'myst_parser',\n]\n\ntemplates_path = ['_templates']\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'cloud'\nhtml_static_path = ['_static']\n", "path": "doc/conf.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Akvo RSR is covered by the GNU Affero General Public License.\n# See more details in the license.txt file located at the root folder of the Akvo RSR module.\n# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass ProjectHierarchy(models.Model):\n \"\"\"\n The actual \"Program\" with a project hierarchy.\n \"\"\"\n project_relation = 'projecthierarchy__in'\n\n root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True)\n \"\"\"\n The root of the program\n It can be used to create subprograms / a program tree\n \"\"\"\n\n max_depth = models.PositiveSmallIntegerField()\n \"\"\"TODO: It is unclear why this field currently exists\"\"\"\n\n is_master = models.BooleanField(_('is master program'), default=False)\n \"\"\"Used when an organisation has one program under which they would like to create subprograms\"\"\"\n\n class Meta:\n app_label = 'rsr'\n verbose_name = _('program')\n verbose_name_plural = _('programs')\n ordering = ['-id']\n\n @property\n def descendants(self):\n \"\"\"\n The entire tree in a list.\n No order is guaranteed\n \"\"\"\n return self.root_project.descendants(max_depth=self.max_depth)\n\n @property\n def project_count(self):\n \"\"\"The number of children without counting the root project\"\"\"\n return self.descendants.count() - 1 # remove root_project from count\n\n @property\n def project_ids(self):\n return self.descendants.values_list('id', flat=True)\n\n @property\n def organisation(self):\n \"\"\"The reporting organisation of the tree\"\"\"\n return self.root_project.reporting_org\n\n def __str__(self):\n return self.root_project.title\n", "path": "akvo/rsr/models/project_hierarchy.py"}, {"content": "# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nimport os\nimport sys\nimport django\nsys.path.insert(0, os.path.abspath('..'))\nos.environ['DJANGO_SETTINGS_MODULE'] = 'akvo.settings'\ndjango.setup()\n\nproject = 'Akvo RSR'\ncopyright = '2023, Akvo Foundation'\nauthor = 'Akvo Foundation'\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n 'sphinxcontrib.plantuml',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.viewcode',\n 'myst_parser',\n]\n\ntemplates_path = ['_templates']\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\nmyst_enable_extensions = [\n \"colon_fence\", # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#syntax-colon-fence\n]\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = 'cloud'\nhtml_static_path = ['_static']\n", "path": "doc/conf.py"}]}
1,031
569
gh_patches_debug_32277
rasdani/github-patches
git_diff
weni-ai__bothub-engine-78
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Is possible translate example to same language --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `bothub/api/serializers/translate.py` Content: ``` 1 from rest_framework import serializers 2 3 from django.utils.translation import gettext as _ 4 5 from bothub.common.models import RepositoryTranslatedExampleEntity 6 from bothub.common.models import RepositoryTranslatedExample 7 from bothub.common.models import RepositoryExample 8 9 from ..validators import CanContributeInRepositoryTranslatedExampleValidator 10 from ..validators import CanContributeInRepositoryExampleValidator 11 from ..validators import TranslatedExampleEntitiesValidator 12 13 14 class RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer): 15 class Meta: 16 model = RepositoryTranslatedExampleEntity 17 fields = [ 18 'id', 19 'repository_translated_example', 20 'start', 21 'end', 22 'entity', 23 'created_at', 24 'value', 25 ] 26 27 repository_translated_example = serializers.PrimaryKeyRelatedField( 28 queryset=RepositoryTranslatedExample.objects, 29 validators=[ 30 CanContributeInRepositoryTranslatedExampleValidator(), 31 ], 32 help_text='Example translation ID') 33 value = serializers.SerializerMethodField() 34 35 def get_value(self, obj): 36 return obj.value 37 38 39 class RepositoryTranslatedExampleSerializer(serializers.ModelSerializer): 40 class Meta: 41 model = RepositoryTranslatedExample 42 fields = [ 43 'id', 44 'original_example', 45 'from_language', 46 'language', 47 'text', 48 'has_valid_entities', 49 'entities', 50 'created_at', 51 ] 52 53 original_example = serializers.PrimaryKeyRelatedField( 54 queryset=RepositoryExample.objects, 55 validators=[ 56 CanContributeInRepositoryExampleValidator(), 57 ], 58 help_text=_('Example\'s ID')) 59 from_language = serializers.SerializerMethodField() 60 has_valid_entities = serializers.SerializerMethodField() 61 entities = RepositoryTranslatedExampleEntitySeralizer( 62 many=True, 63 read_only=True) 64 65 def get_from_language(self, obj): 66 return obj.original_example.repository_update.language 67 68 def get_has_valid_entities(self, obj): 69 return obj.has_valid_entities 70 71 72 class NewRepositoryTranslatedExampleEntitySeralizer( 73 serializers.ModelSerializer): 74 class Meta: 75 model = RepositoryTranslatedExampleEntity 76 fields = [ 77 'start', 78 'end', 79 'entity', 80 ] 81 82 83 class NewRepositoryTranslatedExampleSerializer(serializers.ModelSerializer): 84 class Meta: 85 model = RepositoryTranslatedExample 86 fields = [ 87 'id', 88 'original_example', 89 'language', 90 'text', 91 'has_valid_entities', 92 'entities', 93 ] 94 95 def __init__(self, *args, **kwargs): 96 super().__init__(*args, **kwargs) 97 self.validators.append(TranslatedExampleEntitiesValidator()) 98 99 original_example = serializers.PrimaryKeyRelatedField( 100 queryset=RepositoryExample.objects, 101 validators=[ 102 CanContributeInRepositoryExampleValidator(), 103 ], 104 help_text=_('Example\'s ID')) 105 has_valid_entities = serializers.SerializerMethodField() 106 entities = NewRepositoryTranslatedExampleEntitySeralizer( 107 many=True, 108 style={'text_field': 'text'}) 109 110 def get_has_valid_entities(self, obj): 111 return obj.has_valid_entities 112 113 def create(self, validated_data): 114 entities_data = validated_data.pop('entities') 115 116 translated = self.Meta.model.objects.create(**validated_data) 117 for entity_data in entities_data: 118 RepositoryTranslatedExampleEntity.objects.create( 119 repository_translated_example=translated, 120 **entity_data) 121 return translated 122 ``` Path: `bothub/api/validators.py` Content: ``` 1 from django.utils.translation import gettext as _ 2 from rest_framework.exceptions import PermissionDenied 3 from rest_framework.exceptions import ValidationError 4 5 from bothub.common.models import RepositoryTranslatedExample 6 7 8 class CanContributeInRepositoryValidator(object): 9 def __call__(self, value): 10 user_authorization = value.get_user_authorization( 11 self.request.user) 12 if not user_authorization.can_contribute: 13 raise PermissionDenied( 14 _('You can\'t contribute in this repository')) 15 16 def set_context(self, serializer): 17 self.request = serializer.context.get('request') 18 19 20 class CanContributeInRepositoryExampleValidator(object): 21 def __call__(self, value): 22 repository = value.repository_update.repository 23 user_authorization = repository.get_user_authorization( 24 self.request.user) 25 if not user_authorization.can_contribute: 26 raise PermissionDenied( 27 _('You can\'t contribute in this repository')) 28 29 def set_context(self, serializer): 30 self.request = serializer.context.get('request') 31 32 33 class CanContributeInRepositoryTranslatedExampleValidator(object): 34 def __call__(self, value): 35 repository = value.original_example.repository_update.repository 36 user_authorization = repository.get_user_authorization( 37 self.request.user) 38 if not user_authorization.can_contribute: 39 raise PermissionDenied( 40 _('You can\'t contribute in this repository')) 41 42 def set_context(self, serializer): 43 self.request = serializer.context.get('request') 44 45 46 class TranslatedExampleEntitiesValidator(object): 47 def __call__(self, attrs): 48 original_example = attrs.get('original_example') 49 entities_valid = RepositoryTranslatedExample.same_entities_validator( 50 list(map(lambda x: dict(x), attrs.get('entities'))), 51 list(map(lambda x: x.to_dict, original_example.entities.all()))) 52 if not entities_valid: 53 raise ValidationError({'entities': _('Invalid entities')}) 54 ``` Path: `setup.py` Content: ``` 1 from setuptools import setup, find_packages 2 3 with open('requirements.txt') as fp: 4 install_requires = fp.read() 5 install_requires = list( 6 filter(lambda x: len(x) > 0, install_requires.split('\n'))) 7 8 setup( 9 name='bothub', 10 version='1.7.2', 11 description='bothub', 12 packages=find_packages(), 13 install_requires=install_requires, 14 python_requires='>=3.6', 15 ) 16 ``` --- 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/bothub/api/serializers/translate.py b/bothub/api/serializers/translate.py --- a/bothub/api/serializers/translate.py +++ b/bothub/api/serializers/translate.py @@ -9,6 +9,7 @@ from ..validators import CanContributeInRepositoryTranslatedExampleValidator from ..validators import CanContributeInRepositoryExampleValidator from ..validators import TranslatedExampleEntitiesValidator +from ..validators import TranslatedExampleLanguageValidator class RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer): @@ -95,6 +96,7 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.validators.append(TranslatedExampleEntitiesValidator()) + self.validators.append(TranslatedExampleLanguageValidator()) original_example = serializers.PrimaryKeyRelatedField( queryset=RepositoryExample.objects, diff --git a/bothub/api/validators.py b/bothub/api/validators.py --- a/bothub/api/validators.py +++ b/bothub/api/validators.py @@ -51,3 +51,11 @@ list(map(lambda x: x.to_dict, original_example.entities.all()))) if not entities_valid: raise ValidationError({'entities': _('Invalid entities')}) + + +class TranslatedExampleLanguageValidator(object): + def __call__(self, attrs): + original_example = attrs.get('original_example') + language = attrs.get('language') + if original_example.repository_update.language == language: + raise ValidationError({'language': _('Can\'t translate to same language')}) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -7,7 +7,7 @@ setup( name='bothub', - version='1.7.2', + version='1.7.3', description='bothub', packages=find_packages(), install_requires=install_requires,
{"golden_diff": "diff --git a/bothub/api/serializers/translate.py b/bothub/api/serializers/translate.py\n--- a/bothub/api/serializers/translate.py\n+++ b/bothub/api/serializers/translate.py\n@@ -9,6 +9,7 @@\n from ..validators import CanContributeInRepositoryTranslatedExampleValidator\n from ..validators import CanContributeInRepositoryExampleValidator\n from ..validators import TranslatedExampleEntitiesValidator\n+from ..validators import TranslatedExampleLanguageValidator\n \n \n class RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer):\n@@ -95,6 +96,7 @@\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validators.append(TranslatedExampleEntitiesValidator())\n+ self.validators.append(TranslatedExampleLanguageValidator())\n \n original_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryExample.objects,\ndiff --git a/bothub/api/validators.py b/bothub/api/validators.py\n--- a/bothub/api/validators.py\n+++ b/bothub/api/validators.py\n@@ -51,3 +51,11 @@\n list(map(lambda x: x.to_dict, original_example.entities.all())))\n if not entities_valid:\n raise ValidationError({'entities': _('Invalid entities')})\n+\n+\n+class TranslatedExampleLanguageValidator(object):\n+ def __call__(self, attrs):\n+ original_example = attrs.get('original_example')\n+ language = attrs.get('language')\n+ if original_example.repository_update.language == language:\n+ raise ValidationError({'language': _('Can\\'t translate to same language')})\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -7,7 +7,7 @@\n \n setup(\n name='bothub',\n- version='1.7.2',\n+ version='1.7.3',\n description='bothub',\n packages=find_packages(),\n install_requires=install_requires,\n", "issue": "Is possible translate example to same language\n\n", "before_files": [{"content": "from rest_framework import serializers\n\nfrom django.utils.translation import gettext as _\n\nfrom bothub.common.models import RepositoryTranslatedExampleEntity\nfrom bothub.common.models import RepositoryTranslatedExample\nfrom bothub.common.models import RepositoryExample\n\nfrom ..validators import CanContributeInRepositoryTranslatedExampleValidator\nfrom ..validators import CanContributeInRepositoryExampleValidator\nfrom ..validators import TranslatedExampleEntitiesValidator\n\n\nclass RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExampleEntity\n fields = [\n 'id',\n 'repository_translated_example',\n 'start',\n 'end',\n 'entity',\n 'created_at',\n 'value',\n ]\n\n repository_translated_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryTranslatedExample.objects,\n validators=[\n CanContributeInRepositoryTranslatedExampleValidator(),\n ],\n help_text='Example translation ID')\n value = serializers.SerializerMethodField()\n\n def get_value(self, obj):\n return obj.value\n\n\nclass RepositoryTranslatedExampleSerializer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExample\n fields = [\n 'id',\n 'original_example',\n 'from_language',\n 'language',\n 'text',\n 'has_valid_entities',\n 'entities',\n 'created_at',\n ]\n\n original_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryExample.objects,\n validators=[\n CanContributeInRepositoryExampleValidator(),\n ],\n help_text=_('Example\\'s ID'))\n from_language = serializers.SerializerMethodField()\n has_valid_entities = serializers.SerializerMethodField()\n entities = RepositoryTranslatedExampleEntitySeralizer(\n many=True,\n read_only=True)\n\n def get_from_language(self, obj):\n return obj.original_example.repository_update.language\n\n def get_has_valid_entities(self, obj):\n return obj.has_valid_entities\n\n\nclass NewRepositoryTranslatedExampleEntitySeralizer(\n serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExampleEntity\n fields = [\n 'start',\n 'end',\n 'entity',\n ]\n\n\nclass NewRepositoryTranslatedExampleSerializer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExample\n fields = [\n 'id',\n 'original_example',\n 'language',\n 'text',\n 'has_valid_entities',\n 'entities',\n ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validators.append(TranslatedExampleEntitiesValidator())\n\n original_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryExample.objects,\n validators=[\n CanContributeInRepositoryExampleValidator(),\n ],\n help_text=_('Example\\'s ID'))\n has_valid_entities = serializers.SerializerMethodField()\n entities = NewRepositoryTranslatedExampleEntitySeralizer(\n many=True,\n style={'text_field': 'text'})\n\n def get_has_valid_entities(self, obj):\n return obj.has_valid_entities\n\n def create(self, validated_data):\n entities_data = validated_data.pop('entities')\n\n translated = self.Meta.model.objects.create(**validated_data)\n for entity_data in entities_data:\n RepositoryTranslatedExampleEntity.objects.create(\n repository_translated_example=translated,\n **entity_data)\n return translated\n", "path": "bothub/api/serializers/translate.py"}, {"content": "from django.utils.translation import gettext as _\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.exceptions import ValidationError\n\nfrom bothub.common.models import RepositoryTranslatedExample\n\n\nclass CanContributeInRepositoryValidator(object):\n def __call__(self, value):\n user_authorization = value.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass CanContributeInRepositoryExampleValidator(object):\n def __call__(self, value):\n repository = value.repository_update.repository\n user_authorization = repository.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass CanContributeInRepositoryTranslatedExampleValidator(object):\n def __call__(self, value):\n repository = value.original_example.repository_update.repository\n user_authorization = repository.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass TranslatedExampleEntitiesValidator(object):\n def __call__(self, attrs):\n original_example = attrs.get('original_example')\n entities_valid = RepositoryTranslatedExample.same_entities_validator(\n list(map(lambda x: dict(x), attrs.get('entities'))),\n list(map(lambda x: x.to_dict, original_example.entities.all())))\n if not entities_valid:\n raise ValidationError({'entities': _('Invalid entities')})\n", "path": "bothub/api/validators.py"}, {"content": "from setuptools import setup, find_packages\n\nwith open('requirements.txt') as fp:\n install_requires = fp.read()\ninstall_requires = list(\n filter(lambda x: len(x) > 0, install_requires.split('\\n')))\n\nsetup(\n name='bothub',\n version='1.7.2',\n description='bothub',\n packages=find_packages(),\n install_requires=install_requires,\n python_requires='>=3.6',\n)\n", "path": "setup.py"}], "after_files": [{"content": "from rest_framework import serializers\n\nfrom django.utils.translation import gettext as _\n\nfrom bothub.common.models import RepositoryTranslatedExampleEntity\nfrom bothub.common.models import RepositoryTranslatedExample\nfrom bothub.common.models import RepositoryExample\n\nfrom ..validators import CanContributeInRepositoryTranslatedExampleValidator\nfrom ..validators import CanContributeInRepositoryExampleValidator\nfrom ..validators import TranslatedExampleEntitiesValidator\nfrom ..validators import TranslatedExampleLanguageValidator\n\n\nclass RepositoryTranslatedExampleEntitySeralizer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExampleEntity\n fields = [\n 'id',\n 'repository_translated_example',\n 'start',\n 'end',\n 'entity',\n 'created_at',\n 'value',\n ]\n\n repository_translated_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryTranslatedExample.objects,\n validators=[\n CanContributeInRepositoryTranslatedExampleValidator(),\n ],\n help_text='Example translation ID')\n value = serializers.SerializerMethodField()\n\n def get_value(self, obj):\n return obj.value\n\n\nclass RepositoryTranslatedExampleSerializer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExample\n fields = [\n 'id',\n 'original_example',\n 'from_language',\n 'language',\n 'text',\n 'has_valid_entities',\n 'entities',\n 'created_at',\n ]\n\n original_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryExample.objects,\n validators=[\n CanContributeInRepositoryExampleValidator(),\n ],\n help_text=_('Example\\'s ID'))\n from_language = serializers.SerializerMethodField()\n has_valid_entities = serializers.SerializerMethodField()\n entities = RepositoryTranslatedExampleEntitySeralizer(\n many=True,\n read_only=True)\n\n def get_from_language(self, obj):\n return obj.original_example.repository_update.language\n\n def get_has_valid_entities(self, obj):\n return obj.has_valid_entities\n\n\nclass NewRepositoryTranslatedExampleEntitySeralizer(\n serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExampleEntity\n fields = [\n 'start',\n 'end',\n 'entity',\n ]\n\n\nclass NewRepositoryTranslatedExampleSerializer(serializers.ModelSerializer):\n class Meta:\n model = RepositoryTranslatedExample\n fields = [\n 'id',\n 'original_example',\n 'language',\n 'text',\n 'has_valid_entities',\n 'entities',\n ]\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validators.append(TranslatedExampleEntitiesValidator())\n self.validators.append(TranslatedExampleLanguageValidator())\n\n original_example = serializers.PrimaryKeyRelatedField(\n queryset=RepositoryExample.objects,\n validators=[\n CanContributeInRepositoryExampleValidator(),\n ],\n help_text=_('Example\\'s ID'))\n has_valid_entities = serializers.SerializerMethodField()\n entities = NewRepositoryTranslatedExampleEntitySeralizer(\n many=True,\n style={'text_field': 'text'})\n\n def get_has_valid_entities(self, obj):\n return obj.has_valid_entities\n\n def create(self, validated_data):\n entities_data = validated_data.pop('entities')\n\n translated = self.Meta.model.objects.create(**validated_data)\n for entity_data in entities_data:\n RepositoryTranslatedExampleEntity.objects.create(\n repository_translated_example=translated,\n **entity_data)\n return translated\n", "path": "bothub/api/serializers/translate.py"}, {"content": "from django.utils.translation import gettext as _\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.exceptions import ValidationError\n\nfrom bothub.common.models import RepositoryTranslatedExample\n\n\nclass CanContributeInRepositoryValidator(object):\n def __call__(self, value):\n user_authorization = value.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass CanContributeInRepositoryExampleValidator(object):\n def __call__(self, value):\n repository = value.repository_update.repository\n user_authorization = repository.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass CanContributeInRepositoryTranslatedExampleValidator(object):\n def __call__(self, value):\n repository = value.original_example.repository_update.repository\n user_authorization = repository.get_user_authorization(\n self.request.user)\n if not user_authorization.can_contribute:\n raise PermissionDenied(\n _('You can\\'t contribute in this repository'))\n\n def set_context(self, serializer):\n self.request = serializer.context.get('request')\n\n\nclass TranslatedExampleEntitiesValidator(object):\n def __call__(self, attrs):\n original_example = attrs.get('original_example')\n entities_valid = RepositoryTranslatedExample.same_entities_validator(\n list(map(lambda x: dict(x), attrs.get('entities'))),\n list(map(lambda x: x.to_dict, original_example.entities.all())))\n if not entities_valid:\n raise ValidationError({'entities': _('Invalid entities')})\n\n\nclass TranslatedExampleLanguageValidator(object):\n def __call__(self, attrs):\n original_example = attrs.get('original_example')\n language = attrs.get('language')\n if original_example.repository_update.language == language:\n raise ValidationError({'language': _('Can\\'t translate to same language')})\n", "path": "bothub/api/validators.py"}, {"content": "from setuptools import setup, find_packages\n\nwith open('requirements.txt') as fp:\n install_requires = fp.read()\ninstall_requires = list(\n filter(lambda x: len(x) > 0, install_requires.split('\\n')))\n\nsetup(\n name='bothub',\n version='1.7.3',\n description='bothub',\n packages=find_packages(),\n install_requires=install_requires,\n python_requires='>=3.6',\n)\n", "path": "setup.py"}]}
1,843
424
gh_patches_debug_16402
rasdani/github-patches
git_diff
fonttools__fonttools-717
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- hmtx code should round values Currently, float values result in exception: ``` self._writeTable(masterTable, writer, done) File "/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/__init__.py", line 648, in _writeTable tabledata = self.getTableData(tag) File "/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/__init__.py", line 659, in getTableData return self.tables[tag].compile(self) File "/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/tables/_h_m_t_x.py", line 68, in compile allMetrics = array.array("h", allMetrics) TypeError: integer argument expected, got float ``` Possibly warn? Though it will become annoying if we do. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `Lib/fontTools/ttLib/tables/_h_m_t_x.py` Content: ``` 1 from __future__ import print_function, division, absolute_import 2 from fontTools.misc.py23 import * 3 from fontTools import ttLib 4 from fontTools.misc.textTools import safeEval 5 from . import DefaultTable 6 import sys 7 import struct 8 import array 9 import logging 10 11 12 log = logging.getLogger(__name__) 13 14 15 class table__h_m_t_x(DefaultTable.DefaultTable): 16 17 headerTag = 'hhea' 18 advanceName = 'width' 19 sideBearingName = 'lsb' 20 numberOfMetricsName = 'numberOfHMetrics' 21 longMetricFormat = 'Hh' 22 23 def decompile(self, data, ttFont): 24 numGlyphs = ttFont['maxp'].numGlyphs 25 numberOfMetrics = int(getattr(ttFont[self.headerTag], self.numberOfMetricsName)) 26 if numberOfMetrics > numGlyphs: 27 log.warning("The %s.%s exceeds the maxp.numGlyphs" % ( 28 self.headerTag, self.numberOfMetricsName)) 29 numberOfMetrics = numGlyphs 30 if len(data) < 4 * numberOfMetrics: 31 raise ttLib.TTLibError("not enough '%s' table data" % self.tableTag) 32 # Note: advanceWidth is unsigned, but some font editors might 33 # read/write as signed. We can't be sure whether it was a mistake 34 # or not, so we read as unsigned but also issue a warning... 35 metricsFmt = ">" + self.longMetricFormat * numberOfMetrics 36 metrics = struct.unpack(metricsFmt, data[:4 * numberOfMetrics]) 37 data = data[4 * numberOfMetrics:] 38 numberOfSideBearings = numGlyphs - numberOfMetrics 39 sideBearings = array.array("h", data[:2 * numberOfSideBearings]) 40 data = data[2 * numberOfSideBearings:] 41 42 if sys.byteorder != "big": 43 sideBearings.byteswap() 44 if data: 45 log.warning("too much '%s' table data" % self.tableTag) 46 self.metrics = {} 47 glyphOrder = ttFont.getGlyphOrder() 48 for i in range(numberOfMetrics): 49 glyphName = glyphOrder[i] 50 advanceWidth, lsb = metrics[i*2:i*2+2] 51 if advanceWidth > 32767: 52 log.warning( 53 "Glyph %r has a huge advance %s (%d); is it intentional or " 54 "an (invalid) negative value?", glyphName, self.advanceName, 55 advanceWidth) 56 self.metrics[glyphName] = (advanceWidth, lsb) 57 lastAdvance = metrics[-2] 58 for i in range(numberOfSideBearings): 59 glyphName = glyphOrder[i + numberOfMetrics] 60 self.metrics[glyphName] = (lastAdvance, sideBearings[i]) 61 62 def compile(self, ttFont): 63 metrics = [] 64 hasNegativeAdvances = False 65 for glyphName in ttFont.getGlyphOrder(): 66 advanceWidth, sideBearing = self.metrics[glyphName] 67 if advanceWidth < 0: 68 log.error("Glyph %r has negative advance %s" % ( 69 glyphName, self.advanceName)) 70 hasNegativeAdvances = True 71 metrics.append([advanceWidth, sideBearing]) 72 lastAdvance = metrics[-1][0] 73 lastIndex = len(metrics) 74 while metrics[lastIndex-2][0] == lastAdvance: 75 lastIndex -= 1 76 if lastIndex <= 1: 77 # all advances are equal 78 lastIndex = 1 79 break 80 additionalMetrics = metrics[lastIndex:] 81 additionalMetrics = [sb for advance, sb in additionalMetrics] 82 metrics = metrics[:lastIndex] 83 numberOfMetrics = len(metrics) 84 setattr(ttFont[self.headerTag], self.numberOfMetricsName, numberOfMetrics) 85 86 allMetrics = [] 87 for item in metrics: 88 allMetrics.extend(item) 89 metricsFmt = ">" + self.longMetricFormat * numberOfMetrics 90 try: 91 data = struct.pack(metricsFmt, *allMetrics) 92 except struct.error as e: 93 if "out of range" in str(e) and hasNegativeAdvances: 94 raise ttLib.TTLibError( 95 "'%s' table can't contain negative advance %ss" 96 % (self.tableTag, self.advanceName)) 97 else: 98 raise 99 additionalMetrics = array.array("h", additionalMetrics) 100 if sys.byteorder != "big": 101 additionalMetrics.byteswap() 102 data = data + additionalMetrics.tostring() 103 return data 104 105 def toXML(self, writer, ttFont): 106 names = sorted(self.metrics.keys()) 107 for glyphName in names: 108 advance, sb = self.metrics[glyphName] 109 writer.simpletag("mtx", [ 110 ("name", glyphName), 111 (self.advanceName, advance), 112 (self.sideBearingName, sb), 113 ]) 114 writer.newline() 115 116 def fromXML(self, name, attrs, content, ttFont): 117 if not hasattr(self, "metrics"): 118 self.metrics = {} 119 if name == "mtx": 120 self.metrics[attrs["name"]] = (safeEval(attrs[self.advanceName]), 121 safeEval(attrs[self.sideBearingName])) 122 123 def __delitem__(self, glyphName): 124 del self.metrics[glyphName] 125 126 def __getitem__(self, glyphName): 127 return self.metrics[glyphName] 128 129 def __setitem__(self, glyphName, advance_sb_pair): 130 self.metrics[glyphName] = tuple(advance_sb_pair) 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/Lib/fontTools/ttLib/tables/_h_m_t_x.py b/Lib/fontTools/ttLib/tables/_h_m_t_x.py --- a/Lib/fontTools/ttLib/tables/_h_m_t_x.py +++ b/Lib/fontTools/ttLib/tables/_h_m_t_x.py @@ -78,14 +78,14 @@ lastIndex = 1 break additionalMetrics = metrics[lastIndex:] - additionalMetrics = [sb for advance, sb in additionalMetrics] + additionalMetrics = [int(round(sb)) for _, sb in additionalMetrics] metrics = metrics[:lastIndex] numberOfMetrics = len(metrics) setattr(ttFont[self.headerTag], self.numberOfMetricsName, numberOfMetrics) allMetrics = [] - for item in metrics: - allMetrics.extend(item) + for advance, sb in metrics: + allMetrics.extend([int(round(advance)), int(round(sb))]) metricsFmt = ">" + self.longMetricFormat * numberOfMetrics try: data = struct.pack(metricsFmt, *allMetrics)
{"golden_diff": "diff --git a/Lib/fontTools/ttLib/tables/_h_m_t_x.py b/Lib/fontTools/ttLib/tables/_h_m_t_x.py\n--- a/Lib/fontTools/ttLib/tables/_h_m_t_x.py\n+++ b/Lib/fontTools/ttLib/tables/_h_m_t_x.py\n@@ -78,14 +78,14 @@\n \t\t\t\tlastIndex = 1\n \t\t\t\tbreak\n \t\tadditionalMetrics = metrics[lastIndex:]\n-\t\tadditionalMetrics = [sb for advance, sb in additionalMetrics]\n+\t\tadditionalMetrics = [int(round(sb)) for _, sb in additionalMetrics]\n \t\tmetrics = metrics[:lastIndex]\n \t\tnumberOfMetrics = len(metrics)\n \t\tsetattr(ttFont[self.headerTag], self.numberOfMetricsName, numberOfMetrics)\n \n \t\tallMetrics = []\n-\t\tfor item in metrics:\n-\t\t\tallMetrics.extend(item)\n+\t\tfor advance, sb in metrics:\n+\t\t\tallMetrics.extend([int(round(advance)), int(round(sb))])\n \t\tmetricsFmt = \">\" + self.longMetricFormat * numberOfMetrics\n \t\ttry:\n \t\t\tdata = struct.pack(metricsFmt, *allMetrics)\n", "issue": "hmtx code should round values\nCurrently, float values result in exception:\n\n```\n self._writeTable(masterTable, writer, done)\n File \"/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/__init__.py\", line 648, in _writeTable\n tabledata = self.getTableData(tag)\n File \"/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/__init__.py\", line 659, in getTableData\n return self.tables[tag].compile(self)\n File \"/usr/local/lib/python2.7/dist-packages/fonttools-3.0-py2.7.egg/fontTools/ttLib/tables/_h_m_t_x.py\", line 68, in compile\n allMetrics = array.array(\"h\", allMetrics)\nTypeError: integer argument expected, got float\n```\n\nPossibly warn? Though it will become annoying if we do.\n\n", "before_files": [{"content": "from __future__ import print_function, division, absolute_import\nfrom fontTools.misc.py23 import *\nfrom fontTools import ttLib\nfrom fontTools.misc.textTools import safeEval\nfrom . import DefaultTable\nimport sys\nimport struct\nimport array\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nclass table__h_m_t_x(DefaultTable.DefaultTable):\n\n\theaderTag = 'hhea'\n\tadvanceName = 'width'\n\tsideBearingName = 'lsb'\n\tnumberOfMetricsName = 'numberOfHMetrics'\n\tlongMetricFormat = 'Hh'\n\n\tdef decompile(self, data, ttFont):\n\t\tnumGlyphs = ttFont['maxp'].numGlyphs\n\t\tnumberOfMetrics = int(getattr(ttFont[self.headerTag], self.numberOfMetricsName))\n\t\tif numberOfMetrics > numGlyphs:\n\t\t\tlog.warning(\"The %s.%s exceeds the maxp.numGlyphs\" % (\n\t\t\t\tself.headerTag, self.numberOfMetricsName))\n\t\t\tnumberOfMetrics = numGlyphs\n\t\tif len(data) < 4 * numberOfMetrics:\n\t\t\traise ttLib.TTLibError(\"not enough '%s' table data\" % self.tableTag)\n\t\t# Note: advanceWidth is unsigned, but some font editors might\n\t\t# read/write as signed. We can't be sure whether it was a mistake\n\t\t# or not, so we read as unsigned but also issue a warning...\n\t\tmetricsFmt = \">\" + self.longMetricFormat * numberOfMetrics\n\t\tmetrics = struct.unpack(metricsFmt, data[:4 * numberOfMetrics])\n\t\tdata = data[4 * numberOfMetrics:]\n\t\tnumberOfSideBearings = numGlyphs - numberOfMetrics\n\t\tsideBearings = array.array(\"h\", data[:2 * numberOfSideBearings])\n\t\tdata = data[2 * numberOfSideBearings:]\n\n\t\tif sys.byteorder != \"big\":\n\t\t\tsideBearings.byteswap()\n\t\tif data:\n\t\t\tlog.warning(\"too much '%s' table data\" % self.tableTag)\n\t\tself.metrics = {}\n\t\tglyphOrder = ttFont.getGlyphOrder()\n\t\tfor i in range(numberOfMetrics):\n\t\t\tglyphName = glyphOrder[i]\n\t\t\tadvanceWidth, lsb = metrics[i*2:i*2+2]\n\t\t\tif advanceWidth > 32767:\n\t\t\t\tlog.warning(\n\t\t\t\t\t\"Glyph %r has a huge advance %s (%d); is it intentional or \"\n\t\t\t\t\t\"an (invalid) negative value?\", glyphName, self.advanceName,\n\t\t\t\t\tadvanceWidth)\n\t\t\tself.metrics[glyphName] = (advanceWidth, lsb)\n\t\tlastAdvance = metrics[-2]\n\t\tfor i in range(numberOfSideBearings):\n\t\t\tglyphName = glyphOrder[i + numberOfMetrics]\n\t\t\tself.metrics[glyphName] = (lastAdvance, sideBearings[i])\n\n\tdef compile(self, ttFont):\n\t\tmetrics = []\n\t\thasNegativeAdvances = False\n\t\tfor glyphName in ttFont.getGlyphOrder():\n\t\t\tadvanceWidth, sideBearing = self.metrics[glyphName]\n\t\t\tif advanceWidth < 0:\n\t\t\t\tlog.error(\"Glyph %r has negative advance %s\" % (\n\t\t\t\t\tglyphName, self.advanceName))\n\t\t\t\thasNegativeAdvances = True\n\t\t\tmetrics.append([advanceWidth, sideBearing])\n\t\tlastAdvance = metrics[-1][0]\n\t\tlastIndex = len(metrics)\n\t\twhile metrics[lastIndex-2][0] == lastAdvance:\n\t\t\tlastIndex -= 1\n\t\t\tif lastIndex <= 1:\n\t\t\t\t# all advances are equal\n\t\t\t\tlastIndex = 1\n\t\t\t\tbreak\n\t\tadditionalMetrics = metrics[lastIndex:]\n\t\tadditionalMetrics = [sb for advance, sb in additionalMetrics]\n\t\tmetrics = metrics[:lastIndex]\n\t\tnumberOfMetrics = len(metrics)\n\t\tsetattr(ttFont[self.headerTag], self.numberOfMetricsName, numberOfMetrics)\n\n\t\tallMetrics = []\n\t\tfor item in metrics:\n\t\t\tallMetrics.extend(item)\n\t\tmetricsFmt = \">\" + self.longMetricFormat * numberOfMetrics\n\t\ttry:\n\t\t\tdata = struct.pack(metricsFmt, *allMetrics)\n\t\texcept struct.error as e:\n\t\t\tif \"out of range\" in str(e) and hasNegativeAdvances:\n\t\t\t\traise ttLib.TTLibError(\n\t\t\t\t\t\"'%s' table can't contain negative advance %ss\"\n\t\t\t\t\t% (self.tableTag, self.advanceName))\n\t\t\telse:\n\t\t\t\traise\n\t\tadditionalMetrics = array.array(\"h\", additionalMetrics)\n\t\tif sys.byteorder != \"big\":\n\t\t\tadditionalMetrics.byteswap()\n\t\tdata = data + additionalMetrics.tostring()\n\t\treturn data\n\n\tdef toXML(self, writer, ttFont):\n\t\tnames = sorted(self.metrics.keys())\n\t\tfor glyphName in names:\n\t\t\tadvance, sb = self.metrics[glyphName]\n\t\t\twriter.simpletag(\"mtx\", [\n\t\t\t\t\t(\"name\", glyphName),\n\t\t\t\t\t(self.advanceName, advance),\n\t\t\t\t\t(self.sideBearingName, sb),\n\t\t\t\t\t])\n\t\t\twriter.newline()\n\n\tdef fromXML(self, name, attrs, content, ttFont):\n\t\tif not hasattr(self, \"metrics\"):\n\t\t\tself.metrics = {}\n\t\tif name == \"mtx\":\n\t\t\tself.metrics[attrs[\"name\"]] = (safeEval(attrs[self.advanceName]),\n\t\t\t\t\tsafeEval(attrs[self.sideBearingName]))\n\n\tdef __delitem__(self, glyphName):\n\t\tdel self.metrics[glyphName]\n\n\tdef __getitem__(self, glyphName):\n\t\treturn self.metrics[glyphName]\n\n\tdef __setitem__(self, glyphName, advance_sb_pair):\n\t\tself.metrics[glyphName] = tuple(advance_sb_pair)\n", "path": "Lib/fontTools/ttLib/tables/_h_m_t_x.py"}], "after_files": [{"content": "from __future__ import print_function, division, absolute_import\nfrom fontTools.misc.py23 import *\nfrom fontTools import ttLib\nfrom fontTools.misc.textTools import safeEval\nfrom . import DefaultTable\nimport sys\nimport struct\nimport array\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nclass table__h_m_t_x(DefaultTable.DefaultTable):\n\n\theaderTag = 'hhea'\n\tadvanceName = 'width'\n\tsideBearingName = 'lsb'\n\tnumberOfMetricsName = 'numberOfHMetrics'\n\tlongMetricFormat = 'Hh'\n\n\tdef decompile(self, data, ttFont):\n\t\tnumGlyphs = ttFont['maxp'].numGlyphs\n\t\tnumberOfMetrics = int(getattr(ttFont[self.headerTag], self.numberOfMetricsName))\n\t\tif numberOfMetrics > numGlyphs:\n\t\t\tlog.warning(\"The %s.%s exceeds the maxp.numGlyphs\" % (\n\t\t\t\tself.headerTag, self.numberOfMetricsName))\n\t\t\tnumberOfMetrics = numGlyphs\n\t\tif len(data) < 4 * numberOfMetrics:\n\t\t\traise ttLib.TTLibError(\"not enough '%s' table data\" % self.tableTag)\n\t\t# Note: advanceWidth is unsigned, but some font editors might\n\t\t# read/write as signed. We can't be sure whether it was a mistake\n\t\t# or not, so we read as unsigned but also issue a warning...\n\t\tmetricsFmt = \">\" + self.longMetricFormat * numberOfMetrics\n\t\tmetrics = struct.unpack(metricsFmt, data[:4 * numberOfMetrics])\n\t\tdata = data[4 * numberOfMetrics:]\n\t\tnumberOfSideBearings = numGlyphs - numberOfMetrics\n\t\tsideBearings = array.array(\"h\", data[:2 * numberOfSideBearings])\n\t\tdata = data[2 * numberOfSideBearings:]\n\n\t\tif sys.byteorder != \"big\":\n\t\t\tsideBearings.byteswap()\n\t\tif data:\n\t\t\tlog.warning(\"too much '%s' table data\" % self.tableTag)\n\t\tself.metrics = {}\n\t\tglyphOrder = ttFont.getGlyphOrder()\n\t\tfor i in range(numberOfMetrics):\n\t\t\tglyphName = glyphOrder[i]\n\t\t\tadvanceWidth, lsb = metrics[i*2:i*2+2]\n\t\t\tif advanceWidth > 32767:\n\t\t\t\tlog.warning(\n\t\t\t\t\t\"Glyph %r has a huge advance %s (%d); is it intentional or \"\n\t\t\t\t\t\"an (invalid) negative value?\", glyphName, self.advanceName,\n\t\t\t\t\tadvanceWidth)\n\t\t\tself.metrics[glyphName] = (advanceWidth, lsb)\n\t\tlastAdvance = metrics[-2]\n\t\tfor i in range(numberOfSideBearings):\n\t\t\tglyphName = glyphOrder[i + numberOfMetrics]\n\t\t\tself.metrics[glyphName] = (lastAdvance, sideBearings[i])\n\n\tdef compile(self, ttFont):\n\t\tmetrics = []\n\t\thasNegativeAdvances = False\n\t\tfor glyphName in ttFont.getGlyphOrder():\n\t\t\tadvanceWidth, sideBearing = self.metrics[glyphName]\n\t\t\tif advanceWidth < 0:\n\t\t\t\tlog.error(\"Glyph %r has negative advance %s\" % (\n\t\t\t\t\tglyphName, self.advanceName))\n\t\t\t\thasNegativeAdvances = True\n\t\t\tmetrics.append([advanceWidth, sideBearing])\n\t\tlastAdvance = metrics[-1][0]\n\t\tlastIndex = len(metrics)\n\t\twhile metrics[lastIndex-2][0] == lastAdvance:\n\t\t\tlastIndex -= 1\n\t\t\tif lastIndex <= 1:\n\t\t\t\t# all advances are equal\n\t\t\t\tlastIndex = 1\n\t\t\t\tbreak\n\t\tadditionalMetrics = metrics[lastIndex:]\n\t\tadditionalMetrics = [int(round(sb)) for _, sb in additionalMetrics]\n\t\tmetrics = metrics[:lastIndex]\n\t\tnumberOfMetrics = len(metrics)\n\t\tsetattr(ttFont[self.headerTag], self.numberOfMetricsName, numberOfMetrics)\n\n\t\tallMetrics = []\n\t\tfor advance, sb in metrics:\n\t\t\tallMetrics.extend([int(round(advance)), int(round(sb))])\n\t\tmetricsFmt = \">\" + self.longMetricFormat * numberOfMetrics\n\t\ttry:\n\t\t\tdata = struct.pack(metricsFmt, *allMetrics)\n\t\texcept struct.error as e:\n\t\t\tif \"out of range\" in str(e) and hasNegativeAdvances:\n\t\t\t\traise ttLib.TTLibError(\n\t\t\t\t\t\"'%s' table can't contain negative advance %ss\"\n\t\t\t\t\t% (self.tableTag, self.advanceName))\n\t\t\telse:\n\t\t\t\traise\n\t\tadditionalMetrics = array.array(\"h\", additionalMetrics)\n\t\tif sys.byteorder != \"big\":\n\t\t\tadditionalMetrics.byteswap()\n\t\tdata = data + additionalMetrics.tostring()\n\t\treturn data\n\n\tdef toXML(self, writer, ttFont):\n\t\tnames = sorted(self.metrics.keys())\n\t\tfor glyphName in names:\n\t\t\tadvance, sb = self.metrics[glyphName]\n\t\t\twriter.simpletag(\"mtx\", [\n\t\t\t\t\t(\"name\", glyphName),\n\t\t\t\t\t(self.advanceName, advance),\n\t\t\t\t\t(self.sideBearingName, sb),\n\t\t\t\t\t])\n\t\t\twriter.newline()\n\n\tdef fromXML(self, name, attrs, content, ttFont):\n\t\tif not hasattr(self, \"metrics\"):\n\t\t\tself.metrics = {}\n\t\tif name == \"mtx\":\n\t\t\tself.metrics[attrs[\"name\"]] = (safeEval(attrs[self.advanceName]),\n\t\t\t\t\tsafeEval(attrs[self.sideBearingName]))\n\n\tdef __delitem__(self, glyphName):\n\t\tdel self.metrics[glyphName]\n\n\tdef __getitem__(self, glyphName):\n\t\treturn self.metrics[glyphName]\n\n\tdef __setitem__(self, glyphName, advance_sb_pair):\n\t\tself.metrics[glyphName] = tuple(advance_sb_pair)\n", "path": "Lib/fontTools/ttLib/tables/_h_m_t_x.py"}]}
1,972
248
gh_patches_debug_5813
rasdani/github-patches
git_diff
saleor__saleor-2087
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Missing variable in "fulfillment" email Two small issues in the "fulfillment" email: - logo is missing - in footer there is missing template variable I've just tested it and this is how the email looks like: ![image](https://user-images.githubusercontent.com/5421321/38736166-7bd21386-3f2b-11e8-99e0-65459f62602a.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: `saleor/order/emails.py` Content: ``` 1 from celery import shared_task 2 from django.conf import settings 3 from django.contrib.sites.models import Site 4 from django.urls import reverse 5 from templated_email import send_templated_mail 6 7 from ..core.utils import build_absolute_uri 8 from ..seo.schema.email import get_order_confirmation_markup 9 from .models import Fulfillment, Order 10 11 CONFIRM_ORDER_TEMPLATE = 'source/order/confirm_order' 12 CONFIRM_FULFILLMENT_TEMPLATE = 'source/order/confirm_fulfillment' 13 UPDATE_FULFILLMENT_TEMPLATE = 'source/order/update_fulfillment' 14 CONFIRM_PAYMENT_TEMPLATE = 'source/order/payment/confirm_payment' 15 CONFIRM_NOTE_TEMPLATE = 'source/order/note/confirm_note' 16 17 18 def get_email_context(order_token): 19 """Prepares context required for email template rendering.""" 20 site = Site.objects.get_current() 21 order_url = build_absolute_uri( 22 reverse('order:details', kwargs={'token': order_token})) 23 ctx = { 24 'protocol': 'https' if settings.ENABLE_SSL else 'http', 25 'site_name': site.name, 26 'domain': site.domain, 27 'url': order_url} 28 return ctx 29 30 31 def collect_data_for_email(order_pk, template): 32 """Collects data required for email sending. 33 34 Args: 35 order_pk (int): order primary key 36 template (str): email template path 37 """ 38 order = Order.objects.get(pk=order_pk) 39 recipient_email = order.get_user_current_email() 40 email_context = get_email_context(order.token) 41 42 # Order confirmation template requires additional information 43 if template == CONFIRM_ORDER_TEMPLATE: 44 email_markup = get_order_confirmation_markup(order) 45 email_context.update( 46 {'order': order, 'schema_markup': email_markup}) 47 48 return { 49 'recipient_list': [recipient_email], 'template_name': template, 50 'context': email_context, 'from_email': settings.ORDER_FROM_EMAIL} 51 52 53 def collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk): 54 fulfillment = Fulfillment.objects.get(pk=fulfillment_pk) 55 email_data = collect_data_for_email(order_pk, template) 56 email_data.update({'context': {'fulfillment': fulfillment}}) 57 return email_data 58 59 60 @shared_task 61 def send_order_confirmation(order_pk): 62 """Sends order confirmation email.""" 63 email_data = collect_data_for_email(order_pk, CONFIRM_ORDER_TEMPLATE) 64 send_templated_mail(**email_data) 65 66 67 @shared_task 68 def send_fulfillment_confirmation(order_pk, fulfillment_pk): 69 email_data = collect_data_for_fullfillment_email( 70 order_pk, CONFIRM_FULFILLMENT_TEMPLATE, fulfillment_pk) 71 send_templated_mail(**email_data) 72 73 74 @shared_task 75 def send_fulfillment_update(order_pk, fulfillment_pk): 76 email_data = collect_data_for_fullfillment_email( 77 order_pk, UPDATE_FULFILLMENT_TEMPLATE, fulfillment_pk) 78 send_templated_mail(**email_data) 79 80 81 @shared_task 82 def send_payment_confirmation(order_pk): 83 """Sends payment confirmation email.""" 84 email_data = collect_data_for_email(order_pk, CONFIRM_PAYMENT_TEMPLATE) 85 send_templated_mail(**email_data) 86 87 88 @shared_task 89 def send_note_confirmation(order_pk): 90 """Notifies customer, when new note was added to an order.""" 91 email_data = collect_data_for_email(order_pk, CONFIRM_NOTE_TEMPLATE) 92 send_templated_mail(**email_data) 93 ``` --- 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/saleor/order/emails.py b/saleor/order/emails.py --- a/saleor/order/emails.py +++ b/saleor/order/emails.py @@ -53,7 +53,7 @@ def collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk): fulfillment = Fulfillment.objects.get(pk=fulfillment_pk) email_data = collect_data_for_email(order_pk, template) - email_data.update({'context': {'fulfillment': fulfillment}}) + email_data['context'].update({'fulfillment': fulfillment}) return email_data
{"golden_diff": "diff --git a/saleor/order/emails.py b/saleor/order/emails.py\n--- a/saleor/order/emails.py\n+++ b/saleor/order/emails.py\n@@ -53,7 +53,7 @@\n def collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk):\n fulfillment = Fulfillment.objects.get(pk=fulfillment_pk)\n email_data = collect_data_for_email(order_pk, template)\n- email_data.update({'context': {'fulfillment': fulfillment}})\n+ email_data['context'].update({'fulfillment': fulfillment})\n return email_data\n", "issue": "Missing variable in \"fulfillment\" email\nTwo small issues in the \"fulfillment\" email:\r\n- logo is missing\r\n- in footer there is missing template variable\r\n\r\nI've just tested it and this is how the email looks like:\r\n\r\n![image](https://user-images.githubusercontent.com/5421321/38736166-7bd21386-3f2b-11e8-99e0-65459f62602a.png)\r\n\n", "before_files": [{"content": "from celery import shared_task\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.urls import reverse\nfrom templated_email import send_templated_mail\n\nfrom ..core.utils import build_absolute_uri\nfrom ..seo.schema.email import get_order_confirmation_markup\nfrom .models import Fulfillment, Order\n\nCONFIRM_ORDER_TEMPLATE = 'source/order/confirm_order'\nCONFIRM_FULFILLMENT_TEMPLATE = 'source/order/confirm_fulfillment'\nUPDATE_FULFILLMENT_TEMPLATE = 'source/order/update_fulfillment'\nCONFIRM_PAYMENT_TEMPLATE = 'source/order/payment/confirm_payment'\nCONFIRM_NOTE_TEMPLATE = 'source/order/note/confirm_note'\n\n\ndef get_email_context(order_token):\n \"\"\"Prepares context required for email template rendering.\"\"\"\n site = Site.objects.get_current()\n order_url = build_absolute_uri(\n reverse('order:details', kwargs={'token': order_token}))\n ctx = {\n 'protocol': 'https' if settings.ENABLE_SSL else 'http',\n 'site_name': site.name,\n 'domain': site.domain,\n 'url': order_url}\n return ctx\n\n\ndef collect_data_for_email(order_pk, template):\n \"\"\"Collects data required for email sending.\n\n Args:\n order_pk (int): order primary key\n template (str): email template path\n \"\"\"\n order = Order.objects.get(pk=order_pk)\n recipient_email = order.get_user_current_email()\n email_context = get_email_context(order.token)\n\n # Order confirmation template requires additional information\n if template == CONFIRM_ORDER_TEMPLATE:\n email_markup = get_order_confirmation_markup(order)\n email_context.update(\n {'order': order, 'schema_markup': email_markup})\n\n return {\n 'recipient_list': [recipient_email], 'template_name': template,\n 'context': email_context, 'from_email': settings.ORDER_FROM_EMAIL}\n\n\ndef collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk):\n fulfillment = Fulfillment.objects.get(pk=fulfillment_pk)\n email_data = collect_data_for_email(order_pk, template)\n email_data.update({'context': {'fulfillment': fulfillment}})\n return email_data\n\n\n@shared_task\ndef send_order_confirmation(order_pk):\n \"\"\"Sends order confirmation email.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_ORDER_TEMPLATE)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_fulfillment_confirmation(order_pk, fulfillment_pk):\n email_data = collect_data_for_fullfillment_email(\n order_pk, CONFIRM_FULFILLMENT_TEMPLATE, fulfillment_pk)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_fulfillment_update(order_pk, fulfillment_pk):\n email_data = collect_data_for_fullfillment_email(\n order_pk, UPDATE_FULFILLMENT_TEMPLATE, fulfillment_pk)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_payment_confirmation(order_pk):\n \"\"\"Sends payment confirmation email.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_PAYMENT_TEMPLATE)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_note_confirmation(order_pk):\n \"\"\"Notifies customer, when new note was added to an order.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_NOTE_TEMPLATE)\n send_templated_mail(**email_data)\n", "path": "saleor/order/emails.py"}], "after_files": [{"content": "from celery import shared_task\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.urls import reverse\nfrom templated_email import send_templated_mail\n\nfrom ..core.utils import build_absolute_uri\nfrom ..seo.schema.email import get_order_confirmation_markup\nfrom .models import Fulfillment, Order\n\nCONFIRM_ORDER_TEMPLATE = 'source/order/confirm_order'\nCONFIRM_FULFILLMENT_TEMPLATE = 'source/order/confirm_fulfillment'\nUPDATE_FULFILLMENT_TEMPLATE = 'source/order/update_fulfillment'\nCONFIRM_PAYMENT_TEMPLATE = 'source/order/payment/confirm_payment'\nCONFIRM_NOTE_TEMPLATE = 'source/order/note/confirm_note'\n\n\ndef get_email_context(order_token):\n \"\"\"Prepares context required for email template rendering.\"\"\"\n site = Site.objects.get_current()\n order_url = build_absolute_uri(\n reverse('order:details', kwargs={'token': order_token}))\n ctx = {\n 'protocol': 'https' if settings.ENABLE_SSL else 'http',\n 'site_name': site.name,\n 'domain': site.domain,\n 'url': order_url}\n return ctx\n\n\ndef collect_data_for_email(order_pk, template):\n \"\"\"Collects data required for email sending.\n\n Args:\n order_pk (int): order primary key\n template (str): email template path\n \"\"\"\n order = Order.objects.get(pk=order_pk)\n recipient_email = order.get_user_current_email()\n email_context = get_email_context(order.token)\n\n # Order confirmation template requires additional information\n if template == CONFIRM_ORDER_TEMPLATE:\n email_markup = get_order_confirmation_markup(order)\n email_context.update(\n {'order': order, 'schema_markup': email_markup})\n\n return {\n 'recipient_list': [recipient_email], 'template_name': template,\n 'context': email_context, 'from_email': settings.ORDER_FROM_EMAIL}\n\n\ndef collect_data_for_fullfillment_email(order_pk, template, fulfillment_pk):\n fulfillment = Fulfillment.objects.get(pk=fulfillment_pk)\n email_data = collect_data_for_email(order_pk, template)\n email_data['context'].update({'fulfillment': fulfillment})\n return email_data\n\n\n@shared_task\ndef send_order_confirmation(order_pk):\n \"\"\"Sends order confirmation email.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_ORDER_TEMPLATE)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_fulfillment_confirmation(order_pk, fulfillment_pk):\n email_data = collect_data_for_fullfillment_email(\n order_pk, CONFIRM_FULFILLMENT_TEMPLATE, fulfillment_pk)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_fulfillment_update(order_pk, fulfillment_pk):\n email_data = collect_data_for_fullfillment_email(\n order_pk, UPDATE_FULFILLMENT_TEMPLATE, fulfillment_pk)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_payment_confirmation(order_pk):\n \"\"\"Sends payment confirmation email.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_PAYMENT_TEMPLATE)\n send_templated_mail(**email_data)\n\n\n@shared_task\ndef send_note_confirmation(order_pk):\n \"\"\"Notifies customer, when new note was added to an order.\"\"\"\n email_data = collect_data_for_email(order_pk, CONFIRM_NOTE_TEMPLATE)\n send_templated_mail(**email_data)\n", "path": "saleor/order/emails.py"}]}
1,277
131
gh_patches_debug_728
rasdani/github-patches
git_diff
speechbrain__speechbrain-1504
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Torch 1.12 not compatible? working to install speechbrain 0.5.12, and getting the error that "speechbrain 0.5.12 requires torch<=1.11,>=1.7, but you have torch 1.12.0 which is incompatible." read elsewhere that it should work with >=1.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: `setup.py` Content: ``` 1 #!/usr/bin/env python3 2 import os 3 import sys 4 import site 5 import setuptools 6 from distutils.core import setup 7 8 9 # Editable install in user site directory can be allowed with this hack: 10 # https://github.com/pypa/pip/issues/7953. 11 site.ENABLE_USER_SITE = "--user" in sys.argv[1:] 12 13 with open("README.md") as f: 14 long_description = f.read() 15 16 with open(os.path.join("speechbrain", "version.txt")) as f: 17 version = f.read().strip() 18 19 setup( 20 name="speechbrain", 21 version=version, 22 description="All-in-one speech toolkit in pure Python and Pytorch", 23 long_description=long_description, 24 long_description_content_type="text/markdown", 25 author="Mirco Ravanelli & Others", 26 author_email="[email protected]", 27 classifiers=[ 28 "Programming Language :: Python :: 3", 29 "License :: OSI Approved :: Apache Software License", 30 ], 31 packages=setuptools.find_packages(), 32 package_data={"speechbrain": ["version.txt", "log-config.yaml"]}, 33 install_requires=[ 34 "hyperpyyaml", 35 "joblib", 36 "numpy", 37 "packaging", 38 "scipy", 39 "sentencepiece", 40 "torch>=1.7,<=1.11", 41 "torchaudio", 42 "tqdm", 43 "huggingface_hub", 44 ], 45 python_requires=">=3.7", 46 url="https://speechbrain.github.io/", 47 ) 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/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ "packaging", "scipy", "sentencepiece", - "torch>=1.7,<=1.11", + "torch>=1.9", "torchaudio", "tqdm", "huggingface_hub",
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -37,7 +37,7 @@\n \"packaging\",\n \"scipy\",\n \"sentencepiece\",\n- \"torch>=1.7,<=1.11\",\n+ \"torch>=1.9\",\n \"torchaudio\",\n \"tqdm\",\n \"huggingface_hub\",\n", "issue": "Torch 1.12 not compatible?\nworking to install speechbrain 0.5.12, and getting the error that \"speechbrain 0.5.12 requires torch<=1.11,>=1.7, but you have torch 1.12.0 which is incompatible.\" read elsewhere that it should work with >=1.7. \n", "before_files": [{"content": "#!/usr/bin/env python3\nimport os\nimport sys\nimport site\nimport setuptools\nfrom distutils.core import setup\n\n\n# Editable install in user site directory can be allowed with this hack:\n# https://github.com/pypa/pip/issues/7953.\nsite.ENABLE_USER_SITE = \"--user\" in sys.argv[1:]\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\nwith open(os.path.join(\"speechbrain\", \"version.txt\")) as f:\n version = f.read().strip()\n\nsetup(\n name=\"speechbrain\",\n version=version,\n description=\"All-in-one speech toolkit in pure Python and Pytorch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Mirco Ravanelli & Others\",\n author_email=\"[email protected]\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n packages=setuptools.find_packages(),\n package_data={\"speechbrain\": [\"version.txt\", \"log-config.yaml\"]},\n install_requires=[\n \"hyperpyyaml\",\n \"joblib\",\n \"numpy\",\n \"packaging\",\n \"scipy\",\n \"sentencepiece\",\n \"torch>=1.7,<=1.11\",\n \"torchaudio\",\n \"tqdm\",\n \"huggingface_hub\",\n ],\n python_requires=\">=3.7\",\n url=\"https://speechbrain.github.io/\",\n)\n", "path": "setup.py"}], "after_files": [{"content": "#!/usr/bin/env python3\nimport os\nimport sys\nimport site\nimport setuptools\nfrom distutils.core import setup\n\n\n# Editable install in user site directory can be allowed with this hack:\n# https://github.com/pypa/pip/issues/7953.\nsite.ENABLE_USER_SITE = \"--user\" in sys.argv[1:]\n\nwith open(\"README.md\") as f:\n long_description = f.read()\n\nwith open(os.path.join(\"speechbrain\", \"version.txt\")) as f:\n version = f.read().strip()\n\nsetup(\n name=\"speechbrain\",\n version=version,\n description=\"All-in-one speech toolkit in pure Python and Pytorch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Mirco Ravanelli & Others\",\n author_email=\"[email protected]\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n packages=setuptools.find_packages(),\n package_data={\"speechbrain\": [\"version.txt\", \"log-config.yaml\"]},\n install_requires=[\n \"hyperpyyaml\",\n \"joblib\",\n \"numpy\",\n \"packaging\",\n \"scipy\",\n \"sentencepiece\",\n \"torch>=1.9\",\n \"torchaudio\",\n \"tqdm\",\n \"huggingface_hub\",\n ],\n python_requires=\">=3.7\",\n url=\"https://speechbrain.github.io/\",\n)\n", "path": "setup.py"}]}
745
90
gh_patches_debug_18013
rasdani/github-patches
git_diff
lk-geimfari__mimesis-446
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- romanized decorator mutates ROMANIZATION_DICT After `@romanized` is used, ROMANIZATION_DICT gets updated and every module importing it will get this mutated ROMANIZATION_DICT. Snippet below should reproduce problem. ``` from mimesis import decorators, data if __name__ == '__main__': print('ROMANIZATION_DICT: before') print(data.ROMANIZATION_DICT) @decorators.romanized('ru') def russian_name(): return 'Петр Петрович' # next line is where ROMANIZATION_DICT mutates russian_name() print('ROMANIZATION_DICT: after') print(data.ROMANIZATION_DICT) ``` Problem is here: https://github.com/lk-geimfari/mimesis/blob/master/mimesis/decorators.py#L29 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `mimesis/decorators.py` Content: ``` 1 """Decorators for the public API and for internal purpose.""" 2 3 import functools 4 from string import ascii_letters as letters 5 from string import digits, punctuation 6 from typing import Callable 7 8 from mimesis import data 9 from mimesis.exceptions import UnsupportedLocale 10 11 12 def romanized(locale: str = '') -> Callable: 13 """Romanize the Cyrillic text. 14 15 Transliterate the Cyrillic language from the Cyrillic 16 script into the Latin alphabet. 17 18 .. note:: At this moment it works only for `ru`, `uk`, `kk`. 19 20 :param locale: Locale code. 21 :return: Latinized text. 22 """ 23 def romanized_deco(func): 24 @functools.wraps(func) 25 def wrapper(*args, **kwargs): 26 try: 27 alphabet = data.ROMANIZATION_DICT[locale] 28 # Add common cyrillic common letters 29 alphabet.update(data.COMMON_LETTERS) 30 # String can contain ascii symbols, digits and 31 # punctuation symbols. 32 alphabet.update({s: s for s in 33 letters + digits + punctuation}) 34 except KeyError: 35 raise UnsupportedLocale(locale) 36 result = func(*args, **kwargs) 37 txt = ''.join([alphabet[i] for i in result if i in alphabet]) 38 return txt 39 40 return wrapper 41 42 return romanized_deco 43 ``` --- 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/mimesis/decorators.py b/mimesis/decorators.py --- a/mimesis/decorators.py +++ b/mimesis/decorators.py @@ -24,13 +24,13 @@ @functools.wraps(func) def wrapper(*args, **kwargs): try: - alphabet = data.ROMANIZATION_DICT[locale] - # Add common cyrillic common letters - alphabet.update(data.COMMON_LETTERS) # String can contain ascii symbols, digits and # punctuation symbols. - alphabet.update({s: s for s in - letters + digits + punctuation}) + alphabet = {s: s for s in + letters + digits + punctuation} + alphabet.update(data.ROMANIZATION_DICT[locale]) + # Add common cyrillic letters + alphabet.update(data.COMMON_LETTERS) except KeyError: raise UnsupportedLocale(locale) result = func(*args, **kwargs)
{"golden_diff": "diff --git a/mimesis/decorators.py b/mimesis/decorators.py\n--- a/mimesis/decorators.py\n+++ b/mimesis/decorators.py\n@@ -24,13 +24,13 @@\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n- alphabet = data.ROMANIZATION_DICT[locale]\n- # Add common cyrillic common letters\n- alphabet.update(data.COMMON_LETTERS)\n # String can contain ascii symbols, digits and\n # punctuation symbols.\n- alphabet.update({s: s for s in\n- letters + digits + punctuation})\n+ alphabet = {s: s for s in\n+ letters + digits + punctuation}\n+ alphabet.update(data.ROMANIZATION_DICT[locale])\n+ # Add common cyrillic letters\n+ alphabet.update(data.COMMON_LETTERS)\n except KeyError:\n raise UnsupportedLocale(locale)\n result = func(*args, **kwargs)\n", "issue": "romanized decorator mutates ROMANIZATION_DICT\nAfter `@romanized` is used, ROMANIZATION_DICT gets updated and every module importing it will get this mutated ROMANIZATION_DICT.\r\nSnippet below should reproduce problem.\r\n```\r\nfrom mimesis import decorators, data\r\n\r\n\r\nif __name__ == '__main__':\r\n print('ROMANIZATION_DICT: before')\r\n print(data.ROMANIZATION_DICT)\r\n\r\n @decorators.romanized('ru')\r\n def russian_name(): return '\u041f\u0435\u0442\u0440 \u041f\u0435\u0442\u0440\u043e\u0432\u0438\u0447'\r\n # next line is where ROMANIZATION_DICT mutates\r\n russian_name()\r\n\r\n print('ROMANIZATION_DICT: after')\r\n print(data.ROMANIZATION_DICT)\r\n```\r\nProblem is here:\r\nhttps://github.com/lk-geimfari/mimesis/blob/master/mimesis/decorators.py#L29\r\n\n", "before_files": [{"content": "\"\"\"Decorators for the public API and for internal purpose.\"\"\"\n\nimport functools\nfrom string import ascii_letters as letters\nfrom string import digits, punctuation\nfrom typing import Callable\n\nfrom mimesis import data\nfrom mimesis.exceptions import UnsupportedLocale\n\n\ndef romanized(locale: str = '') -> Callable:\n \"\"\"Romanize the Cyrillic text.\n\n Transliterate the Cyrillic language from the Cyrillic\n script into the Latin alphabet.\n\n .. note:: At this moment it works only for `ru`, `uk`, `kk`.\n\n :param locale: Locale code.\n :return: Latinized text.\n \"\"\"\n def romanized_deco(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n alphabet = data.ROMANIZATION_DICT[locale]\n # Add common cyrillic common letters\n alphabet.update(data.COMMON_LETTERS)\n # String can contain ascii symbols, digits and\n # punctuation symbols.\n alphabet.update({s: s for s in\n letters + digits + punctuation})\n except KeyError:\n raise UnsupportedLocale(locale)\n result = func(*args, **kwargs)\n txt = ''.join([alphabet[i] for i in result if i in alphabet])\n return txt\n\n return wrapper\n\n return romanized_deco\n", "path": "mimesis/decorators.py"}], "after_files": [{"content": "\"\"\"Decorators for the public API and for internal purpose.\"\"\"\n\nimport functools\nfrom string import ascii_letters as letters\nfrom string import digits, punctuation\nfrom typing import Callable\n\nfrom mimesis import data\nfrom mimesis.exceptions import UnsupportedLocale\n\n\ndef romanized(locale: str = '') -> Callable:\n \"\"\"Romanize the Cyrillic text.\n\n Transliterate the Cyrillic language from the Cyrillic\n script into the Latin alphabet.\n\n .. note:: At this moment it works only for `ru`, `uk`, `kk`.\n\n :param locale: Locale code.\n :return: Latinized text.\n \"\"\"\n def romanized_deco(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n try:\n # String can contain ascii symbols, digits and\n # punctuation symbols.\n alphabet = {s: s for s in\n letters + digits + punctuation}\n alphabet.update(data.ROMANIZATION_DICT[locale])\n # Add common cyrillic letters\n alphabet.update(data.COMMON_LETTERS)\n except KeyError:\n raise UnsupportedLocale(locale)\n result = func(*args, **kwargs)\n txt = ''.join([alphabet[i] for i in result if i in alphabet])\n return txt\n\n return wrapper\n\n return romanized_deco\n", "path": "mimesis/decorators.py"}]}
800
220
gh_patches_debug_26944
rasdani/github-patches
git_diff
Qiskit__qiskit-12321
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add insert_barrier argument to UnitaryOverlap ### What should we add? This argument would insert a barrier between the two unitaries. This is useful if you want to prevent circuit optimization between the two parts. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `qiskit/circuit/library/overlap.py` Content: ``` 1 # This code is part of Qiskit. 2 # 3 # (C) Copyright IBM 2023. 4 # 5 # This code is licensed under the Apache License, Version 2.0. You may 6 # obtain a copy of this license in the LICENSE.txt file in the root directory 7 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 8 # 9 # Any modifications or derivative works of this code must retain this 10 # copyright notice, and modified files need to carry a notice indicating 11 # that they have been altered from the originals. 12 13 """Unitary overlap circuit.""" 14 15 from qiskit.circuit import QuantumCircuit, Gate 16 from qiskit.circuit.parametervector import ParameterVector 17 from qiskit.circuit.exceptions import CircuitError 18 from qiskit.circuit import Barrier 19 20 21 class UnitaryOverlap(QuantumCircuit): 22 r"""Circuit that returns the overlap between two unitaries :math:`U_2^{\dag} U_1`. 23 24 The input quantum circuits must represent unitary operations, since they must be invertible. 25 If the inputs will have parameters, they are replaced by :class:`.ParameterVector`\s with 26 names `"p1"` (for circuit ``unitary1``) and `"p2"` (for circuit ``unitary_2``) in the output 27 circuit. 28 29 This circuit is usually employed in computing the fidelity: 30 31 .. math:: 32 33 \left|\langle 0| U_2^{\dag} U_1|0\rangle\right|^{2} 34 35 by computing the probability of being in the all-zeros bit-string, or equivalently, 36 the expectation value of projector :math:`|0\rangle\langle 0|`. 37 38 Example:: 39 40 import numpy as np 41 from qiskit.circuit.library import EfficientSU2, UnitaryOverlap 42 from qiskit.primitives import Sampler 43 44 # get two circuit to prepare states of which we comput the overlap 45 circuit = EfficientSU2(2, reps=1) 46 unitary1 = circuit.assign_parameters(np.random.random(circuit.num_parameters)) 47 unitary2 = circuit.assign_parameters(np.random.random(circuit.num_parameters)) 48 49 # create the overlap circuit 50 overlap = UnitaryOverap(unitary1, unitary2) 51 52 # sample from the overlap 53 sampler = Sampler(options={"shots": 100}) 54 result = sampler.run(overlap).result() 55 56 # the fidelity is the probability to measure 0 57 fidelity = result.quasi_dists[0].get(0, 0) 58 59 """ 60 61 def __init__( 62 self, unitary1: QuantumCircuit, unitary2: QuantumCircuit, prefix1="p1", prefix2="p2" 63 ): 64 """ 65 Args: 66 unitary1: Unitary acting on the ket vector. 67 unitary2: Unitary whose inverse operates on the bra vector. 68 prefix1: The name of the parameter vector associated to ``unitary1``, 69 if it is parameterized. Defaults to ``"p1"``. 70 prefix2: The name of the parameter vector associated to ``unitary2``, 71 if it is parameterized. Defaults to ``"p2"``. 72 73 Raises: 74 CircuitError: Number of qubits in ``unitary1`` and ``unitary2`` does not match. 75 CircuitError: Inputs contain measurements and/or resets. 76 """ 77 # check inputs are valid 78 if unitary1.num_qubits != unitary2.num_qubits: 79 raise CircuitError( 80 f"Number of qubits in unitaries does " 81 f"not match: {unitary1.num_qubits} != {unitary2.num_qubits}." 82 ) 83 84 unitaries = [unitary1, unitary2] 85 for unitary in unitaries: 86 _check_unitary(unitary) 87 88 # Vectors of new parameters, if any. Need the unitaries in a list here to ensure 89 # we can overwrite them. 90 for i, prefix in enumerate([prefix1, prefix2]): 91 if unitaries[i].num_parameters > 0: 92 new_params = ParameterVector(prefix, unitaries[i].num_parameters) 93 unitaries[i] = unitaries[i].assign_parameters(new_params) 94 95 # Generate the actual overlap circuit 96 super().__init__(unitaries[0].num_qubits, name="UnitaryOverlap") 97 self.compose(unitaries[0], inplace=True) 98 self.compose(unitaries[1].inverse(), inplace=True) 99 100 101 def _check_unitary(circuit): 102 """Check a circuit is unitary by checking if all operations are of type ``Gate``.""" 103 104 for instruction in circuit.data: 105 if not isinstance(instruction.operation, (Gate, Barrier)): 106 raise CircuitError( 107 ( 108 "One or more instructions cannot be converted to" 109 ' a gate. "{}" is not a gate instruction' 110 ).format(instruction.operation.name) 111 ) 112 ``` --- 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/qiskit/circuit/library/overlap.py b/qiskit/circuit/library/overlap.py --- a/qiskit/circuit/library/overlap.py +++ b/qiskit/circuit/library/overlap.py @@ -59,7 +59,12 @@ """ def __init__( - self, unitary1: QuantumCircuit, unitary2: QuantumCircuit, prefix1="p1", prefix2="p2" + self, + unitary1: QuantumCircuit, + unitary2: QuantumCircuit, + prefix1: str = "p1", + prefix2: str = "p2", + insert_barrier: bool = False, ): """ Args: @@ -69,6 +74,7 @@ if it is parameterized. Defaults to ``"p1"``. prefix2: The name of the parameter vector associated to ``unitary2``, if it is parameterized. Defaults to ``"p2"``. + insert_barrier: Whether to insert a barrier between the two unitaries. Raises: CircuitError: Number of qubits in ``unitary1`` and ``unitary2`` does not match. @@ -95,6 +101,8 @@ # Generate the actual overlap circuit super().__init__(unitaries[0].num_qubits, name="UnitaryOverlap") self.compose(unitaries[0], inplace=True) + if insert_barrier: + self.barrier() self.compose(unitaries[1].inverse(), inplace=True)
{"golden_diff": "diff --git a/qiskit/circuit/library/overlap.py b/qiskit/circuit/library/overlap.py\n--- a/qiskit/circuit/library/overlap.py\n+++ b/qiskit/circuit/library/overlap.py\n@@ -59,7 +59,12 @@\n \"\"\"\n \n def __init__(\n- self, unitary1: QuantumCircuit, unitary2: QuantumCircuit, prefix1=\"p1\", prefix2=\"p2\"\n+ self,\n+ unitary1: QuantumCircuit,\n+ unitary2: QuantumCircuit,\n+ prefix1: str = \"p1\",\n+ prefix2: str = \"p2\",\n+ insert_barrier: bool = False,\n ):\n \"\"\"\n Args:\n@@ -69,6 +74,7 @@\n if it is parameterized. Defaults to ``\"p1\"``.\n prefix2: The name of the parameter vector associated to ``unitary2``,\n if it is parameterized. Defaults to ``\"p2\"``.\n+ insert_barrier: Whether to insert a barrier between the two unitaries.\n \n Raises:\n CircuitError: Number of qubits in ``unitary1`` and ``unitary2`` does not match.\n@@ -95,6 +101,8 @@\n # Generate the actual overlap circuit\n super().__init__(unitaries[0].num_qubits, name=\"UnitaryOverlap\")\n self.compose(unitaries[0], inplace=True)\n+ if insert_barrier:\n+ self.barrier()\n self.compose(unitaries[1].inverse(), inplace=True)\n", "issue": "Add insert_barrier argument to UnitaryOverlap\n### What should we add?\n\nThis argument would insert a barrier between the two unitaries. This is useful if you want to prevent circuit optimization between the two parts.\n", "before_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2023.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Unitary overlap circuit.\"\"\"\n\nfrom qiskit.circuit import QuantumCircuit, Gate\nfrom qiskit.circuit.parametervector import ParameterVector\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.circuit import Barrier\n\n\nclass UnitaryOverlap(QuantumCircuit):\n r\"\"\"Circuit that returns the overlap between two unitaries :math:`U_2^{\\dag} U_1`.\n\n The input quantum circuits must represent unitary operations, since they must be invertible.\n If the inputs will have parameters, they are replaced by :class:`.ParameterVector`\\s with\n names `\"p1\"` (for circuit ``unitary1``) and `\"p2\"` (for circuit ``unitary_2``) in the output\n circuit.\n\n This circuit is usually employed in computing the fidelity:\n\n .. math::\n\n \\left|\\langle 0| U_2^{\\dag} U_1|0\\rangle\\right|^{2}\n\n by computing the probability of being in the all-zeros bit-string, or equivalently,\n the expectation value of projector :math:`|0\\rangle\\langle 0|`.\n\n Example::\n\n import numpy as np\n from qiskit.circuit.library import EfficientSU2, UnitaryOverlap\n from qiskit.primitives import Sampler\n\n # get two circuit to prepare states of which we comput the overlap\n circuit = EfficientSU2(2, reps=1)\n unitary1 = circuit.assign_parameters(np.random.random(circuit.num_parameters))\n unitary2 = circuit.assign_parameters(np.random.random(circuit.num_parameters))\n\n # create the overlap circuit\n overlap = UnitaryOverap(unitary1, unitary2)\n\n # sample from the overlap\n sampler = Sampler(options={\"shots\": 100})\n result = sampler.run(overlap).result()\n\n # the fidelity is the probability to measure 0\n fidelity = result.quasi_dists[0].get(0, 0)\n\n \"\"\"\n\n def __init__(\n self, unitary1: QuantumCircuit, unitary2: QuantumCircuit, prefix1=\"p1\", prefix2=\"p2\"\n ):\n \"\"\"\n Args:\n unitary1: Unitary acting on the ket vector.\n unitary2: Unitary whose inverse operates on the bra vector.\n prefix1: The name of the parameter vector associated to ``unitary1``,\n if it is parameterized. Defaults to ``\"p1\"``.\n prefix2: The name of the parameter vector associated to ``unitary2``,\n if it is parameterized. Defaults to ``\"p2\"``.\n\n Raises:\n CircuitError: Number of qubits in ``unitary1`` and ``unitary2`` does not match.\n CircuitError: Inputs contain measurements and/or resets.\n \"\"\"\n # check inputs are valid\n if unitary1.num_qubits != unitary2.num_qubits:\n raise CircuitError(\n f\"Number of qubits in unitaries does \"\n f\"not match: {unitary1.num_qubits} != {unitary2.num_qubits}.\"\n )\n\n unitaries = [unitary1, unitary2]\n for unitary in unitaries:\n _check_unitary(unitary)\n\n # Vectors of new parameters, if any. Need the unitaries in a list here to ensure\n # we can overwrite them.\n for i, prefix in enumerate([prefix1, prefix2]):\n if unitaries[i].num_parameters > 0:\n new_params = ParameterVector(prefix, unitaries[i].num_parameters)\n unitaries[i] = unitaries[i].assign_parameters(new_params)\n\n # Generate the actual overlap circuit\n super().__init__(unitaries[0].num_qubits, name=\"UnitaryOverlap\")\n self.compose(unitaries[0], inplace=True)\n self.compose(unitaries[1].inverse(), inplace=True)\n\n\ndef _check_unitary(circuit):\n \"\"\"Check a circuit is unitary by checking if all operations are of type ``Gate``.\"\"\"\n\n for instruction in circuit.data:\n if not isinstance(instruction.operation, (Gate, Barrier)):\n raise CircuitError(\n (\n \"One or more instructions cannot be converted to\"\n ' a gate. \"{}\" is not a gate instruction'\n ).format(instruction.operation.name)\n )\n", "path": "qiskit/circuit/library/overlap.py"}], "after_files": [{"content": "# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2023.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Unitary overlap circuit.\"\"\"\n\nfrom qiskit.circuit import QuantumCircuit, Gate\nfrom qiskit.circuit.parametervector import ParameterVector\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.circuit import Barrier\n\n\nclass UnitaryOverlap(QuantumCircuit):\n r\"\"\"Circuit that returns the overlap between two unitaries :math:`U_2^{\\dag} U_1`.\n\n The input quantum circuits must represent unitary operations, since they must be invertible.\n If the inputs will have parameters, they are replaced by :class:`.ParameterVector`\\s with\n names `\"p1\"` (for circuit ``unitary1``) and `\"p2\"` (for circuit ``unitary_2``) in the output\n circuit.\n\n This circuit is usually employed in computing the fidelity:\n\n .. math::\n\n \\left|\\langle 0| U_2^{\\dag} U_1|0\\rangle\\right|^{2}\n\n by computing the probability of being in the all-zeros bit-string, or equivalently,\n the expectation value of projector :math:`|0\\rangle\\langle 0|`.\n\n Example::\n\n import numpy as np\n from qiskit.circuit.library import EfficientSU2, UnitaryOverlap\n from qiskit.primitives import Sampler\n\n # get two circuit to prepare states of which we comput the overlap\n circuit = EfficientSU2(2, reps=1)\n unitary1 = circuit.assign_parameters(np.random.random(circuit.num_parameters))\n unitary2 = circuit.assign_parameters(np.random.random(circuit.num_parameters))\n\n # create the overlap circuit\n overlap = UnitaryOverap(unitary1, unitary2)\n\n # sample from the overlap\n sampler = Sampler(options={\"shots\": 100})\n result = sampler.run(overlap).result()\n\n # the fidelity is the probability to measure 0\n fidelity = result.quasi_dists[0].get(0, 0)\n\n \"\"\"\n\n def __init__(\n self,\n unitary1: QuantumCircuit,\n unitary2: QuantumCircuit,\n prefix1: str = \"p1\",\n prefix2: str = \"p2\",\n insert_barrier: bool = False,\n ):\n \"\"\"\n Args:\n unitary1: Unitary acting on the ket vector.\n unitary2: Unitary whose inverse operates on the bra vector.\n prefix1: The name of the parameter vector associated to ``unitary1``,\n if it is parameterized. Defaults to ``\"p1\"``.\n prefix2: The name of the parameter vector associated to ``unitary2``,\n if it is parameterized. Defaults to ``\"p2\"``.\n insert_barrier: Whether to insert a barrier between the two unitaries.\n\n Raises:\n CircuitError: Number of qubits in ``unitary1`` and ``unitary2`` does not match.\n CircuitError: Inputs contain measurements and/or resets.\n \"\"\"\n # check inputs are valid\n if unitary1.num_qubits != unitary2.num_qubits:\n raise CircuitError(\n f\"Number of qubits in unitaries does \"\n f\"not match: {unitary1.num_qubits} != {unitary2.num_qubits}.\"\n )\n\n unitaries = [unitary1, unitary2]\n for unitary in unitaries:\n _check_unitary(unitary)\n\n # Vectors of new parameters, if any. Need the unitaries in a list here to ensure\n # we can overwrite them.\n for i, prefix in enumerate([prefix1, prefix2]):\n if unitaries[i].num_parameters > 0:\n new_params = ParameterVector(prefix, unitaries[i].num_parameters)\n unitaries[i] = unitaries[i].assign_parameters(new_params)\n\n # Generate the actual overlap circuit\n super().__init__(unitaries[0].num_qubits, name=\"UnitaryOverlap\")\n self.compose(unitaries[0], inplace=True)\n if insert_barrier:\n self.barrier()\n self.compose(unitaries[1].inverse(), inplace=True)\n\n\ndef _check_unitary(circuit):\n \"\"\"Check a circuit is unitary by checking if all operations are of type ``Gate``.\"\"\"\n\n for instruction in circuit.data:\n if not isinstance(instruction.operation, (Gate, Barrier)):\n raise CircuitError(\n (\n \"One or more instructions cannot be converted to\"\n ' a gate. \"{}\" is not a gate instruction'\n ).format(instruction.operation.name)\n )\n", "path": "qiskit/circuit/library/overlap.py"}]}
1,600
346
gh_patches_debug_60680
rasdani/github-patches
git_diff
OCHA-DAP__hdx-ckan-1798
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Ebola page: loading second page of datasets reloads to top of page Would it be easy to have it load the page at the `Datasets [41]` 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: `ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py` Content: ``` 1 ''' 2 Created on Nov 3, 2014 3 4 @author: alexandru-m-g 5 ''' 6 7 import logging 8 import datetime as dt 9 import decimal 10 11 import pylons.config as config 12 13 import ckan.lib.base as base 14 import ckan.logic as logic 15 import ckan.model as model 16 import ckan.common as common 17 import ckan.lib.helpers as h 18 19 render = base.render 20 get_action = logic.get_action 21 c = common.c 22 request = common.request 23 _ = common._ 24 25 Decimal = decimal.Decimal 26 27 log = logging.getLogger(__name__) 28 29 30 class CrisisController(base.BaseController): 31 32 def show(self): 33 34 context = {'model': model, 'session': model.Session, 35 'user': c.user or c.author, 'for_view': True, 36 'auth_user_obj': c.userobj} 37 38 datastore_resource_id = self._get_datastore_resource_id( 39 context, config.get('hdx.crisis.ebola_dataset', None), config.get('hdx.crisis.ebola_resource_title', None)) 40 if datastore_resource_id: 41 c.top_line_items = self._get_top_line_items( 42 context, datastore_resource_id) 43 44 limit = 25 45 c.q = u'ebola' 46 47 page = int(request.params.get('page', 1)) 48 data_dict = {'sort': u'metadata_modified desc', 49 'fq': '+dataset_type:dataset', 50 'rows': limit, 51 'q': c.q, 52 'start': (page - 1) * limit 53 } 54 query = get_action("package_search")(context, data_dict) 55 56 def pager_url(q=None, page=None): 57 return h.url_for('show_crisis', page=page) 58 59 c.page = h.Page( 60 collection=query['results'], 61 page=page, 62 url=pager_url, 63 item_count=query['count'], 64 items_per_page=limit 65 ) 66 c.items = query['results'] 67 c.item_count = query['count'] 68 69 c.other_links = {} 70 c.other_links['show_more'] = h.url_for( 71 "search", **{'q': u'ebola', 'sort': u'metadata_modified desc', 72 'ext_indicator': '0'}) 73 74 return render('crisis/crisis.html') 75 76 def _get_decimal_value(self, value): 77 decimal_value = Decimal(str(value)).quantize( 78 Decimal('.1'), rounding=decimal.ROUND_HALF_UP) 79 return decimal_value 80 81 def _format_results(self, result): 82 for r in result['records']: 83 d = dt.datetime.strptime(r[u'latest_date'], '%Y-%m-%dT%H:%M:%S') 84 r[u'latest_date'] = dt.datetime.strftime(d, '%b %d, %Y') 85 86 modified_value = r[u'value'] 87 if r[u'units'] == 'ratio': 88 modified_value *= 100.0 89 elif r[u'units'] == 'million': 90 modified_value /= 1000000.0 91 92 int_value = int(modified_value) 93 if int_value == modified_value: 94 r[u'formatted_value'] = '{:,}'.format(int_value) 95 else: 96 if r[u'units'] == 'ratio': 97 r[u'formatted_value'] = '{:,.1f}'.format( 98 self._get_decimal_value(modified_value)) 99 elif r[u'units'] == 'million': 100 r[u'formatted_value'] = '{:,.1f}'.format( 101 self._get_decimal_value(modified_value)) 102 #r[u'formatted_value'] += ' ' + _('million') 103 104 def _get_top_line_items(self, context, datastore_resource_id): 105 modified_context = dict(context) 106 modified_context['ignore_auth'] = True 107 result = get_action('datastore_search')( 108 modified_context, {'resource_id': datastore_resource_id}) 109 if 'records' in result: 110 self._format_results(result) 111 return result['records'] 112 return [] 113 114 def _get_datastore_resource_id(self, context, dataset_id, resource_name): 115 try: 116 modified_context = dict(context) 117 modified_context['ignore_auth'] = True 118 dataset = get_action('package_show')( 119 modified_context, {'id': dataset_id}) 120 121 if 'resources' in dataset: 122 for r in dataset['resources']: 123 if 'datastore_active' in r and r['datastore_active'] \ 124 and r['name'] == resource_name: 125 return r['id'] 126 return None 127 except: 128 log.warning('No dataset with id ' + dataset_id) 129 return None 130 ``` --- 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/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py b/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py --- a/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py +++ b/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py @@ -54,7 +54,8 @@ query = get_action("package_search")(context, data_dict) def pager_url(q=None, page=None): - return h.url_for('show_crisis', page=page) + url = h.url_for('show_crisis', page=page) + '#datasets-section' + return url c.page = h.Page( collection=query['results'],
{"golden_diff": "diff --git a/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py b/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py\n--- a/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py\n+++ b/ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py\n@@ -54,7 +54,8 @@\n query = get_action(\"package_search\")(context, data_dict)\n \n def pager_url(q=None, page=None):\n- return h.url_for('show_crisis', page=page)\n+ url = h.url_for('show_crisis', page=page) + '#datasets-section'\n+ return url\n \n c.page = h.Page(\n collection=query['results'],\n", "issue": "Ebola page: loading second page of datasets reloads to top of page\nWould it be easy to have it load the page at the `Datasets [41]` line?\n\n", "before_files": [{"content": "'''\nCreated on Nov 3, 2014\n\n@author: alexandru-m-g\n'''\n\nimport logging\nimport datetime as dt\nimport decimal\n\nimport pylons.config as config\n\nimport ckan.lib.base as base\nimport ckan.logic as logic\nimport ckan.model as model\nimport ckan.common as common\nimport ckan.lib.helpers as h\n\nrender = base.render\nget_action = logic.get_action\nc = common.c\nrequest = common.request\n_ = common._\n\nDecimal = decimal.Decimal\n\nlog = logging.getLogger(__name__)\n\n\nclass CrisisController(base.BaseController):\n\n def show(self):\n\n context = {'model': model, 'session': model.Session,\n 'user': c.user or c.author, 'for_view': True,\n 'auth_user_obj': c.userobj}\n\n datastore_resource_id = self._get_datastore_resource_id(\n context, config.get('hdx.crisis.ebola_dataset', None), config.get('hdx.crisis.ebola_resource_title', None))\n if datastore_resource_id:\n c.top_line_items = self._get_top_line_items(\n context, datastore_resource_id)\n\n limit = 25\n c.q = u'ebola'\n\n page = int(request.params.get('page', 1))\n data_dict = {'sort': u'metadata_modified desc',\n 'fq': '+dataset_type:dataset',\n 'rows': limit,\n 'q': c.q,\n 'start': (page - 1) * limit\n }\n query = get_action(\"package_search\")(context, data_dict)\n\n def pager_url(q=None, page=None):\n return h.url_for('show_crisis', page=page)\n\n c.page = h.Page(\n collection=query['results'],\n page=page,\n url=pager_url,\n item_count=query['count'],\n items_per_page=limit\n )\n c.items = query['results']\n c.item_count = query['count']\n\n c.other_links = {}\n c.other_links['show_more'] = h.url_for(\n \"search\", **{'q': u'ebola', 'sort': u'metadata_modified desc',\n 'ext_indicator': '0'})\n\n return render('crisis/crisis.html')\n\n def _get_decimal_value(self, value):\n decimal_value = Decimal(str(value)).quantize(\n Decimal('.1'), rounding=decimal.ROUND_HALF_UP)\n return decimal_value\n\n def _format_results(self, result):\n for r in result['records']:\n d = dt.datetime.strptime(r[u'latest_date'], '%Y-%m-%dT%H:%M:%S')\n r[u'latest_date'] = dt.datetime.strftime(d, '%b %d, %Y')\n\n modified_value = r[u'value']\n if r[u'units'] == 'ratio':\n modified_value *= 100.0\n elif r[u'units'] == 'million':\n modified_value /= 1000000.0\n\n int_value = int(modified_value)\n if int_value == modified_value:\n r[u'formatted_value'] = '{:,}'.format(int_value)\n else:\n if r[u'units'] == 'ratio':\n r[u'formatted_value'] = '{:,.1f}'.format(\n self._get_decimal_value(modified_value))\n elif r[u'units'] == 'million':\n r[u'formatted_value'] = '{:,.1f}'.format(\n self._get_decimal_value(modified_value))\n #r[u'formatted_value'] += ' ' + _('million')\n\n def _get_top_line_items(self, context, datastore_resource_id):\n modified_context = dict(context)\n modified_context['ignore_auth'] = True\n result = get_action('datastore_search')(\n modified_context, {'resource_id': datastore_resource_id})\n if 'records' in result:\n self._format_results(result)\n return result['records']\n return []\n\n def _get_datastore_resource_id(self, context, dataset_id, resource_name):\n try:\n modified_context = dict(context)\n modified_context['ignore_auth'] = True\n dataset = get_action('package_show')(\n modified_context, {'id': dataset_id})\n\n if 'resources' in dataset:\n for r in dataset['resources']:\n if 'datastore_active' in r and r['datastore_active'] \\\n and r['name'] == resource_name:\n return r['id']\n return None\n except:\n log.warning('No dataset with id ' + dataset_id)\n return None\n", "path": "ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py"}], "after_files": [{"content": "'''\nCreated on Nov 3, 2014\n\n@author: alexandru-m-g\n'''\n\nimport logging\nimport datetime as dt\nimport decimal\n\nimport pylons.config as config\n\nimport ckan.lib.base as base\nimport ckan.logic as logic\nimport ckan.model as model\nimport ckan.common as common\nimport ckan.lib.helpers as h\n\nrender = base.render\nget_action = logic.get_action\nc = common.c\nrequest = common.request\n_ = common._\n\nDecimal = decimal.Decimal\n\nlog = logging.getLogger(__name__)\n\n\nclass CrisisController(base.BaseController):\n\n def show(self):\n\n context = {'model': model, 'session': model.Session,\n 'user': c.user or c.author, 'for_view': True,\n 'auth_user_obj': c.userobj}\n\n datastore_resource_id = self._get_datastore_resource_id(\n context, config.get('hdx.crisis.ebola_dataset', None), config.get('hdx.crisis.ebola_resource_title', None))\n if datastore_resource_id:\n c.top_line_items = self._get_top_line_items(\n context, datastore_resource_id)\n\n limit = 25\n c.q = u'ebola'\n\n page = int(request.params.get('page', 1))\n data_dict = {'sort': u'metadata_modified desc',\n 'fq': '+dataset_type:dataset',\n 'rows': limit,\n 'q': c.q,\n 'start': (page - 1) * limit\n }\n query = get_action(\"package_search\")(context, data_dict)\n\n def pager_url(q=None, page=None):\n url = h.url_for('show_crisis', page=page) + '#datasets-section'\n return url\n\n c.page = h.Page(\n collection=query['results'],\n page=page,\n url=pager_url,\n item_count=query['count'],\n items_per_page=limit\n )\n c.items = query['results']\n c.item_count = query['count']\n\n c.other_links = {}\n c.other_links['show_more'] = h.url_for(\n \"search\", **{'q': u'ebola', 'sort': u'metadata_modified desc',\n 'ext_indicator': '0'})\n\n return render('crisis/crisis.html')\n\n def _get_decimal_value(self, value):\n decimal_value = Decimal(str(value)).quantize(\n Decimal('.1'), rounding=decimal.ROUND_HALF_UP)\n return decimal_value\n\n def _format_results(self, result):\n for r in result['records']:\n d = dt.datetime.strptime(r[u'latest_date'], '%Y-%m-%dT%H:%M:%S')\n r[u'latest_date'] = dt.datetime.strftime(d, '%b %d, %Y')\n\n modified_value = r[u'value']\n if r[u'units'] == 'ratio':\n modified_value *= 100.0\n elif r[u'units'] == 'million':\n modified_value /= 1000000.0\n\n int_value = int(modified_value)\n if int_value == modified_value:\n r[u'formatted_value'] = '{:,}'.format(int_value)\n else:\n if r[u'units'] == 'ratio':\n r[u'formatted_value'] = '{:,.1f}'.format(\n self._get_decimal_value(modified_value))\n elif r[u'units'] == 'million':\n r[u'formatted_value'] = '{:,.1f}'.format(\n self._get_decimal_value(modified_value))\n #r[u'formatted_value'] += ' ' + _('million')\n\n def _get_top_line_items(self, context, datastore_resource_id):\n modified_context = dict(context)\n modified_context['ignore_auth'] = True\n result = get_action('datastore_search')(\n modified_context, {'resource_id': datastore_resource_id})\n if 'records' in result:\n self._format_results(result)\n return result['records']\n return []\n\n def _get_datastore_resource_id(self, context, dataset_id, resource_name):\n try:\n modified_context = dict(context)\n modified_context['ignore_auth'] = True\n dataset = get_action('package_show')(\n modified_context, {'id': dataset_id})\n\n if 'resources' in dataset:\n for r in dataset['resources']:\n if 'datastore_active' in r and r['datastore_active'] \\\n and r['name'] == resource_name:\n return r['id']\n return None\n except:\n log.warning('No dataset with id ' + dataset_id)\n return None\n", "path": "ckanext-hdx_crisis/ckanext/hdx_crisis/controllers/crisis_controller.py"}]}
1,590
201
gh_patches_debug_7958
rasdani/github-patches
git_diff
apache__tvm-13442
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- [Bug][ci] Deploy docs is busted See for example https://ci.tlcpack.ai/blue/organizations/jenkins/tvm/detail/main/4756/pipeline ``` Traceback (most recent call last): File "./ci/scripts/jenkins/s3.py", line 134, in <module> chmod(files) File "./ci/scripts/jenkins/s3.py", line 70, in chmod SH.run(f"chmod +x {' '.join(to_chmod)}") File "/tmp/jenkins-ba6c252c/workspace/exec_0/tvm/deploy-docs/ci/scripts/jenkins/cmd_utils.py", line 78, in run return subprocess.run(cmd, **defaults) File "/usr/lib/python3.8/subprocess.py", line 493, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.8/subprocess.py", line 858, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 7] Argument list too long: '/bin/sh' ``` cc @Mousius @driazati @gigiblender --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `ci/scripts/jenkins/s3.py` Content: ``` 1 #!/usr/bin/env python3 2 # Licensed to the Apache Software Foundation (ASF) under one 3 # or more contributor license agreements. See the NOTICE file 4 # distributed with this work for additional information 5 # regarding copyright ownership. The ASF licenses this file 6 # to you under the Apache License, Version 2.0 (the 7 # "License"); you may not use this file except in compliance 8 # with the License. You may obtain a copy of the License at 9 # 10 # http://www.apache.org/licenses/LICENSE-2.0 11 # 12 # Unless required by applicable law or agreed to in writing, 13 # software distributed under the License is distributed on an 14 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 # KIND, either express or implied. See the License for the 16 # specific language governing permissions and limitations 17 # under the License. 18 19 import argparse 20 import logging 21 import re 22 from pathlib import Path 23 from typing import List 24 from enum import Enum 25 26 from cmd_utils import Sh, REPO_ROOT, init_log 27 28 RETRY_SCRIPT = REPO_ROOT / "ci" / "scripts" / "jenkins" / "retry.sh" 29 S3_DOWNLOAD_REGEX = re.compile(r"download: s3://.* to (.*)") 30 SH = Sh() 31 32 33 class Action(Enum): 34 UPLOAD = 1 35 DOWNLOAD = 2 36 37 38 def show_md5(item: str) -> None: 39 if not Path(item).is_dir(): 40 sh.run(f"md5sum {item}") 41 42 43 def parse_output_files(stdout: str) -> List[str]: 44 """ 45 Grab the list of downloaded files from the output of 'aws s3 cp'. Lines look 46 like: 47 48 download: s3://some/prefix/a_file.txt to a_file.txt 49 """ 50 files = [] 51 for line in stdout.split("\n"): 52 line = line.strip() 53 if line == "": 54 continue 55 m = S3_DOWNLOAD_REGEX.match(line) 56 if m: 57 files.append(m.groups()[0]) 58 59 return files 60 61 62 def chmod(files: List[str]) -> None: 63 """ 64 S3 has no concept of file permissions so add them back in here to every file 65 """ 66 # Add execute bit for downloads 67 to_chmod = [str(f) for f in files] 68 logging.info(f"Adding execute bit for files: {to_chmod}") 69 if len(to_chmod) > 0: 70 SH.run(f"chmod +x {' '.join(to_chmod)}") 71 72 73 def s3(source: str, destination: str, recursive: bool) -> List[str]: 74 """ 75 Send or download the source to the destination in S3 76 """ 77 cmd = f". {RETRY_SCRIPT.relative_to(REPO_ROOT)} && retry 3 aws s3 cp --no-progress" 78 79 if recursive: 80 cmd += " --recursive" 81 82 cmd += f" {source} {destination}" 83 _, stdout = SH.tee(cmd) 84 return stdout 85 86 87 if __name__ == "__main__": 88 init_log() 89 help = "Uploads or downloads files from S3" 90 parser = argparse.ArgumentParser(description=help) 91 parser.add_argument("--action", help="either 'upload' or 'download'", required=True) 92 parser.add_argument("--bucket", help="s3 bucket", required=True) 93 parser.add_argument( 94 "--prefix", help="s3 bucket + tag (e.g. s3://tvm-ci-prod/PR-1234/cpu", required=True 95 ) 96 parser.add_argument("--items", help="files and folders to upload", nargs="+") 97 98 args = parser.parse_args() 99 logging.info(args) 100 101 sh = Sh() 102 103 if Path.cwd() != REPO_ROOT: 104 logging.error(f"s3.py can only be executed from the repo root, instead was in {Path.cwd()}") 105 exit(1) 106 107 prefix = args.prefix.strip("/") 108 s3_path = f"s3://{args.bucket}/{prefix}" 109 logging.info(f"Using s3 path: {s3_path}") 110 111 if args.action == "upload": 112 action = Action.UPLOAD 113 elif args.action == "download": 114 action = Action.DOWNLOAD 115 else: 116 logging.error(f"Unsupported action: {args.action}") 117 exit(1) 118 119 if args.items is None: 120 if args.action == "upload": 121 logging.error(f"Cannot upload without --items") 122 exit(1) 123 else: 124 # Download the whole prefix 125 items = ["."] 126 127 else: 128 items = args.items 129 130 for item in items: 131 if action == Action.DOWNLOAD: 132 stdout = s3(source=s3_path, destination=item, recursive=True) 133 files = parse_output_files(stdout) 134 chmod(files) 135 for file in files: 136 # Show md5 after downloading 137 show_md5(file) 138 elif action == Action.UPLOAD: 139 show_md5(item) 140 s3(item, s3_path + "/" + item, recursive=Path(item).is_dir()) 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/ci/scripts/jenkins/s3.py b/ci/scripts/jenkins/s3.py --- a/ci/scripts/jenkins/s3.py +++ b/ci/scripts/jenkins/s3.py @@ -129,7 +129,12 @@ for item in items: if action == Action.DOWNLOAD: - stdout = s3(source=s3_path, destination=item, recursive=True) + source = s3_path + recursive = True + if item != ".": + source = s3_path + "/" + item + recursive = False + stdout = s3(source=source, destination=item, recursive=recursive) files = parse_output_files(stdout) chmod(files) for file in files:
{"golden_diff": "diff --git a/ci/scripts/jenkins/s3.py b/ci/scripts/jenkins/s3.py\n--- a/ci/scripts/jenkins/s3.py\n+++ b/ci/scripts/jenkins/s3.py\n@@ -129,7 +129,12 @@\n \n for item in items:\n if action == Action.DOWNLOAD:\n- stdout = s3(source=s3_path, destination=item, recursive=True)\n+ source = s3_path\n+ recursive = True\n+ if item != \".\":\n+ source = s3_path + \"/\" + item\n+ recursive = False\n+ stdout = s3(source=source, destination=item, recursive=recursive)\n files = parse_output_files(stdout)\n chmod(files)\n for file in files:\n", "issue": "[Bug][ci] Deploy docs is busted\nSee for example https://ci.tlcpack.ai/blue/organizations/jenkins/tvm/detail/main/4756/pipeline\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"./ci/scripts/jenkins/s3.py\", line 134, in <module>\r\n chmod(files)\r\n File \"./ci/scripts/jenkins/s3.py\", line 70, in chmod\r\n SH.run(f\"chmod +x {' '.join(to_chmod)}\")\r\n File \"/tmp/jenkins-ba6c252c/workspace/exec_0/tvm/deploy-docs/ci/scripts/jenkins/cmd_utils.py\", line 78, in run\r\n return subprocess.run(cmd, **defaults)\r\n File \"/usr/lib/python3.8/subprocess.py\", line 493, in run\r\n with Popen(*popenargs, **kwargs) as process:\r\n File \"/usr/lib/python3.8/subprocess.py\", line 858, in __init__\r\n self._execute_child(args, executable, preexec_fn, close_fds,\r\n File \"/usr/lib/python3.8/subprocess.py\", line 1704, in _execute_child\r\n raise child_exception_type(errno_num, err_msg, err_filename)\r\nOSError: [Errno 7] Argument list too long: '/bin/sh'\r\n```\n\ncc @Mousius @driazati @gigiblender\n", "before_files": [{"content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import List\nfrom enum import Enum\n\nfrom cmd_utils import Sh, REPO_ROOT, init_log\n\nRETRY_SCRIPT = REPO_ROOT / \"ci\" / \"scripts\" / \"jenkins\" / \"retry.sh\"\nS3_DOWNLOAD_REGEX = re.compile(r\"download: s3://.* to (.*)\")\nSH = Sh()\n\n\nclass Action(Enum):\n UPLOAD = 1\n DOWNLOAD = 2\n\n\ndef show_md5(item: str) -> None:\n if not Path(item).is_dir():\n sh.run(f\"md5sum {item}\")\n\n\ndef parse_output_files(stdout: str) -> List[str]:\n \"\"\"\n Grab the list of downloaded files from the output of 'aws s3 cp'. Lines look\n like:\n\n download: s3://some/prefix/a_file.txt to a_file.txt\n \"\"\"\n files = []\n for line in stdout.split(\"\\n\"):\n line = line.strip()\n if line == \"\":\n continue\n m = S3_DOWNLOAD_REGEX.match(line)\n if m:\n files.append(m.groups()[0])\n\n return files\n\n\ndef chmod(files: List[str]) -> None:\n \"\"\"\n S3 has no concept of file permissions so add them back in here to every file\n \"\"\"\n # Add execute bit for downloads\n to_chmod = [str(f) for f in files]\n logging.info(f\"Adding execute bit for files: {to_chmod}\")\n if len(to_chmod) > 0:\n SH.run(f\"chmod +x {' '.join(to_chmod)}\")\n\n\ndef s3(source: str, destination: str, recursive: bool) -> List[str]:\n \"\"\"\n Send or download the source to the destination in S3\n \"\"\"\n cmd = f\". {RETRY_SCRIPT.relative_to(REPO_ROOT)} && retry 3 aws s3 cp --no-progress\"\n\n if recursive:\n cmd += \" --recursive\"\n\n cmd += f\" {source} {destination}\"\n _, stdout = SH.tee(cmd)\n return stdout\n\n\nif __name__ == \"__main__\":\n init_log()\n help = \"Uploads or downloads files from S3\"\n parser = argparse.ArgumentParser(description=help)\n parser.add_argument(\"--action\", help=\"either 'upload' or 'download'\", required=True)\n parser.add_argument(\"--bucket\", help=\"s3 bucket\", required=True)\n parser.add_argument(\n \"--prefix\", help=\"s3 bucket + tag (e.g. s3://tvm-ci-prod/PR-1234/cpu\", required=True\n )\n parser.add_argument(\"--items\", help=\"files and folders to upload\", nargs=\"+\")\n\n args = parser.parse_args()\n logging.info(args)\n\n sh = Sh()\n\n if Path.cwd() != REPO_ROOT:\n logging.error(f\"s3.py can only be executed from the repo root, instead was in {Path.cwd()}\")\n exit(1)\n\n prefix = args.prefix.strip(\"/\")\n s3_path = f\"s3://{args.bucket}/{prefix}\"\n logging.info(f\"Using s3 path: {s3_path}\")\n\n if args.action == \"upload\":\n action = Action.UPLOAD\n elif args.action == \"download\":\n action = Action.DOWNLOAD\n else:\n logging.error(f\"Unsupported action: {args.action}\")\n exit(1)\n\n if args.items is None:\n if args.action == \"upload\":\n logging.error(f\"Cannot upload without --items\")\n exit(1)\n else:\n # Download the whole prefix\n items = [\".\"]\n\n else:\n items = args.items\n\n for item in items:\n if action == Action.DOWNLOAD:\n stdout = s3(source=s3_path, destination=item, recursive=True)\n files = parse_output_files(stdout)\n chmod(files)\n for file in files:\n # Show md5 after downloading\n show_md5(file)\n elif action == Action.UPLOAD:\n show_md5(item)\n s3(item, s3_path + \"/\" + item, recursive=Path(item).is_dir())\n", "path": "ci/scripts/jenkins/s3.py"}], "after_files": [{"content": "#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport argparse\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import List\nfrom enum import Enum\n\nfrom cmd_utils import Sh, REPO_ROOT, init_log\n\nRETRY_SCRIPT = REPO_ROOT / \"ci\" / \"scripts\" / \"jenkins\" / \"retry.sh\"\nS3_DOWNLOAD_REGEX = re.compile(r\"download: s3://.* to (.*)\")\nSH = Sh()\n\n\nclass Action(Enum):\n UPLOAD = 1\n DOWNLOAD = 2\n\n\ndef show_md5(item: str) -> None:\n if not Path(item).is_dir():\n sh.run(f\"md5sum {item}\")\n\n\ndef parse_output_files(stdout: str) -> List[str]:\n \"\"\"\n Grab the list of downloaded files from the output of 'aws s3 cp'. Lines look\n like:\n\n download: s3://some/prefix/a_file.txt to a_file.txt\n \"\"\"\n files = []\n for line in stdout.split(\"\\n\"):\n line = line.strip()\n if line == \"\":\n continue\n m = S3_DOWNLOAD_REGEX.match(line)\n if m:\n files.append(m.groups()[0])\n\n return files\n\n\ndef chmod(files: List[str]) -> None:\n \"\"\"\n S3 has no concept of file permissions so add them back in here to every file\n \"\"\"\n # Add execute bit for downloads\n to_chmod = [str(f) for f in files]\n logging.info(f\"Adding execute bit for files: {to_chmod}\")\n if len(to_chmod) > 0:\n SH.run(f\"chmod +x {' '.join(to_chmod)}\")\n\n\ndef s3(source: str, destination: str, recursive: bool) -> List[str]:\n \"\"\"\n Send or download the source to the destination in S3\n \"\"\"\n cmd = f\". {RETRY_SCRIPT.relative_to(REPO_ROOT)} && retry 3 aws s3 cp --no-progress\"\n\n if recursive:\n cmd += \" --recursive\"\n\n cmd += f\" {source} {destination}\"\n _, stdout = SH.tee(cmd)\n return stdout\n\n\nif __name__ == \"__main__\":\n init_log()\n help = \"Uploads or downloads files from S3\"\n parser = argparse.ArgumentParser(description=help)\n parser.add_argument(\"--action\", help=\"either 'upload' or 'download'\", required=True)\n parser.add_argument(\"--bucket\", help=\"s3 bucket\", required=True)\n parser.add_argument(\n \"--prefix\", help=\"s3 bucket + tag (e.g. s3://tvm-ci-prod/PR-1234/cpu\", required=True\n )\n parser.add_argument(\"--items\", help=\"files and folders to upload\", nargs=\"+\")\n\n args = parser.parse_args()\n logging.info(args)\n\n sh = Sh()\n\n if Path.cwd() != REPO_ROOT:\n logging.error(f\"s3.py can only be executed from the repo root, instead was in {Path.cwd()}\")\n exit(1)\n\n prefix = args.prefix.strip(\"/\")\n s3_path = f\"s3://{args.bucket}/{prefix}\"\n logging.info(f\"Using s3 path: {s3_path}\")\n\n if args.action == \"upload\":\n action = Action.UPLOAD\n elif args.action == \"download\":\n action = Action.DOWNLOAD\n else:\n logging.error(f\"Unsupported action: {args.action}\")\n exit(1)\n\n if args.items is None:\n if args.action == \"upload\":\n logging.error(f\"Cannot upload without --items\")\n exit(1)\n else:\n # Download the whole prefix\n items = [\".\"]\n\n else:\n items = args.items\n\n for item in items:\n if action == Action.DOWNLOAD:\n source = s3_path\n recursive = True\n if item != \".\":\n source = s3_path + \"/\" + item\n recursive = False\n stdout = s3(source=source, destination=item, recursive=recursive)\n files = parse_output_files(stdout)\n chmod(files)\n for file in files:\n # Show md5 after downloading\n show_md5(file)\n elif action == Action.UPLOAD:\n show_md5(item)\n s3(item, s3_path + \"/\" + item, recursive=Path(item).is_dir())\n", "path": "ci/scripts/jenkins/s3.py"}]}
1,956
165
gh_patches_debug_2938
rasdani/github-patches
git_diff
Parsl__parsl-613
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- TorqueProvider fails on NSCC The following patch is required in order to run the `TorqueProvider` on NSCC: ``` [nscc04] ~/libsubmit >git diff diff --git a/libsubmit/providers/torque/template.py b/libsubmit/providers/torque/template.py index a00ce7c..056c648 100644 --- a/libsubmit/providers/torque/template.py +++ b/libsubmit/providers/torque/template.py @@ -8,7 +8,6 @@ template_string = '''#!/bin/bash #PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node} #PBS -o ${submit_script_dir}/${jobname}.submit.stdout #PBS -e ${submit_script_dir}/${jobname}.submit.stderr -#PBS -v WORKER_LOGGING_LEVEL ${overrides} export JOBNAME="${jobname}" ``` Otherwise, the job fails with `qsub: cannot send environment with the job`. Could we just merge the patch, or should we make this configurable somehow? --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `parsl/providers/torque/template.py` Content: ``` 1 template_string = '''#!/bin/bash 2 3 #PBS -S /bin/bash 4 #PBS -N ${jobname} 5 #PBS -m n 6 #PBS -k eo 7 #PBS -l walltime=$walltime 8 #PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node} 9 #PBS -o ${submit_script_dir}/${jobname}.submit.stdout 10 #PBS -e ${submit_script_dir}/${jobname}.submit.stderr 11 #PBS -v WORKER_LOGGING_LEVEL 12 ${overrides} 13 14 export JOBNAME="${jobname}" 15 16 ${user_script} 17 18 ''' 19 ``` --- 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/parsl/providers/torque/template.py b/parsl/providers/torque/template.py --- a/parsl/providers/torque/template.py +++ b/parsl/providers/torque/template.py @@ -8,7 +8,6 @@ #PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node} #PBS -o ${submit_script_dir}/${jobname}.submit.stdout #PBS -e ${submit_script_dir}/${jobname}.submit.stderr -#PBS -v WORKER_LOGGING_LEVEL ${overrides} export JOBNAME="${jobname}"
{"golden_diff": "diff --git a/parsl/providers/torque/template.py b/parsl/providers/torque/template.py\n--- a/parsl/providers/torque/template.py\n+++ b/parsl/providers/torque/template.py\n@@ -8,7 +8,6 @@\n #PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}\n #PBS -o ${submit_script_dir}/${jobname}.submit.stdout\n #PBS -e ${submit_script_dir}/${jobname}.submit.stderr\n-#PBS -v WORKER_LOGGING_LEVEL\n ${overrides}\n \n export JOBNAME=\"${jobname}\"\n", "issue": "TorqueProvider fails on NSCC \nThe following patch is required in order to run the `TorqueProvider` on NSCC:\r\n```\r\n[nscc04] ~/libsubmit >git diff\r\ndiff --git a/libsubmit/providers/torque/template.py b/libsubmit/providers/torque/template.py\r\nindex a00ce7c..056c648 100644\r\n--- a/libsubmit/providers/torque/template.py\r\n+++ b/libsubmit/providers/torque/template.py\r\n@@ -8,7 +8,6 @@ template_string = '''#!/bin/bash\r\n #PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}\r\n #PBS -o ${submit_script_dir}/${jobname}.submit.stdout\r\n #PBS -e ${submit_script_dir}/${jobname}.submit.stderr\r\n-#PBS -v WORKER_LOGGING_LEVEL\r\n ${overrides}\r\n\r\n export JOBNAME=\"${jobname}\"\r\n```\r\n\r\nOtherwise, the job fails with `qsub: cannot send environment with the job`. Could we just merge the patch, or should we make this configurable somehow?\n", "before_files": [{"content": "template_string = '''#!/bin/bash\n\n#PBS -S /bin/bash\n#PBS -N ${jobname}\n#PBS -m n\n#PBS -k eo\n#PBS -l walltime=$walltime\n#PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}\n#PBS -o ${submit_script_dir}/${jobname}.submit.stdout\n#PBS -e ${submit_script_dir}/${jobname}.submit.stderr\n#PBS -v WORKER_LOGGING_LEVEL\n${overrides}\n\nexport JOBNAME=\"${jobname}\"\n\n${user_script}\n\n'''\n", "path": "parsl/providers/torque/template.py"}], "after_files": [{"content": "template_string = '''#!/bin/bash\n\n#PBS -S /bin/bash\n#PBS -N ${jobname}\n#PBS -m n\n#PBS -k eo\n#PBS -l walltime=$walltime\n#PBS -l nodes=${nodes_per_block}:ppn=${tasks_per_node}\n#PBS -o ${submit_script_dir}/${jobname}.submit.stdout\n#PBS -e ${submit_script_dir}/${jobname}.submit.stderr\n${overrides}\n\nexport JOBNAME=\"${jobname}\"\n\n${user_script}\n\n'''\n", "path": "parsl/providers/torque/template.py"}]}
638
123
gh_patches_debug_584
rasdani/github-patches
git_diff
pex-tool__pex-1709
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Release 2.1.77 On the docket: + [x] Fix pathologic lock creation slowness. #1707 + [x] Support uncompressed PEXes. (#1705) --- 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.76" 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.76" +__version__ = "2.1.77"
{"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.76\"\n+__version__ = \"2.1.77\"\n", "issue": "Release 2.1.77\nOn the docket:\r\n+ [x] Fix pathologic lock creation slowness. #1707 \r\n+ [x] Support uncompressed PEXes. (#1705)\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.76\"\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.77\"\n", "path": "pex/version.py"}]}
356
96
gh_patches_debug_60843
rasdani/github-patches
git_diff
doccano__doccano-1670
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Database table for SpanType has invalid name How to reproduce the behaviour --------- - Pull latest changes from master - ./manage.py migrate - ./api/migrations/0033_auto_20220127_0654.py will migrate the database table for `SpanType` to `label_types_spanType` - Delete a project `Project.objects.first().delete()`` Exception: <img width="511" alt="image" src="https://user-images.githubusercontent.com/6747788/152384221-a6a549b8-1cca-49c0-86e4-6a20f7d0a266.png"> The issue can be resolved by either renaming db table `label_types_spanType` to `label_types_spantype` or by explicitly setting `tb_table` for SpanType model like this: `db_table = "label_types_spanType"` Your Environment --------- * Operating System: macOS Monterey, doccano is locally executed * Python Version Used: 3.9 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `backend/api/migrations/0033_auto_20220127_0654.py` Content: ``` 1 # Generated by Django 3.2.11 on 2022-01-27 06:54 2 3 from django.db import migrations 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('labels', '0003_auto_20220127_0654'), 10 ('api', '0032_auto_20220127_0654'), 11 ] 12 13 operations = [ 14 migrations.SeparateDatabaseAndState( 15 state_operations=[ 16 migrations.DeleteModel( 17 name='CategoryType', 18 ), 19 migrations.DeleteModel( 20 name='RelationTypes', 21 ), 22 migrations.DeleteModel( 23 name='SpanType', 24 ), 25 ], 26 database_operations=[ 27 migrations.AlterModelTable( 28 name='CategoryType', 29 table='label_types_categorytype' 30 ), 31 migrations.AlterModelTable( 32 name='RelationTypes', 33 table='label_types_relationtypes' 34 ), 35 migrations.AlterModelTable( 36 name='SpanType', 37 table='label_types_spanType' 38 ) 39 ] 40 ) 41 ] 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/backend/api/migrations/0033_auto_20220127_0654.py b/backend/api/migrations/0033_auto_20220127_0654.py --- a/backend/api/migrations/0033_auto_20220127_0654.py +++ b/backend/api/migrations/0033_auto_20220127_0654.py @@ -34,7 +34,7 @@ ), migrations.AlterModelTable( name='SpanType', - table='label_types_spanType' + table='label_types_spantype' ) ] )
{"golden_diff": "diff --git a/backend/api/migrations/0033_auto_20220127_0654.py b/backend/api/migrations/0033_auto_20220127_0654.py\n--- a/backend/api/migrations/0033_auto_20220127_0654.py\n+++ b/backend/api/migrations/0033_auto_20220127_0654.py\n@@ -34,7 +34,7 @@\n ),\n migrations.AlterModelTable(\n name='SpanType',\n- table='label_types_spanType'\n+ table='label_types_spantype'\n )\n ]\n )\n", "issue": "Database table for SpanType has invalid name \nHow to reproduce the behaviour\r\n---------\r\n- Pull latest changes from master\r\n- ./manage.py migrate\r\n- ./api/migrations/0033_auto_20220127_0654.py will migrate the database table for `SpanType` to `label_types_spanType`\r\n- Delete a project `Project.objects.first().delete()``\r\n\r\nException:\r\n\r\n<img width=\"511\" alt=\"image\" src=\"https://user-images.githubusercontent.com/6747788/152384221-a6a549b8-1cca-49c0-86e4-6a20f7d0a266.png\">\r\n \r\nThe issue can be resolved by either renaming db table `label_types_spanType` to `label_types_spantype` or by explicitly setting `tb_table` for SpanType model like this: `db_table = \"label_types_spanType\"`\r\n\r\nYour Environment\r\n---------\r\n* Operating System: macOS Monterey, doccano is locally executed\r\n* Python Version Used: 3.9\r\n\n", "before_files": [{"content": "# Generated by Django 3.2.11 on 2022-01-27 06:54\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('labels', '0003_auto_20220127_0654'),\n ('api', '0032_auto_20220127_0654'),\n ]\n\n operations = [\n migrations.SeparateDatabaseAndState(\n state_operations=[\n migrations.DeleteModel(\n name='CategoryType',\n ),\n migrations.DeleteModel(\n name='RelationTypes',\n ),\n migrations.DeleteModel(\n name='SpanType',\n ),\n ],\n database_operations=[\n migrations.AlterModelTable(\n name='CategoryType',\n table='label_types_categorytype'\n ),\n migrations.AlterModelTable(\n name='RelationTypes',\n table='label_types_relationtypes'\n ),\n migrations.AlterModelTable(\n name='SpanType',\n table='label_types_spanType'\n )\n ]\n )\n ]\n", "path": "backend/api/migrations/0033_auto_20220127_0654.py"}], "after_files": [{"content": "# Generated by Django 3.2.11 on 2022-01-27 06:54\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('labels', '0003_auto_20220127_0654'),\n ('api', '0032_auto_20220127_0654'),\n ]\n\n operations = [\n migrations.SeparateDatabaseAndState(\n state_operations=[\n migrations.DeleteModel(\n name='CategoryType',\n ),\n migrations.DeleteModel(\n name='RelationTypes',\n ),\n migrations.DeleteModel(\n name='SpanType',\n ),\n ],\n database_operations=[\n migrations.AlterModelTable(\n name='CategoryType',\n table='label_types_categorytype'\n ),\n migrations.AlterModelTable(\n name='RelationTypes',\n table='label_types_relationtypes'\n ),\n migrations.AlterModelTable(\n name='SpanType',\n table='label_types_spantype'\n )\n ]\n )\n ]\n", "path": "backend/api/migrations/0033_auto_20220127_0654.py"}]}
835
163
gh_patches_debug_29475
rasdani/github-patches
git_diff
litestar-org__litestar-2259
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- StaticFilesConfig and virtual directories I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems. https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py` Content: ``` 1 import json 2 from pathlib import Path 3 from typing import Any 4 5 from rich import get_console 6 from sqlalchemy import create_engine 7 from sqlalchemy.orm import Mapped, Session, sessionmaker 8 9 from litestar.contrib.sqlalchemy.base import UUIDBase 10 from litestar.contrib.sqlalchemy.repository import SQLAlchemySyncRepository 11 from litestar.repository.filters import LimitOffset 12 13 here = Path(__file__).parent 14 console = get_console() 15 16 17 class USState(UUIDBase): 18 # you can optionally override the generated table name by manually setting it. 19 __tablename__ = "us_state_lookup" # type: ignore[assignment] 20 abbreviation: Mapped[str] 21 name: Mapped[str] 22 23 24 class USStateRepository(SQLAlchemySyncRepository[USState]): 25 """US State repository.""" 26 27 model_type = USState 28 29 30 engine = create_engine( 31 "duckdb:///:memory:", 32 future=True, 33 ) 34 session_factory: sessionmaker[Session] = sessionmaker(engine, expire_on_commit=False) 35 36 37 def open_fixture(fixtures_path: Path, fixture_name: str) -> Any: 38 """Loads JSON file with the specified fixture name 39 40 Args: 41 fixtures_path (Path): The path to look for fixtures 42 fixture_name (str): The fixture name to load. 43 44 Raises: 45 FileNotFoundError: Fixtures not found. 46 47 Returns: 48 Any: The parsed JSON data 49 """ 50 fixture = Path(fixtures_path / f"{fixture_name}.json") 51 if fixture.exists(): 52 with fixture.open(mode="r", encoding="utf-8") as f: 53 f_data = f.read() 54 return json.loads(f_data) 55 raise FileNotFoundError(f"Could not find the {fixture_name} fixture") 56 57 58 def run_script() -> None: 59 """Load data from a fixture.""" 60 61 # Initializes the database. 62 with engine.begin() as conn: 63 USState.metadata.create_all(conn) 64 65 with session_factory() as db_session: 66 # 1) load the JSON data into the US States table 67 repo = USStateRepository(session=db_session) 68 fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore 69 objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture]) 70 db_session.commit() 71 console.print(f"Created {len(objs)} new objects.") 72 73 # 2) Select paginated data and total row count. 74 created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0)) 75 console.print(f"Selected {len(created_objs)} records out of a total of {total_objs}.") 76 77 # 2) Let's remove the batch of records selected. 78 deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs]) 79 console.print(f"Removed {len(deleted_objs)} records out of a total of {total_objs}.") 80 81 # 3) Le'ts count the remaining rows 82 remaining_count = repo.count() 83 console.print(f"Found {remaining_count} remaining records after delete.") 84 85 86 if __name__ == "__main__": 87 run_script() 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/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py --- a/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py +++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py @@ -63,7 +63,7 @@ USState.metadata.create_all(conn) with session_factory() as db_session: - # 1) load the JSON data into the US States table + # 1) Load the JSON data into the US States table. repo = USStateRepository(session=db_session) fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture]) @@ -74,11 +74,11 @@ created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0)) console.print(f"Selected {len(created_objs)} records out of a total of {total_objs}.") - # 2) Let's remove the batch of records selected. + # 3) Let's remove the batch of records selected. deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs]) console.print(f"Removed {len(deleted_objs)} records out of a total of {total_objs}.") - # 3) Le'ts count the remaining rows + # 4) Let's count the remaining rows remaining_count = repo.count() console.print(f"Found {remaining_count} remaining records after delete.")
{"golden_diff": "diff --git a/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py\n--- a/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py\n+++ b/docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py\n@@ -63,7 +63,7 @@\n USState.metadata.create_all(conn)\n \n with session_factory() as db_session:\n- # 1) load the JSON data into the US States table\n+ # 1) Load the JSON data into the US States table.\n repo = USStateRepository(session=db_session)\n fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore\n objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture])\n@@ -74,11 +74,11 @@\n created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0))\n console.print(f\"Selected {len(created_objs)} records out of a total of {total_objs}.\")\n \n- # 2) Let's remove the batch of records selected.\n+ # 3) Let's remove the batch of records selected.\n deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs])\n console.print(f\"Removed {len(deleted_objs)} records out of a total of {total_objs}.\")\n \n- # 3) Le'ts count the remaining rows\n+ # 4) Let's count the remaining rows\n remaining_count = repo.count()\n console.print(f\"Found {remaining_count} remaining records after delete.\")\n", "issue": "StaticFilesConfig and virtual directories\nI'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. \r\n\r\nThis is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.\r\n\r\nhttps://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32\n", "before_files": [{"content": "import json\nfrom pathlib import Path\nfrom typing import Any\n\nfrom rich import get_console\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Mapped, Session, sessionmaker\n\nfrom litestar.contrib.sqlalchemy.base import UUIDBase\nfrom litestar.contrib.sqlalchemy.repository import SQLAlchemySyncRepository\nfrom litestar.repository.filters import LimitOffset\n\nhere = Path(__file__).parent\nconsole = get_console()\n\n\nclass USState(UUIDBase):\n # you can optionally override the generated table name by manually setting it.\n __tablename__ = \"us_state_lookup\" # type: ignore[assignment]\n abbreviation: Mapped[str]\n name: Mapped[str]\n\n\nclass USStateRepository(SQLAlchemySyncRepository[USState]):\n \"\"\"US State repository.\"\"\"\n\n model_type = USState\n\n\nengine = create_engine(\n \"duckdb:///:memory:\",\n future=True,\n)\nsession_factory: sessionmaker[Session] = sessionmaker(engine, expire_on_commit=False)\n\n\ndef open_fixture(fixtures_path: Path, fixture_name: str) -> Any:\n \"\"\"Loads JSON file with the specified fixture name\n\n Args:\n fixtures_path (Path): The path to look for fixtures\n fixture_name (str): The fixture name to load.\n\n Raises:\n FileNotFoundError: Fixtures not found.\n\n Returns:\n Any: The parsed JSON data\n \"\"\"\n fixture = Path(fixtures_path / f\"{fixture_name}.json\")\n if fixture.exists():\n with fixture.open(mode=\"r\", encoding=\"utf-8\") as f:\n f_data = f.read()\n return json.loads(f_data)\n raise FileNotFoundError(f\"Could not find the {fixture_name} fixture\")\n\n\ndef run_script() -> None:\n \"\"\"Load data from a fixture.\"\"\"\n\n # Initializes the database.\n with engine.begin() as conn:\n USState.metadata.create_all(conn)\n\n with session_factory() as db_session:\n # 1) load the JSON data into the US States table\n repo = USStateRepository(session=db_session)\n fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore\n objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture])\n db_session.commit()\n console.print(f\"Created {len(objs)} new objects.\")\n\n # 2) Select paginated data and total row count.\n created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0))\n console.print(f\"Selected {len(created_objs)} records out of a total of {total_objs}.\")\n\n # 2) Let's remove the batch of records selected.\n deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs])\n console.print(f\"Removed {len(deleted_objs)} records out of a total of {total_objs}.\")\n\n # 3) Le'ts count the remaining rows\n remaining_count = repo.count()\n console.print(f\"Found {remaining_count} remaining records after delete.\")\n\n\nif __name__ == \"__main__\":\n run_script()\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py"}], "after_files": [{"content": "import json\nfrom pathlib import Path\nfrom typing import Any\n\nfrom rich import get_console\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Mapped, Session, sessionmaker\n\nfrom litestar.contrib.sqlalchemy.base import UUIDBase\nfrom litestar.contrib.sqlalchemy.repository import SQLAlchemySyncRepository\nfrom litestar.repository.filters import LimitOffset\n\nhere = Path(__file__).parent\nconsole = get_console()\n\n\nclass USState(UUIDBase):\n # you can optionally override the generated table name by manually setting it.\n __tablename__ = \"us_state_lookup\" # type: ignore[assignment]\n abbreviation: Mapped[str]\n name: Mapped[str]\n\n\nclass USStateRepository(SQLAlchemySyncRepository[USState]):\n \"\"\"US State repository.\"\"\"\n\n model_type = USState\n\n\nengine = create_engine(\n \"duckdb:///:memory:\",\n future=True,\n)\nsession_factory: sessionmaker[Session] = sessionmaker(engine, expire_on_commit=False)\n\n\ndef open_fixture(fixtures_path: Path, fixture_name: str) -> Any:\n \"\"\"Loads JSON file with the specified fixture name\n\n Args:\n fixtures_path (Path): The path to look for fixtures\n fixture_name (str): The fixture name to load.\n\n Raises:\n FileNotFoundError: Fixtures not found.\n\n Returns:\n Any: The parsed JSON data\n \"\"\"\n fixture = Path(fixtures_path / f\"{fixture_name}.json\")\n if fixture.exists():\n with fixture.open(mode=\"r\", encoding=\"utf-8\") as f:\n f_data = f.read()\n return json.loads(f_data)\n raise FileNotFoundError(f\"Could not find the {fixture_name} fixture\")\n\n\ndef run_script() -> None:\n \"\"\"Load data from a fixture.\"\"\"\n\n # Initializes the database.\n with engine.begin() as conn:\n USState.metadata.create_all(conn)\n\n with session_factory() as db_session:\n # 1) Load the JSON data into the US States table.\n repo = USStateRepository(session=db_session)\n fixture = open_fixture(here, USStateRepository.model_type.__tablename__) # type: ignore\n objs = repo.add_many([USStateRepository.model_type(**raw_obj) for raw_obj in fixture])\n db_session.commit()\n console.print(f\"Created {len(objs)} new objects.\")\n\n # 2) Select paginated data and total row count.\n created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0))\n console.print(f\"Selected {len(created_objs)} records out of a total of {total_objs}.\")\n\n # 3) Let's remove the batch of records selected.\n deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs])\n console.print(f\"Removed {len(deleted_objs)} records out of a total of {total_objs}.\")\n\n # 4) Let's count the remaining rows\n remaining_count = repo.count()\n console.print(f\"Found {remaining_count} remaining records after delete.\")\n\n\nif __name__ == \"__main__\":\n run_script()\n", "path": "docs/examples/contrib/sqlalchemy/sqlalchemy_repository_bulk_operations.py"}]}
1,263
357
gh_patches_debug_25431
rasdani/github-patches
git_diff
lutris__lutris-994
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Auto update latest DXVK versions https://github.com/lutris/lutris/blob/525c84d9da173e84fd5585eed6b9d2fef5bef2b2/lutris/util/dxvk.py#L11-L12 Instead of writing static versions, use GitHub API to get the latest versions of DXVK: ```bash curl -s https://api.github.com/repos/doitsujin/dxvk/tags | jq '[.[] | .name] | join(", ")' "v0.62, v0.61, v0.60, v0.54, v0.53, v0.52, v0.51, v0.50, v0.42, v0.41, v0.40, v0.31, v0.30, v0.21, v0.20" ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `lutris/util/dxvk.py` Content: ``` 1 """DXVK helper module""" 2 import os 3 import time 4 import shutil 5 6 from lutris.settings import RUNTIME_DIR 7 from lutris.util.log import logger 8 from lutris.util.extract import extract_archive 9 from lutris.util.downloader import Downloader 10 11 DXVK_LATEST = "0.52" 12 DXVK_PAST_RELEASES = ["0.51", "0.50", "0.42", "0.31", "0.21"] 13 14 15 class DXVKManager: 16 """Utility class to install DXVK dlls to a Wine prefix""" 17 base_url = "https://github.com/doitsujin/dxvk/releases/download/v{}/dxvk-{}.tar.gz" 18 base_dir = os.path.join(RUNTIME_DIR, 'dxvk') 19 dxvk_dlls = ('dxgi', 'd3d11') 20 latest_version = DXVK_LATEST 21 22 def __init__(self, prefix, arch='win64', version=None): 23 self.prefix = prefix 24 if not os.path.isdir(self.base_dir): 25 os.makedirs(self.base_dir) 26 self._version = version 27 self.wine_arch = arch 28 29 @property 30 def version(self): 31 """Return version of DXVK (latest known version if not provided)""" 32 if self._version: 33 return self._version 34 return self.latest_version 35 36 @property 37 def dxvk_path(self): 38 """Return path to DXVK local cache""" 39 return os.path.join(self.base_dir, self.version) 40 41 @staticmethod 42 def is_dxvk_dll(dll_path): 43 """Check if a given DLL path is provided by DXVK 44 45 Very basic check to see if a dll exists and is over 1MB. If this is the 46 case, then consider the DLL to be from DXVK 47 """ 48 if os.path.exists(dll_path): 49 dll_stats = os.stat(dll_path) 50 dll_size = dll_stats.st_size 51 else: 52 dll_size = 0 53 return dll_size > 1024 * 1024 54 55 def is_available(self): 56 """Return whether DXVK is cached locally""" 57 return os.path.exists(self.dxvk_path) 58 59 def download(self): 60 """Download DXVK to the local cache""" 61 # There's a glitch in one of the archive's names 62 fixed_version = 'v0.40' if self.version == '0.40' else self.version 63 dxvk_url = self.base_url.format(self.version, fixed_version) 64 if self.is_available(): 65 logger.warning("DXVK already available at %s", self.dxvk_path) 66 67 dxvk_archive_path = os.path.join(self.base_dir, os.path.basename(dxvk_url)) 68 downloader = Downloader(dxvk_url, dxvk_archive_path) 69 downloader.start() 70 while downloader.check_progress() < 1: 71 time.sleep(1) 72 if not os.path.exists(dxvk_archive_path): 73 logger.error("DXVK %s not downloaded") 74 return 75 if os.stat(dxvk_archive_path).st_size: 76 extract_archive(dxvk_archive_path, self.dxvk_path, merge_single=True) 77 else: 78 logger.error("%s is an empty file", self.dxvk_path) 79 os.remove(dxvk_archive_path) 80 81 def enable_dxvk_dll(self, system_dir, dxvk_arch, dll): 82 """Copies DXVK dlls to the appropriate destination""" 83 wine_dll_path = os.path.join(system_dir, '%s.dll' % dll) 84 logger.info("Replacing %s/%s with DXVK version", system_dir, dll) 85 if not self.is_dxvk_dll(wine_dll_path): 86 # Backing up original version (may not be needed) 87 if os.path.exists(wine_dll_path): 88 shutil.move(wine_dll_path, wine_dll_path + ".orig") 89 # Copying DXVK's version 90 dxvk_dll_path = os.path.join(self.dxvk_path, dxvk_arch, "%s.dll" % dll) 91 shutil.copy(dxvk_dll_path, wine_dll_path) 92 93 def disable_dxvk_dll(self, system_dir, dxvk_arch, dll): 94 """Remove DXVK DLL from Wine prefix""" 95 wine_dll_path = os.path.join(system_dir, '%s.dll' % dll) 96 if self.is_dxvk_dll(wine_dll_path): 97 logger.info("Removing DXVK dll %s/%s", system_dir, dll) 98 os.remove(wine_dll_path) 99 # Restoring original version (may not be needed) 100 if os.path.exists(wine_dll_path + '.orig'): 101 shutil.move(wine_dll_path + '.orig', wine_dll_path) 102 103 def _iter_dxvk_dlls(self): 104 windows_path = os.path.join(self.prefix, 'drive_c/windows') 105 if self.wine_arch == 'win64': 106 system_dirs = { 107 'x64': os.path.join(windows_path, 'system32'), 108 'x32': os.path.join(windows_path, 'syswow64') 109 } 110 elif self.wine_arch == 'win32': 111 system_dirs = { 112 'x32': os.path.join(windows_path, 'system32'), 113 } 114 115 for dxvk_arch, system_dir in system_dirs.items(): 116 for dll in self.dxvk_dlls: 117 yield system_dir, dxvk_arch, dll 118 119 def enable(self): 120 """Enable DXVK for the current prefix""" 121 if not os.path.exists(self.dxvk_path): 122 logger.error("DXVK %s is not availble locally" % self.version) 123 return 124 for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls(): 125 self.enable_dxvk_dll(system_dir, dxvk_arch, dll) 126 127 def disable(self): 128 """Disable DXVK for the current prefix""" 129 for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls(): 130 self.disable_dxvk_dll(system_dir, dxvk_arch, dll) 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/lutris/util/dxvk.py b/lutris/util/dxvk.py --- a/lutris/util/dxvk.py +++ b/lutris/util/dxvk.py @@ -1,16 +1,41 @@ """DXVK helper module""" import os +import json import time import shutil +import urllib.request from lutris.settings import RUNTIME_DIR from lutris.util.log import logger from lutris.util.extract import extract_archive from lutris.util.downloader import Downloader -DXVK_LATEST = "0.52" -DXVK_PAST_RELEASES = ["0.51", "0.50", "0.42", "0.31", "0.21"] +def get_latest_dxvk_versions(): + """Get latest DXVK versions from GitHub""" + dxvk_url = "https://api.github.com/repos/doitsujin/dxvk/tags" + cache = os.path.join(RUNTIME_DIR, 'dxvk', 'dxvk_versions.json') + + # If the DXVK cache does not exist then download it + if not os.path.exists(cache): + urllib.request.urlretrieve(dxvk_url, cache) + + # Re-download DXVK versions cache if more than a day old + if os.path.getmtime(cache)+86400 < time.time(): + urllib.request.urlretrieve(dxvk_url, cache) + + with open(cache, "r") as f: + dxvk_json = json.load(f) + DXVK_LATEST = dxvk_json[0]['name'].replace('v','') + DXVK_PAST_RELEASES = [x['name'].replace('v', '') for x in dxvk_json][1:] + + return DXVK_LATEST, DXVK_PAST_RELEASES + +try: + DXVK_LATEST, DXVK_PAST_RELEASES = get_latest_dxvk_versions() +except: + DXVK_LATEST = "0.52" + DXVK_PAST_RELEASES = ["0.51", "0.50", "0.42", "0.31", "0.21"] class DXVKManager: """Utility class to install DXVK dlls to a Wine prefix"""
{"golden_diff": "diff --git a/lutris/util/dxvk.py b/lutris/util/dxvk.py\n--- a/lutris/util/dxvk.py\n+++ b/lutris/util/dxvk.py\n@@ -1,16 +1,41 @@\n \"\"\"DXVK helper module\"\"\"\n import os\n+import json\n import time\n import shutil\n+import urllib.request\n \n from lutris.settings import RUNTIME_DIR\n from lutris.util.log import logger\n from lutris.util.extract import extract_archive\n from lutris.util.downloader import Downloader\n \n-DXVK_LATEST = \"0.52\"\n-DXVK_PAST_RELEASES = [\"0.51\", \"0.50\", \"0.42\", \"0.31\", \"0.21\"]\n \n+def get_latest_dxvk_versions():\n+ \"\"\"Get latest DXVK versions from GitHub\"\"\"\n+ dxvk_url = \"https://api.github.com/repos/doitsujin/dxvk/tags\"\n+ cache = os.path.join(RUNTIME_DIR, 'dxvk', 'dxvk_versions.json')\n+\n+ # If the DXVK cache does not exist then download it\n+ if not os.path.exists(cache):\n+ urllib.request.urlretrieve(dxvk_url, cache)\n+\n+ # Re-download DXVK versions cache if more than a day old\n+ if os.path.getmtime(cache)+86400 < time.time():\n+ urllib.request.urlretrieve(dxvk_url, cache)\n+\n+ with open(cache, \"r\") as f:\n+ dxvk_json = json.load(f)\n+ DXVK_LATEST = dxvk_json[0]['name'].replace('v','')\n+ DXVK_PAST_RELEASES = [x['name'].replace('v', '') for x in dxvk_json][1:]\n+\n+ return DXVK_LATEST, DXVK_PAST_RELEASES\n+\n+try:\n+ DXVK_LATEST, DXVK_PAST_RELEASES = get_latest_dxvk_versions()\n+except:\n+ DXVK_LATEST = \"0.52\"\n+ DXVK_PAST_RELEASES = [\"0.51\", \"0.50\", \"0.42\", \"0.31\", \"0.21\"]\n \n class DXVKManager:\n \"\"\"Utility class to install DXVK dlls to a Wine prefix\"\"\"\n", "issue": "Auto update latest DXVK versions\nhttps://github.com/lutris/lutris/blob/525c84d9da173e84fd5585eed6b9d2fef5bef2b2/lutris/util/dxvk.py#L11-L12\r\n\r\nInstead of writing static versions, use GitHub API to get the latest versions of DXVK:\r\n```bash\r\ncurl -s https://api.github.com/repos/doitsujin/dxvk/tags | jq '[.[] | .name] | join(\", \")'\r\n\"v0.62, v0.61, v0.60, v0.54, v0.53, v0.52, v0.51, v0.50, v0.42, v0.41, v0.40, v0.31, v0.30, v0.21, v0.20\"\r\n```\n", "before_files": [{"content": "\"\"\"DXVK helper module\"\"\"\nimport os\nimport time\nimport shutil\n\nfrom lutris.settings import RUNTIME_DIR\nfrom lutris.util.log import logger\nfrom lutris.util.extract import extract_archive\nfrom lutris.util.downloader import Downloader\n\nDXVK_LATEST = \"0.52\"\nDXVK_PAST_RELEASES = [\"0.51\", \"0.50\", \"0.42\", \"0.31\", \"0.21\"]\n\n\nclass DXVKManager:\n \"\"\"Utility class to install DXVK dlls to a Wine prefix\"\"\"\n base_url = \"https://github.com/doitsujin/dxvk/releases/download/v{}/dxvk-{}.tar.gz\"\n base_dir = os.path.join(RUNTIME_DIR, 'dxvk')\n dxvk_dlls = ('dxgi', 'd3d11')\n latest_version = DXVK_LATEST\n\n def __init__(self, prefix, arch='win64', version=None):\n self.prefix = prefix\n if not os.path.isdir(self.base_dir):\n os.makedirs(self.base_dir)\n self._version = version\n self.wine_arch = arch\n\n @property\n def version(self):\n \"\"\"Return version of DXVK (latest known version if not provided)\"\"\"\n if self._version:\n return self._version\n return self.latest_version\n\n @property\n def dxvk_path(self):\n \"\"\"Return path to DXVK local cache\"\"\"\n return os.path.join(self.base_dir, self.version)\n\n @staticmethod\n def is_dxvk_dll(dll_path):\n \"\"\"Check if a given DLL path is provided by DXVK\n\n Very basic check to see if a dll exists and is over 1MB. If this is the\n case, then consider the DLL to be from DXVK\n \"\"\"\n if os.path.exists(dll_path):\n dll_stats = os.stat(dll_path)\n dll_size = dll_stats.st_size\n else:\n dll_size = 0\n return dll_size > 1024 * 1024\n\n def is_available(self):\n \"\"\"Return whether DXVK is cached locally\"\"\"\n return os.path.exists(self.dxvk_path)\n\n def download(self):\n \"\"\"Download DXVK to the local cache\"\"\"\n # There's a glitch in one of the archive's names\n fixed_version = 'v0.40' if self.version == '0.40' else self.version\n dxvk_url = self.base_url.format(self.version, fixed_version)\n if self.is_available():\n logger.warning(\"DXVK already available at %s\", self.dxvk_path)\n\n dxvk_archive_path = os.path.join(self.base_dir, os.path.basename(dxvk_url))\n downloader = Downloader(dxvk_url, dxvk_archive_path)\n downloader.start()\n while downloader.check_progress() < 1:\n time.sleep(1)\n if not os.path.exists(dxvk_archive_path):\n logger.error(\"DXVK %s not downloaded\")\n return\n if os.stat(dxvk_archive_path).st_size:\n extract_archive(dxvk_archive_path, self.dxvk_path, merge_single=True)\n else:\n logger.error(\"%s is an empty file\", self.dxvk_path)\n os.remove(dxvk_archive_path)\n\n def enable_dxvk_dll(self, system_dir, dxvk_arch, dll):\n \"\"\"Copies DXVK dlls to the appropriate destination\"\"\"\n wine_dll_path = os.path.join(system_dir, '%s.dll' % dll)\n logger.info(\"Replacing %s/%s with DXVK version\", system_dir, dll)\n if not self.is_dxvk_dll(wine_dll_path):\n # Backing up original version (may not be needed)\n if os.path.exists(wine_dll_path):\n shutil.move(wine_dll_path, wine_dll_path + \".orig\")\n # Copying DXVK's version\n dxvk_dll_path = os.path.join(self.dxvk_path, dxvk_arch, \"%s.dll\" % dll)\n shutil.copy(dxvk_dll_path, wine_dll_path)\n\n def disable_dxvk_dll(self, system_dir, dxvk_arch, dll):\n \"\"\"Remove DXVK DLL from Wine prefix\"\"\"\n wine_dll_path = os.path.join(system_dir, '%s.dll' % dll)\n if self.is_dxvk_dll(wine_dll_path):\n logger.info(\"Removing DXVK dll %s/%s\", system_dir, dll)\n os.remove(wine_dll_path)\n # Restoring original version (may not be needed)\n if os.path.exists(wine_dll_path + '.orig'):\n shutil.move(wine_dll_path + '.orig', wine_dll_path)\n\n def _iter_dxvk_dlls(self):\n windows_path = os.path.join(self.prefix, 'drive_c/windows')\n if self.wine_arch == 'win64':\n system_dirs = {\n 'x64': os.path.join(windows_path, 'system32'),\n 'x32': os.path.join(windows_path, 'syswow64')\n }\n elif self.wine_arch == 'win32':\n system_dirs = {\n 'x32': os.path.join(windows_path, 'system32'),\n }\n\n for dxvk_arch, system_dir in system_dirs.items():\n for dll in self.dxvk_dlls:\n yield system_dir, dxvk_arch, dll\n\n def enable(self):\n \"\"\"Enable DXVK for the current prefix\"\"\"\n if not os.path.exists(self.dxvk_path):\n logger.error(\"DXVK %s is not availble locally\" % self.version)\n return\n for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls():\n self.enable_dxvk_dll(system_dir, dxvk_arch, dll)\n\n def disable(self):\n \"\"\"Disable DXVK for the current prefix\"\"\"\n for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls():\n self.disable_dxvk_dll(system_dir, dxvk_arch, dll)\n", "path": "lutris/util/dxvk.py"}], "after_files": [{"content": "\"\"\"DXVK helper module\"\"\"\nimport os\nimport json\nimport time\nimport shutil\nimport urllib.request\n\nfrom lutris.settings import RUNTIME_DIR\nfrom lutris.util.log import logger\nfrom lutris.util.extract import extract_archive\nfrom lutris.util.downloader import Downloader\n\n\ndef get_latest_dxvk_versions():\n \"\"\"Get latest DXVK versions from GitHub\"\"\"\n dxvk_url = \"https://api.github.com/repos/doitsujin/dxvk/tags\"\n cache = os.path.join(RUNTIME_DIR, 'dxvk', 'dxvk_versions.json')\n\n # If the DXVK cache does not exist then download it\n if not os.path.exists(cache):\n urllib.request.urlretrieve(dxvk_url, cache)\n\n # Re-download DXVK versions cache if more than a day old\n if os.path.getmtime(cache)+86400 < time.time():\n urllib.request.urlretrieve(dxvk_url, cache)\n\n with open(cache, \"r\") as f:\n dxvk_json = json.load(f)\n DXVK_LATEST = dxvk_json[0]['name'].replace('v','')\n DXVK_PAST_RELEASES = [x['name'].replace('v', '') for x in dxvk_json][1:]\n\n return DXVK_LATEST, DXVK_PAST_RELEASES\n\ntry:\n DXVK_LATEST, DXVK_PAST_RELEASES = get_latest_dxvk_versions()\nexcept:\n DXVK_LATEST = \"0.52\"\n DXVK_PAST_RELEASES = [\"0.51\", \"0.50\", \"0.42\", \"0.31\", \"0.21\"]\n\nclass DXVKManager:\n \"\"\"Utility class to install DXVK dlls to a Wine prefix\"\"\"\n base_url = \"https://github.com/doitsujin/dxvk/releases/download/v{}/dxvk-{}.tar.gz\"\n base_dir = os.path.join(RUNTIME_DIR, 'dxvk')\n dxvk_dlls = ('dxgi', 'd3d11')\n latest_version = DXVK_LATEST\n\n def __init__(self, prefix, arch='win64', version=None):\n self.prefix = prefix\n if not os.path.isdir(self.base_dir):\n os.makedirs(self.base_dir)\n self._version = version\n self.wine_arch = arch\n\n @property\n def version(self):\n \"\"\"Return version of DXVK (latest known version if not provided)\"\"\"\n if self._version:\n return self._version\n return self.latest_version\n\n @property\n def dxvk_path(self):\n \"\"\"Return path to DXVK local cache\"\"\"\n return os.path.join(self.base_dir, self.version)\n\n @staticmethod\n def is_dxvk_dll(dll_path):\n \"\"\"Check if a given DLL path is provided by DXVK\n\n Very basic check to see if a dll exists and is over 1MB. If this is the\n case, then consider the DLL to be from DXVK\n \"\"\"\n if os.path.exists(dll_path):\n dll_stats = os.stat(dll_path)\n dll_size = dll_stats.st_size\n else:\n dll_size = 0\n return dll_size > 1024 * 1024\n\n def is_available(self):\n \"\"\"Return whether DXVK is cached locally\"\"\"\n return os.path.exists(self.dxvk_path)\n\n def download(self):\n \"\"\"Download DXVK to the local cache\"\"\"\n # There's a glitch in one of the archive's names\n fixed_version = 'v0.40' if self.version == '0.40' else self.version\n dxvk_url = self.base_url.format(self.version, fixed_version)\n if self.is_available():\n logger.warning(\"DXVK already available at %s\", self.dxvk_path)\n\n dxvk_archive_path = os.path.join(self.base_dir, os.path.basename(dxvk_url))\n downloader = Downloader(dxvk_url, dxvk_archive_path)\n downloader.start()\n while downloader.check_progress() < 1:\n time.sleep(1)\n if not os.path.exists(dxvk_archive_path):\n logger.error(\"DXVK %s not downloaded\")\n return\n if os.stat(dxvk_archive_path).st_size:\n extract_archive(dxvk_archive_path, self.dxvk_path, merge_single=True)\n else:\n logger.error(\"%s is an empty file\", self.dxvk_path)\n os.remove(dxvk_archive_path)\n\n def enable_dxvk_dll(self, system_dir, dxvk_arch, dll):\n \"\"\"Copies DXVK dlls to the appropriate destination\"\"\"\n wine_dll_path = os.path.join(system_dir, '%s.dll' % dll)\n logger.info(\"Replacing %s/%s with DXVK version\", system_dir, dll)\n if not self.is_dxvk_dll(wine_dll_path):\n # Backing up original version (may not be needed)\n if os.path.exists(wine_dll_path):\n shutil.move(wine_dll_path, wine_dll_path + \".orig\")\n # Copying DXVK's version\n dxvk_dll_path = os.path.join(self.dxvk_path, dxvk_arch, \"%s.dll\" % dll)\n shutil.copy(dxvk_dll_path, wine_dll_path)\n\n def disable_dxvk_dll(self, system_dir, dxvk_arch, dll):\n \"\"\"Remove DXVK DLL from Wine prefix\"\"\"\n wine_dll_path = os.path.join(system_dir, '%s.dll' % dll)\n if self.is_dxvk_dll(wine_dll_path):\n logger.info(\"Removing DXVK dll %s/%s\", system_dir, dll)\n os.remove(wine_dll_path)\n # Restoring original version (may not be needed)\n if os.path.exists(wine_dll_path + '.orig'):\n shutil.move(wine_dll_path + '.orig', wine_dll_path)\n\n def _iter_dxvk_dlls(self):\n windows_path = os.path.join(self.prefix, 'drive_c/windows')\n if self.wine_arch == 'win64':\n system_dirs = {\n 'x64': os.path.join(windows_path, 'system32'),\n 'x32': os.path.join(windows_path, 'syswow64')\n }\n elif self.wine_arch == 'win32':\n system_dirs = {\n 'x32': os.path.join(windows_path, 'system32'),\n }\n\n for dxvk_arch, system_dir in system_dirs.items():\n for dll in self.dxvk_dlls:\n yield system_dir, dxvk_arch, dll\n\n def enable(self):\n \"\"\"Enable DXVK for the current prefix\"\"\"\n if not os.path.exists(self.dxvk_path):\n logger.error(\"DXVK %s is not availble locally\" % self.version)\n return\n for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls():\n self.enable_dxvk_dll(system_dir, dxvk_arch, dll)\n\n def disable(self):\n \"\"\"Disable DXVK for the current prefix\"\"\"\n for system_dir, dxvk_arch, dll in self._iter_dxvk_dlls():\n self.disable_dxvk_dll(system_dir, dxvk_arch, dll)\n", "path": "lutris/util/dxvk.py"}]}
2,039
501
gh_patches_debug_4016
rasdani/github-patches
git_diff
ansible__awx-14626
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Issue on awx.awx.export/import awx cli/collection ### Please confirm the following - [X] I agree to follow this project's [code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html). - [X] I have checked the [current issues](https://github.com/ansible/awx/issues) for duplicates. - [X] I understand that AWX is open source software provided for free and that I might not receive a timely response. - [X] I am **NOT** reporting a (potential) security vulnerability. (These should be emailed to `[email protected]` instead.) ### Bug Summary Hi team, I founded tow bugs related awx cli and collection import / export. The first issue is related export module, that not work if user is a system_auditor (or not have certain admin role in object like schedule. I already found why this bug is present and proposed a PR: #14626 . Second "bug" is related import module (I don't know and don't find if someone decide it) and is related how import will be processed. Actually import perform a `POST`, if object not exists, or a `PUT`, if object exists. In case of we `PUT` an object that already exist api will replace it in all fields, including encrypted key, that in export are removed (correctly). So, i don't know if it's better approach with `PATCH` instead a `PUT`, but I think that here the issue is in the export itself, that will replace value of encrypted key `$encrypted$` with `''` . The side effect of "restore" `$encrypted$ ` on the export is that we remove it for the POST, due to the fact that is a reseved keyword. I will propose a PR also to fix the second bugs ### AWX version 23.3.1 ### Select the relevant components - [ ] UI - [ ] UI (tech preview) - [X] API - [ ] Docs - [X] Collection - [X] CLI - [ ] Other ### Installation method kubernetes ### Modifications no ### Ansible version _No response_ ### Operating system _No response_ ### Web browser _No response_ ### Steps to reproduce bug 1: execute an export of schedule with a system_auditor bug 2: import a credential already present in AWX ### Expected results bug 1: export will go fine bug 2: credential will be updated with only fields present in export ### Actual results bug 1: export will fail bug 2: credential will be replaced with exported data. But due to the fact that encrypted key are not exported and replaced the value `$encrypted$` with `''` we replace current secrets with `''` ### Additional information _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: `awxkit/awxkit/api/utils.py` Content: ``` 1 import logging 2 import re 3 4 5 log = logging.getLogger(__name__) 6 7 descRE = re.compile(r'^[*] `(\w+)`: [^(]*\((\w+), ([^)]+)\)') 8 9 10 def freeze(key): 11 if key is None: 12 return None 13 return frozenset((k, freeze(v) if isinstance(v, dict) else v) for k, v in key.items()) 14 15 16 def parse_description(desc): 17 options = {} 18 for line in desc[desc.index('POST') :].splitlines(): 19 match = descRE.match(line) 20 if not match: 21 continue 22 options[match.group(1)] = {'type': match.group(2), 'required': match.group(3) == 'required'} 23 return options 24 25 26 def remove_encrypted(value): 27 if value == '$encrypted$': 28 return '' 29 if isinstance(value, list): 30 return [remove_encrypted(item) for item in value] 31 if isinstance(value, dict): 32 return {k: remove_encrypted(v) for k, v in value.items()} 33 return value 34 35 36 def get_post_fields(page, cache): 37 options_page = cache.get_options(page) 38 if options_page is None: 39 return None 40 41 if 'POST' not in options_page.r.headers.get('Allow', ''): 42 return None 43 44 if 'POST' in options_page.json['actions']: 45 return options_page.json['actions']['POST'] 46 else: 47 log.warning("Insufficient privileges on %s, inferring POST fields from description.", options_page.endpoint) 48 return parse_description(options_page.json['description']) 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/awxkit/awxkit/api/utils.py b/awxkit/awxkit/api/utils.py --- a/awxkit/awxkit/api/utils.py +++ b/awxkit/awxkit/api/utils.py @@ -15,7 +15,12 @@ def parse_description(desc): options = {} - for line in desc[desc.index('POST') :].splitlines(): + desc_lines = [] + if 'POST' in desc: + desc_lines = desc[desc.index('POST') :].splitlines() + else: + desc_lines = desc.splitlines() + for line in desc_lines: match = descRE.match(line) if not match: continue
{"golden_diff": "diff --git a/awxkit/awxkit/api/utils.py b/awxkit/awxkit/api/utils.py\n--- a/awxkit/awxkit/api/utils.py\n+++ b/awxkit/awxkit/api/utils.py\n@@ -15,7 +15,12 @@\n \n def parse_description(desc):\n options = {}\n- for line in desc[desc.index('POST') :].splitlines():\n+ desc_lines = []\n+ if 'POST' in desc:\n+ desc_lines = desc[desc.index('POST') :].splitlines()\n+ else:\n+ desc_lines = desc.splitlines()\n+ for line in desc_lines:\n match = descRE.match(line)\n if not match:\n continue\n", "issue": "Issue on awx.awx.export/import awx cli/collection\n### Please confirm the following\r\n\r\n- [X] I agree to follow this project's [code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html).\r\n- [X] I have checked the [current issues](https://github.com/ansible/awx/issues) for duplicates.\r\n- [X] I understand that AWX is open source software provided for free and that I might not receive a timely response.\r\n- [X] I am **NOT** reporting a (potential) security vulnerability. (These should be emailed to `[email protected]` instead.)\r\n\r\n### Bug Summary\r\n\r\nHi team,\r\nI founded tow bugs related awx cli and collection import / export.\r\n\r\nThe first issue is related export module, that not work if user is a system_auditor (or not have certain admin role in object like schedule.\r\nI already found why this bug is present and proposed a PR: #14626 .\r\n\r\nSecond \"bug\" is related import module (I don't know and don't find if someone decide it) and is related how import will be processed.\r\nActually import perform a `POST`, if object not exists, or a `PUT`, if object exists. In case of we `PUT` an object that already exist api will replace it in all fields, including encrypted key, that in export are removed (correctly).\r\n\r\nSo, i don't know if it's better approach with `PATCH` instead a `PUT`, but I think that here the issue is in the export itself, that will replace value of encrypted key `$encrypted$` with `''` .\r\nThe side effect of \"restore\" `$encrypted$ ` on the export is that we remove it for the POST, due to the fact that is a reseved keyword.\r\n \r\n I will propose a PR also to fix the second bugs\r\n\r\n### AWX version\r\n\r\n23.3.1\r\n\r\n### Select the relevant components\r\n\r\n- [ ] UI\r\n- [ ] UI (tech preview)\r\n- [X] API\r\n- [ ] Docs\r\n- [X] Collection\r\n- [X] CLI\r\n- [ ] Other\r\n\r\n### Installation method\r\n\r\nkubernetes\r\n\r\n### Modifications\r\n\r\nno\r\n\r\n### Ansible version\r\n\r\n_No response_\r\n\r\n### Operating system\r\n\r\n_No response_\r\n\r\n### Web browser\r\n\r\n_No response_\r\n\r\n### Steps to reproduce\r\n\r\nbug 1: execute an export of schedule with a system_auditor\r\n\r\nbug 2: import a credential already present in AWX\r\n\r\n### Expected results\r\n\r\nbug 1: export will go fine\r\n\r\nbug 2: credential will be updated with only fields present in export\r\n\r\n### Actual results\r\n\r\nbug 1: export will fail\r\n\r\nbug 2: credential will be replaced with exported data. But due to the fact that encrypted key are not exported and replaced the value `$encrypted$` with `''` we replace current secrets with `''`\r\n\r\n### Additional information\r\n\r\n_No response_\n", "before_files": [{"content": "import logging\nimport re\n\n\nlog = logging.getLogger(__name__)\n\ndescRE = re.compile(r'^[*] `(\\w+)`: [^(]*\\((\\w+), ([^)]+)\\)')\n\n\ndef freeze(key):\n if key is None:\n return None\n return frozenset((k, freeze(v) if isinstance(v, dict) else v) for k, v in key.items())\n\n\ndef parse_description(desc):\n options = {}\n for line in desc[desc.index('POST') :].splitlines():\n match = descRE.match(line)\n if not match:\n continue\n options[match.group(1)] = {'type': match.group(2), 'required': match.group(3) == 'required'}\n return options\n\n\ndef remove_encrypted(value):\n if value == '$encrypted$':\n return ''\n if isinstance(value, list):\n return [remove_encrypted(item) for item in value]\n if isinstance(value, dict):\n return {k: remove_encrypted(v) for k, v in value.items()}\n return value\n\n\ndef get_post_fields(page, cache):\n options_page = cache.get_options(page)\n if options_page is None:\n return None\n\n if 'POST' not in options_page.r.headers.get('Allow', ''):\n return None\n\n if 'POST' in options_page.json['actions']:\n return options_page.json['actions']['POST']\n else:\n log.warning(\"Insufficient privileges on %s, inferring POST fields from description.\", options_page.endpoint)\n return parse_description(options_page.json['description'])\n", "path": "awxkit/awxkit/api/utils.py"}], "after_files": [{"content": "import logging\nimport re\n\n\nlog = logging.getLogger(__name__)\n\ndescRE = re.compile(r'^[*] `(\\w+)`: [^(]*\\((\\w+), ([^)]+)\\)')\n\n\ndef freeze(key):\n if key is None:\n return None\n return frozenset((k, freeze(v) if isinstance(v, dict) else v) for k, v in key.items())\n\n\ndef parse_description(desc):\n options = {}\n desc_lines = []\n if 'POST' in desc:\n desc_lines = desc[desc.index('POST') :].splitlines()\n else:\n desc_lines = desc.splitlines()\n for line in desc_lines:\n match = descRE.match(line)\n if not match:\n continue\n options[match.group(1)] = {'type': match.group(2), 'required': match.group(3) == 'required'}\n return options\n\n\ndef remove_encrypted(value):\n if value == '$encrypted$':\n return ''\n if isinstance(value, list):\n return [remove_encrypted(item) for item in value]\n if isinstance(value, dict):\n return {k: remove_encrypted(v) for k, v in value.items()}\n return value\n\n\ndef get_post_fields(page, cache):\n options_page = cache.get_options(page)\n if options_page is None:\n return None\n\n if 'POST' not in options_page.r.headers.get('Allow', ''):\n return None\n\n if 'POST' in options_page.json['actions']:\n return options_page.json['actions']['POST']\n else:\n log.warning(\"Insufficient privileges on %s, inferring POST fields from description.\", options_page.endpoint)\n return parse_description(options_page.json['description'])\n", "path": "awxkit/awxkit/api/utils.py"}]}
1,308
165
gh_patches_debug_59177
rasdani/github-patches
git_diff
fossasia__open-event-server-4147
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- IntegrityError: (psycopg2.IntegrityError) column "field_identifier" contains null values https://sentry.eventyay.com/eventyay/api/issues/25/ ``` IntegrityError: (psycopg2.IntegrityError) column "field_identifier" contains null values [SQL: 'ALTER TABLE custom_forms ADD COLUMN field_identifier VARCHAR NOT NULL'] (25 additional frame(s) were not displayed) ... File "sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) IntegrityError: (psycopg2.IntegrityError) column "field_identifier" contains null values [SQL: 'ALTER TABLE custom_forms ADD COLUMN field_identifier VARCHAR NOT NULL'] ``` --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `migrations/versions/aefa134809bf_.py` Content: ``` 1 """empty message 2 3 Revision ID: aefa134809bf 4 Revises: 2b39d8c05788 5 Create Date: 2017-07-21 20:37:50.193436 6 7 """ 8 9 from alembic import op 10 import sqlalchemy as sa 11 import sqlalchemy_utils 12 13 14 # revision identifiers, used by Alembic. 15 revision = 'aefa134809bf' 16 down_revision = '2b39d8c05788' 17 18 19 def upgrade(): 20 # ### commands auto generated by Alembic - please adjust! ### 21 op.add_column('custom_forms', sa.Column('field_identifier', sa.String(), nullable=False)) 22 op.add_column('custom_forms', sa.Column('form', sa.String(), nullable=False)) 23 op.add_column('custom_forms', sa.Column('is_fixed', sa.Boolean(), nullable=True)) 24 op.add_column('custom_forms', sa.Column('is_included', sa.Boolean(), nullable=True)) 25 op.add_column('custom_forms', sa.Column('is_required', sa.Boolean(), nullable=True)) 26 op.add_column('custom_forms', sa.Column('type', sa.String(), nullable=False)) 27 op.create_unique_constraint('custom_form_identifier', 'custom_forms', ['event_id', 'field_identifier', 'form']) 28 op.drop_column('custom_forms', 'speaker_form') 29 op.drop_column('custom_forms', 'session_form') 30 # ### end Alembic commands ### 31 32 33 def downgrade(): 34 # ### commands auto generated by Alembic - please adjust! ### 35 op.add_column('custom_forms', sa.Column('session_form', sa.VARCHAR(), autoincrement=False, nullable=False)) 36 op.add_column('custom_forms', sa.Column('speaker_form', sa.VARCHAR(), autoincrement=False, nullable=False)) 37 op.drop_constraint('custom_form_identifier', 'custom_forms', type_='unique') 38 op.drop_column('custom_forms', 'type') 39 op.drop_column('custom_forms', 'is_required') 40 op.drop_column('custom_forms', 'is_included') 41 op.drop_column('custom_forms', 'is_fixed') 42 op.drop_column('custom_forms', 'form') 43 op.drop_column('custom_forms', 'field_identifier') 44 # ### end Alembic commands ### 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/migrations/versions/aefa134809bf_.py b/migrations/versions/aefa134809bf_.py --- a/migrations/versions/aefa134809bf_.py +++ b/migrations/versions/aefa134809bf_.py @@ -18,6 +18,7 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### + op.execute("DELETE FROM custom_forms") op.add_column('custom_forms', sa.Column('field_identifier', sa.String(), nullable=False)) op.add_column('custom_forms', sa.Column('form', sa.String(), nullable=False)) op.add_column('custom_forms', sa.Column('is_fixed', sa.Boolean(), nullable=True))
{"golden_diff": "diff --git a/migrations/versions/aefa134809bf_.py b/migrations/versions/aefa134809bf_.py\n--- a/migrations/versions/aefa134809bf_.py\n+++ b/migrations/versions/aefa134809bf_.py\n@@ -18,6 +18,7 @@\n \n def upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n+ op.execute(\"DELETE FROM custom_forms\")\n op.add_column('custom_forms', sa.Column('field_identifier', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('form', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('is_fixed', sa.Boolean(), nullable=True))\n", "issue": "IntegrityError: (psycopg2.IntegrityError) column \"field_identifier\" contains null values\nhttps://sentry.eventyay.com/eventyay/api/issues/25/\r\n\r\n```\r\nIntegrityError: (psycopg2.IntegrityError) column \"field_identifier\" contains null values\r\n [SQL: 'ALTER TABLE custom_forms ADD COLUMN field_identifier VARCHAR NOT NULL']\r\n(25 additional frame(s) were not displayed)\r\n...\r\n File \"sqlalchemy/engine/base.py\", line 1189, in _execute_context\r\n context)\r\n File \"sqlalchemy/engine/base.py\", line 1402, in _handle_dbapi_exception\r\n exc_info\r\n File \"sqlalchemy/util/compat.py\", line 203, in raise_from_cause\r\n reraise(type(exception), exception, tb=exc_tb, cause=cause)\r\n File \"sqlalchemy/engine/base.py\", line 1182, in _execute_context\r\n context)\r\n File \"sqlalchemy/engine/default.py\", line 470, in do_execute\r\n cursor.execute(statement, parameters)\r\n\r\nIntegrityError: (psycopg2.IntegrityError) column \"field_identifier\" contains null values\r\n [SQL: 'ALTER TABLE custom_forms ADD COLUMN field_identifier VARCHAR NOT NULL']\r\n```\n", "before_files": [{"content": "\"\"\"empty message\n\nRevision ID: aefa134809bf\nRevises: 2b39d8c05788\nCreate Date: 2017-07-21 20:37:50.193436\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy_utils\n\n\n# revision identifiers, used by Alembic.\nrevision = 'aefa134809bf'\ndown_revision = '2b39d8c05788'\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('custom_forms', sa.Column('field_identifier', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('form', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('is_fixed', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('is_included', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('is_required', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('type', sa.String(), nullable=False))\n op.create_unique_constraint('custom_form_identifier', 'custom_forms', ['event_id', 'field_identifier', 'form'])\n op.drop_column('custom_forms', 'speaker_form')\n op.drop_column('custom_forms', 'session_form')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('custom_forms', sa.Column('session_form', sa.VARCHAR(), autoincrement=False, nullable=False))\n op.add_column('custom_forms', sa.Column('speaker_form', sa.VARCHAR(), autoincrement=False, nullable=False))\n op.drop_constraint('custom_form_identifier', 'custom_forms', type_='unique')\n op.drop_column('custom_forms', 'type')\n op.drop_column('custom_forms', 'is_required')\n op.drop_column('custom_forms', 'is_included')\n op.drop_column('custom_forms', 'is_fixed')\n op.drop_column('custom_forms', 'form')\n op.drop_column('custom_forms', 'field_identifier')\n # ### end Alembic commands ###\n", "path": "migrations/versions/aefa134809bf_.py"}], "after_files": [{"content": "\"\"\"empty message\n\nRevision ID: aefa134809bf\nRevises: 2b39d8c05788\nCreate Date: 2017-07-21 20:37:50.193436\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlalchemy_utils\n\n\n# revision identifiers, used by Alembic.\nrevision = 'aefa134809bf'\ndown_revision = '2b39d8c05788'\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.execute(\"DELETE FROM custom_forms\")\n op.add_column('custom_forms', sa.Column('field_identifier', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('form', sa.String(), nullable=False))\n op.add_column('custom_forms', sa.Column('is_fixed', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('is_included', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('is_required', sa.Boolean(), nullable=True))\n op.add_column('custom_forms', sa.Column('type', sa.String(), nullable=False))\n op.create_unique_constraint('custom_form_identifier', 'custom_forms', ['event_id', 'field_identifier', 'form'])\n op.drop_column('custom_forms', 'speaker_form')\n op.drop_column('custom_forms', 'session_form')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('custom_forms', sa.Column('session_form', sa.VARCHAR(), autoincrement=False, nullable=False))\n op.add_column('custom_forms', sa.Column('speaker_form', sa.VARCHAR(), autoincrement=False, nullable=False))\n op.drop_constraint('custom_form_identifier', 'custom_forms', type_='unique')\n op.drop_column('custom_forms', 'type')\n op.drop_column('custom_forms', 'is_required')\n op.drop_column('custom_forms', 'is_included')\n op.drop_column('custom_forms', 'is_fixed')\n op.drop_column('custom_forms', 'form')\n op.drop_column('custom_forms', 'field_identifier')\n # ### end Alembic commands ###\n", "path": "migrations/versions/aefa134809bf_.py"}]}
1,111
172
gh_patches_debug_18270
rasdani/github-patches
git_diff
dask__distributed-6904
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Importing from distributed shows pyright error **What happened**: When type-checking a program that imports from distributed with pyright, an error is accused: ```python # foo.py from distributed import Client print(Client) ``` ``` pyright foo.py ... /tmp/test-area/foo.py:1:25 - error: "Client" is not exported from module "distributed"   Import from "distributed.client" instead (reportPrivateImportUsage) 1 error, 0 warnings, 0 informations ``` **What you expected to happen**: I expect the package to be correctly typed, following PEP 484 **Anything else we need to know?**: PEP 484 states that > Modules and variables imported into the stub are not considered exported from the stub unless the import uses the `import ... as ... form` or the equivalent `from ... import ... as ... form` and Pyright follows this guideline, although mypy doesn't. **Environment**: - Dask version: 2022.8.0 - Python version: 3.10.5 - Operating System: Arch linux - Install method (conda, pip, source): pip inside an environment --- 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/__init__.py` Content: ``` 1 from __future__ import annotations 2 3 # isort: off 4 from distributed import config # load distributed configuration first 5 from distributed import widgets # load distributed widgets second 6 7 # isort: on 8 9 import atexit 10 11 import dask 12 from dask.config import config # type: ignore 13 14 from distributed._version import get_versions 15 from distributed.actor import Actor, ActorFuture, BaseActorFuture 16 from distributed.client import ( 17 Client, 18 CompatibleExecutor, 19 Future, 20 as_completed, 21 default_client, 22 fire_and_forget, 23 futures_of, 24 get_task_metadata, 25 get_task_stream, 26 performance_report, 27 wait, 28 ) 29 from distributed.core import Status, connect, rpc 30 from distributed.deploy import Adaptive, LocalCluster, SpecCluster, SSHCluster 31 from distributed.diagnostics.plugin import ( 32 Environ, 33 NannyPlugin, 34 PipInstall, 35 SchedulerPlugin, 36 UploadDirectory, 37 UploadFile, 38 WorkerPlugin, 39 ) 40 from distributed.diagnostics.progressbar import progress 41 from distributed.event import Event 42 from distributed.lock import Lock 43 from distributed.multi_lock import MultiLock 44 from distributed.nanny import Nanny 45 from distributed.pubsub import Pub, Sub 46 from distributed.queues import Queue 47 from distributed.scheduler import KilledWorker, Scheduler 48 from distributed.security import Security 49 from distributed.semaphore import Semaphore 50 from distributed.threadpoolexecutor import rejoin 51 from distributed.utils import CancelledError, TimeoutError, sync 52 from distributed.variable import Variable 53 from distributed.worker import ( 54 Reschedule, 55 Worker, 56 get_client, 57 get_worker, 58 print, 59 secede, 60 warn, 61 ) 62 from distributed.worker_client import local_client, worker_client 63 64 65 def __getattr__(name): 66 global __version__, __git_revision__ 67 68 if name == "__version__": 69 from importlib.metadata import version 70 71 __version__ = version("distributed") 72 return __version__ 73 74 if name == "__git_revision__": 75 from distributed._version import get_versions 76 77 __git_revision__ = get_versions()["full-revisionid"] 78 return __git_revision__ 79 80 raise AttributeError(f"module {__name__!r} has no attribute {name!r}") 81 82 83 _python_shutting_down = False 84 85 86 @atexit.register 87 def _(): 88 """Set a global when Python shuts down. 89 90 Note 91 ---- 92 This function must be registered with atexit *after* any class that invokes 93 ``dstributed.utils.is_python_shutting_down`` has been defined. This way it 94 will be called before the ``__del__`` method of those classes. 95 96 See Also 97 -------- 98 distributed.utils.is_python_shutting_down 99 """ 100 global _python_shutting_down 101 _python_shutting_down = True 102 ``` --- 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/__init__.py b/distributed/__init__.py --- a/distributed/__init__.py +++ b/distributed/__init__.py @@ -99,3 +99,65 @@ """ global _python_shutting_down _python_shutting_down = True + + +__all__ = [ + "Actor", + "ActorFuture", + "Adaptive", + "BaseActorFuture", + "CancelledError", + "Client", + "CompatibleExecutor", + "Environ", + "Event", + "Future", + "KilledWorker", + "LocalCluster", + "Lock", + "MultiLock", + "Nanny", + "NannyPlugin", + "PipInstall", + "Pub", + "Queue", + "Reschedule", + "SSHCluster", + "Scheduler", + "SchedulerPlugin", + "Security", + "Semaphore", + "SpecCluster", + "Status", + "Sub", + "TimeoutError", + "UploadDirectory", + "UploadFile", + "Variable", + "Worker", + "WorkerPlugin", + "as_completed", + "config", + "connect", + "dask", + "default_client", + "fire_and_forget", + "futures_of", + "get_client", + "get_task_metadata", + "get_task_stream", + "get_versions", + "get_worker", + "local_client", + "performance_report", + "print", + "progress", + "rejoin", + "rpc", + "secede", + "sync", + "wait", + "warn", + "widgets", + "worker_client", +]
{"golden_diff": "diff --git a/distributed/__init__.py b/distributed/__init__.py\n--- a/distributed/__init__.py\n+++ b/distributed/__init__.py\n@@ -99,3 +99,65 @@\n \"\"\"\n global _python_shutting_down\n _python_shutting_down = True\n+\n+\n+__all__ = [\n+ \"Actor\",\n+ \"ActorFuture\",\n+ \"Adaptive\",\n+ \"BaseActorFuture\",\n+ \"CancelledError\",\n+ \"Client\",\n+ \"CompatibleExecutor\",\n+ \"Environ\",\n+ \"Event\",\n+ \"Future\",\n+ \"KilledWorker\",\n+ \"LocalCluster\",\n+ \"Lock\",\n+ \"MultiLock\",\n+ \"Nanny\",\n+ \"NannyPlugin\",\n+ \"PipInstall\",\n+ \"Pub\",\n+ \"Queue\",\n+ \"Reschedule\",\n+ \"SSHCluster\",\n+ \"Scheduler\",\n+ \"SchedulerPlugin\",\n+ \"Security\",\n+ \"Semaphore\",\n+ \"SpecCluster\",\n+ \"Status\",\n+ \"Sub\",\n+ \"TimeoutError\",\n+ \"UploadDirectory\",\n+ \"UploadFile\",\n+ \"Variable\",\n+ \"Worker\",\n+ \"WorkerPlugin\",\n+ \"as_completed\",\n+ \"config\",\n+ \"connect\",\n+ \"dask\",\n+ \"default_client\",\n+ \"fire_and_forget\",\n+ \"futures_of\",\n+ \"get_client\",\n+ \"get_task_metadata\",\n+ \"get_task_stream\",\n+ \"get_versions\",\n+ \"get_worker\",\n+ \"local_client\",\n+ \"performance_report\",\n+ \"print\",\n+ \"progress\",\n+ \"rejoin\",\n+ \"rpc\",\n+ \"secede\",\n+ \"sync\",\n+ \"wait\",\n+ \"warn\",\n+ \"widgets\",\n+ \"worker_client\",\n+]\n", "issue": "Importing from distributed shows pyright error\n**What happened**:\r\nWhen type-checking a program that imports from distributed with pyright, an error is accused:\r\n\r\n```python\r\n# foo.py\r\nfrom distributed import Client\r\nprint(Client)\r\n```\r\n\r\n```\r\npyright foo.py\r\n...\r\n /tmp/test-area/foo.py:1:25 - error: \"Client\" is not exported from module \"distributed\"\r\n \u00a0\u00a0Import from \"distributed.client\" instead (reportPrivateImportUsage)\r\n1 error, 0 warnings, 0 informations\r\n```\r\n\r\n**What you expected to happen**:\r\nI expect the package to be correctly typed, following PEP 484\r\n\r\n\r\n**Anything else we need to know?**:\r\n\r\nPEP 484 states that\r\n\r\n> Modules and variables imported into the stub are not considered exported from the stub unless the import uses the `import ... as ... form` or the equivalent `from ... import ... as ... form`\r\n\r\nand Pyright follows this guideline, although mypy doesn't.\r\n\r\n**Environment**:\r\n\r\n- Dask version: 2022.8.0\r\n- Python version: 3.10.5\r\n- Operating System: Arch linux\r\n- Install method (conda, pip, source): pip inside an environment\n", "before_files": [{"content": "from __future__ import annotations\n\n# isort: off\nfrom distributed import config # load distributed configuration first\nfrom distributed import widgets # load distributed widgets second\n\n# isort: on\n\nimport atexit\n\nimport dask\nfrom dask.config import config # type: ignore\n\nfrom distributed._version import get_versions\nfrom distributed.actor import Actor, ActorFuture, BaseActorFuture\nfrom distributed.client import (\n Client,\n CompatibleExecutor,\n Future,\n as_completed,\n default_client,\n fire_and_forget,\n futures_of,\n get_task_metadata,\n get_task_stream,\n performance_report,\n wait,\n)\nfrom distributed.core import Status, connect, rpc\nfrom distributed.deploy import Adaptive, LocalCluster, SpecCluster, SSHCluster\nfrom distributed.diagnostics.plugin import (\n Environ,\n NannyPlugin,\n PipInstall,\n SchedulerPlugin,\n UploadDirectory,\n UploadFile,\n WorkerPlugin,\n)\nfrom distributed.diagnostics.progressbar import progress\nfrom distributed.event import Event\nfrom distributed.lock import Lock\nfrom distributed.multi_lock import MultiLock\nfrom distributed.nanny import Nanny\nfrom distributed.pubsub import Pub, Sub\nfrom distributed.queues import Queue\nfrom distributed.scheduler import KilledWorker, Scheduler\nfrom distributed.security import Security\nfrom distributed.semaphore import Semaphore\nfrom distributed.threadpoolexecutor import rejoin\nfrom distributed.utils import CancelledError, TimeoutError, sync\nfrom distributed.variable import Variable\nfrom distributed.worker import (\n Reschedule,\n Worker,\n get_client,\n get_worker,\n print,\n secede,\n warn,\n)\nfrom distributed.worker_client import local_client, worker_client\n\n\ndef __getattr__(name):\n global __version__, __git_revision__\n\n if name == \"__version__\":\n from importlib.metadata import version\n\n __version__ = version(\"distributed\")\n return __version__\n\n if name == \"__git_revision__\":\n from distributed._version import get_versions\n\n __git_revision__ = get_versions()[\"full-revisionid\"]\n return __git_revision__\n\n raise AttributeError(f\"module {__name__!r} has no attribute {name!r}\")\n\n\n_python_shutting_down = False\n\n\[email protected]\ndef _():\n \"\"\"Set a global when Python shuts down.\n\n Note\n ----\n This function must be registered with atexit *after* any class that invokes\n ``dstributed.utils.is_python_shutting_down`` has been defined. This way it\n will be called before the ``__del__`` method of those classes.\n\n See Also\n --------\n distributed.utils.is_python_shutting_down\n \"\"\"\n global _python_shutting_down\n _python_shutting_down = True\n", "path": "distributed/__init__.py"}], "after_files": [{"content": "from __future__ import annotations\n\n# isort: off\nfrom distributed import config # load distributed configuration first\nfrom distributed import widgets # load distributed widgets second\n\n# isort: on\n\nimport atexit\n\nimport dask\nfrom dask.config import config # type: ignore\n\nfrom distributed._version import get_versions\nfrom distributed.actor import Actor, ActorFuture, BaseActorFuture\nfrom distributed.client import (\n Client,\n CompatibleExecutor,\n Future,\n as_completed,\n default_client,\n fire_and_forget,\n futures_of,\n get_task_metadata,\n get_task_stream,\n performance_report,\n wait,\n)\nfrom distributed.core import Status, connect, rpc\nfrom distributed.deploy import Adaptive, LocalCluster, SpecCluster, SSHCluster\nfrom distributed.diagnostics.plugin import (\n Environ,\n NannyPlugin,\n PipInstall,\n SchedulerPlugin,\n UploadDirectory,\n UploadFile,\n WorkerPlugin,\n)\nfrom distributed.diagnostics.progressbar import progress\nfrom distributed.event import Event\nfrom distributed.lock import Lock\nfrom distributed.multi_lock import MultiLock\nfrom distributed.nanny import Nanny\nfrom distributed.pubsub import Pub, Sub\nfrom distributed.queues import Queue\nfrom distributed.scheduler import KilledWorker, Scheduler\nfrom distributed.security import Security\nfrom distributed.semaphore import Semaphore\nfrom distributed.threadpoolexecutor import rejoin\nfrom distributed.utils import CancelledError, TimeoutError, sync\nfrom distributed.variable import Variable\nfrom distributed.worker import (\n Reschedule,\n Worker,\n get_client,\n get_worker,\n print,\n secede,\n warn,\n)\nfrom distributed.worker_client import local_client, worker_client\n\n\ndef __getattr__(name):\n global __version__, __git_revision__\n\n if name == \"__version__\":\n from importlib.metadata import version\n\n __version__ = version(\"distributed\")\n return __version__\n\n if name == \"__git_revision__\":\n from distributed._version import get_versions\n\n __git_revision__ = get_versions()[\"full-revisionid\"]\n return __git_revision__\n\n raise AttributeError(f\"module {__name__!r} has no attribute {name!r}\")\n\n\n_python_shutting_down = False\n\n\[email protected]\ndef _():\n \"\"\"Set a global when Python shuts down.\n\n Note\n ----\n This function must be registered with atexit *after* any class that invokes\n ``dstributed.utils.is_python_shutting_down`` has been defined. This way it\n will be called before the ``__del__`` method of those classes.\n\n See Also\n --------\n distributed.utils.is_python_shutting_down\n \"\"\"\n global _python_shutting_down\n _python_shutting_down = True\n\n\n__all__ = [\n \"Actor\",\n \"ActorFuture\",\n \"Adaptive\",\n \"BaseActorFuture\",\n \"CancelledError\",\n \"Client\",\n \"CompatibleExecutor\",\n \"Environ\",\n \"Event\",\n \"Future\",\n \"KilledWorker\",\n \"LocalCluster\",\n \"Lock\",\n \"MultiLock\",\n \"Nanny\",\n \"NannyPlugin\",\n \"PipInstall\",\n \"Pub\",\n \"Queue\",\n \"Reschedule\",\n \"SSHCluster\",\n \"Scheduler\",\n \"SchedulerPlugin\",\n \"Security\",\n \"Semaphore\",\n \"SpecCluster\",\n \"Status\",\n \"Sub\",\n \"TimeoutError\",\n \"UploadDirectory\",\n \"UploadFile\",\n \"Variable\",\n \"Worker\",\n \"WorkerPlugin\",\n \"as_completed\",\n \"config\",\n \"connect\",\n \"dask\",\n \"default_client\",\n \"fire_and_forget\",\n \"futures_of\",\n \"get_client\",\n \"get_task_metadata\",\n \"get_task_stream\",\n \"get_versions\",\n \"get_worker\",\n \"local_client\",\n \"performance_report\",\n \"print\",\n \"progress\",\n \"rejoin\",\n \"rpc\",\n \"secede\",\n \"sync\",\n \"wait\",\n \"warn\",\n \"widgets\",\n \"worker_client\",\n]\n", "path": "distributed/__init__.py"}]}
1,301
412
gh_patches_debug_8505
rasdani/github-patches
git_diff
Textualize__textual-1552
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Change Clock color Following on from #1411, perhaps the clock colour needs a wee revisit too? ![Screenshot 2022-12-31 at 10 04 46](https://user-images.githubusercontent.com/28237/210132768-00166ecf-0bf3-4486-bc7f-09cc52d46b21.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: `src/textual/widgets/_header.py` Content: ``` 1 from __future__ import annotations 2 3 from datetime import datetime 4 5 from rich.text import Text 6 7 from ..widget import Widget 8 from ..reactive import Reactive, watch 9 10 11 class HeaderIcon(Widget): 12 """Display an 'icon' on the left of the header.""" 13 14 DEFAULT_CSS = """ 15 HeaderIcon { 16 dock: left; 17 padding: 0 1; 18 width: 8; 19 content-align: left middle; 20 } 21 """ 22 icon = Reactive("⭘") 23 24 def render(self): 25 return self.icon 26 27 28 class HeaderClockSpace(Widget): 29 """The space taken up by the clock on the right of the header.""" 30 31 DEFAULT_CSS = """ 32 HeaderClockSpace { 33 dock: right; 34 width: 10; 35 padding: 0 1; 36 } 37 """ 38 39 def render(self) -> str: 40 return "" 41 42 43 class HeaderClock(HeaderClockSpace): 44 """Display a clock on the right of the header.""" 45 46 DEFAULT_CSS = """ 47 HeaderClock { 48 background: $secondary-background-lighten-1; 49 color: $text; 50 text-opacity: 85%; 51 content-align: center middle; 52 } 53 """ 54 55 def on_mount(self) -> None: 56 self.set_interval(1, callback=self.refresh, name=f"update header clock") 57 58 def render(self): 59 return Text(datetime.now().time().strftime("%X")) 60 61 62 class HeaderTitle(Widget): 63 """Display the title / subtitle in the header.""" 64 65 DEFAULT_CSS = """ 66 HeaderTitle { 67 content-align: center middle; 68 width: 100%; 69 } 70 """ 71 72 text: Reactive[str] = Reactive("") 73 sub_text = Reactive("") 74 75 def render(self) -> Text: 76 text = Text(self.text, no_wrap=True, overflow="ellipsis") 77 if self.sub_text: 78 text.append(" — ") 79 text.append(self.sub_text, "dim") 80 return text 81 82 83 class Header(Widget): 84 """A header widget with icon and clock. 85 86 Args: 87 show_clock (bool, optional): True if the clock should be shown on the right of the header. 88 """ 89 90 DEFAULT_CSS = """ 91 Header { 92 dock: top; 93 width: 100%; 94 background: $foreground 5%; 95 color: $text; 96 height: 1; 97 } 98 Header.-tall { 99 height: 3; 100 } 101 """ 102 103 tall = Reactive(False) 104 105 DEFAULT_CLASSES = "" 106 107 def __init__( 108 self, 109 show_clock: bool = False, 110 *, 111 name: str | None = None, 112 id: str | None = None, 113 classes: str | None = None, 114 ): 115 super().__init__(name=name, id=id, classes=classes) 116 self.show_clock = show_clock 117 118 def compose(self): 119 yield HeaderIcon() 120 yield HeaderTitle() 121 yield HeaderClock() if self.show_clock else HeaderClockSpace() 122 123 def watch_tall(self, tall: bool) -> None: 124 self.set_class(tall, "-tall") 125 126 def on_click(self): 127 self.toggle_class("-tall") 128 129 def on_mount(self) -> None: 130 def set_title(title: str) -> None: 131 self.query_one(HeaderTitle).text = title 132 133 def set_sub_title(sub_title: str) -> None: 134 self.query_one(HeaderTitle).sub_text = sub_title 135 136 watch(self.app, "title", set_title) 137 watch(self.app, "sub_title", set_sub_title) 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/src/textual/widgets/_header.py b/src/textual/widgets/_header.py --- a/src/textual/widgets/_header.py +++ b/src/textual/widgets/_header.py @@ -45,7 +45,7 @@ DEFAULT_CSS = """ HeaderClock { - background: $secondary-background-lighten-1; + background: $foreground-darken-1 5%; color: $text; text-opacity: 85%; content-align: center middle; @@ -97,7 +97,7 @@ } Header.-tall { height: 3; - } + } """ tall = Reactive(False)
{"golden_diff": "diff --git a/src/textual/widgets/_header.py b/src/textual/widgets/_header.py\n--- a/src/textual/widgets/_header.py\n+++ b/src/textual/widgets/_header.py\n@@ -45,7 +45,7 @@\n \n DEFAULT_CSS = \"\"\"\n HeaderClock {\n- background: $secondary-background-lighten-1;\n+ background: $foreground-darken-1 5%;\n color: $text;\n text-opacity: 85%;\n content-align: center middle;\n@@ -97,7 +97,7 @@\n }\n Header.-tall {\n height: 3;\n- } \n+ }\n \"\"\"\n \n tall = Reactive(False)\n", "issue": "Change Clock color\nFollowing on from #1411, perhaps the clock colour needs a wee revisit too?\r\n\r\n![Screenshot 2022-12-31 at 10 04 46](https://user-images.githubusercontent.com/28237/210132768-00166ecf-0bf3-4486-bc7f-09cc52d46b21.png)\r\n\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom datetime import datetime\n\nfrom rich.text import Text\n\nfrom ..widget import Widget\nfrom ..reactive import Reactive, watch\n\n\nclass HeaderIcon(Widget):\n \"\"\"Display an 'icon' on the left of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderIcon {\n dock: left;\n padding: 0 1;\n width: 8;\n content-align: left middle;\n }\n \"\"\"\n icon = Reactive(\"\u2b58\")\n\n def render(self):\n return self.icon\n\n\nclass HeaderClockSpace(Widget):\n \"\"\"The space taken up by the clock on the right of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderClockSpace {\n dock: right;\n width: 10;\n padding: 0 1;\n }\n \"\"\"\n\n def render(self) -> str:\n return \"\"\n\n\nclass HeaderClock(HeaderClockSpace):\n \"\"\"Display a clock on the right of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderClock {\n background: $secondary-background-lighten-1;\n color: $text;\n text-opacity: 85%;\n content-align: center middle;\n }\n \"\"\"\n\n def on_mount(self) -> None:\n self.set_interval(1, callback=self.refresh, name=f\"update header clock\")\n\n def render(self):\n return Text(datetime.now().time().strftime(\"%X\"))\n\n\nclass HeaderTitle(Widget):\n \"\"\"Display the title / subtitle in the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderTitle {\n content-align: center middle;\n width: 100%;\n }\n \"\"\"\n\n text: Reactive[str] = Reactive(\"\")\n sub_text = Reactive(\"\")\n\n def render(self) -> Text:\n text = Text(self.text, no_wrap=True, overflow=\"ellipsis\")\n if self.sub_text:\n text.append(\" \u2014 \")\n text.append(self.sub_text, \"dim\")\n return text\n\n\nclass Header(Widget):\n \"\"\"A header widget with icon and clock.\n\n Args:\n show_clock (bool, optional): True if the clock should be shown on the right of the header.\n \"\"\"\n\n DEFAULT_CSS = \"\"\"\n Header {\n dock: top;\n width: 100%;\n background: $foreground 5%;\n color: $text;\n height: 1;\n }\n Header.-tall {\n height: 3;\n } \n \"\"\"\n\n tall = Reactive(False)\n\n DEFAULT_CLASSES = \"\"\n\n def __init__(\n self,\n show_clock: bool = False,\n *,\n name: str | None = None,\n id: str | None = None,\n classes: str | None = None,\n ):\n super().__init__(name=name, id=id, classes=classes)\n self.show_clock = show_clock\n\n def compose(self):\n yield HeaderIcon()\n yield HeaderTitle()\n yield HeaderClock() if self.show_clock else HeaderClockSpace()\n\n def watch_tall(self, tall: bool) -> None:\n self.set_class(tall, \"-tall\")\n\n def on_click(self):\n self.toggle_class(\"-tall\")\n\n def on_mount(self) -> None:\n def set_title(title: str) -> None:\n self.query_one(HeaderTitle).text = title\n\n def set_sub_title(sub_title: str) -> None:\n self.query_one(HeaderTitle).sub_text = sub_title\n\n watch(self.app, \"title\", set_title)\n watch(self.app, \"sub_title\", set_sub_title)\n", "path": "src/textual/widgets/_header.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom datetime import datetime\n\nfrom rich.text import Text\n\nfrom ..widget import Widget\nfrom ..reactive import Reactive, watch\n\n\nclass HeaderIcon(Widget):\n \"\"\"Display an 'icon' on the left of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderIcon {\n dock: left;\n padding: 0 1;\n width: 8;\n content-align: left middle;\n }\n \"\"\"\n icon = Reactive(\"\u2b58\")\n\n def render(self):\n return self.icon\n\n\nclass HeaderClockSpace(Widget):\n \"\"\"The space taken up by the clock on the right of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderClockSpace {\n dock: right;\n width: 10;\n padding: 0 1;\n }\n \"\"\"\n\n def render(self) -> str:\n return \"\"\n\n\nclass HeaderClock(HeaderClockSpace):\n \"\"\"Display a clock on the right of the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderClock {\n background: $foreground-darken-1 5%;\n color: $text;\n text-opacity: 85%;\n content-align: center middle;\n }\n \"\"\"\n\n def on_mount(self) -> None:\n self.set_interval(1, callback=self.refresh, name=f\"update header clock\")\n\n def render(self):\n return Text(datetime.now().time().strftime(\"%X\"))\n\n\nclass HeaderTitle(Widget):\n \"\"\"Display the title / subtitle in the header.\"\"\"\n\n DEFAULT_CSS = \"\"\"\n HeaderTitle {\n content-align: center middle;\n width: 100%;\n }\n \"\"\"\n\n text: Reactive[str] = Reactive(\"\")\n sub_text = Reactive(\"\")\n\n def render(self) -> Text:\n text = Text(self.text, no_wrap=True, overflow=\"ellipsis\")\n if self.sub_text:\n text.append(\" \u2014 \")\n text.append(self.sub_text, \"dim\")\n return text\n\n\nclass Header(Widget):\n \"\"\"A header widget with icon and clock.\n\n Args:\n show_clock (bool, optional): True if the clock should be shown on the right of the header.\n \"\"\"\n\n DEFAULT_CSS = \"\"\"\n Header {\n dock: top;\n width: 100%;\n background: $foreground 5%;\n color: $text;\n height: 1;\n }\n Header.-tall {\n height: 3;\n }\n \"\"\"\n\n tall = Reactive(False)\n\n DEFAULT_CLASSES = \"\"\n\n def __init__(\n self,\n show_clock: bool = False,\n *,\n name: str | None = None,\n id: str | None = None,\n classes: str | None = None,\n ):\n super().__init__(name=name, id=id, classes=classes)\n self.show_clock = show_clock\n\n def compose(self):\n yield HeaderIcon()\n yield HeaderTitle()\n yield HeaderClock() if self.show_clock else HeaderClockSpace()\n\n def watch_tall(self, tall: bool) -> None:\n self.set_class(tall, \"-tall\")\n\n def on_click(self):\n self.toggle_class(\"-tall\")\n\n def on_mount(self) -> None:\n def set_title(title: str) -> None:\n self.query_one(HeaderTitle).text = title\n\n def set_sub_title(sub_title: str) -> None:\n self.query_one(HeaderTitle).sub_text = sub_title\n\n watch(self.app, \"title\", set_title)\n watch(self.app, \"sub_title\", set_sub_title)\n", "path": "src/textual/widgets/_header.py"}]}
1,438
150
gh_patches_debug_642
rasdani/github-patches
git_diff
pex-tool__pex-2062
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Release 2.1.123 On the docket: + [x] Create lockfile for xmlsec fails #2063 + [x] Internal not enough values to unpack error for pex3 lock create 'pip @ https://github.com/pypa/pip/archive/22.0.2.zip' ... #2057 + [x] Pex lock creation does not handle wheels with non {cp,pp,py} pyver tag. #2059 --- 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.122" 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.122" +__version__ = "2.1.123"
{"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.122\"\n+__version__ = \"2.1.123\"\n", "issue": "Release 2.1.123\nOn the docket:\r\n+ [x] Create lockfile for xmlsec fails #2063\r\n+ [x] Internal not enough values to unpack error for pex3 lock create 'pip @ https://github.com/pypa/pip/archive/22.0.2.zip' ... #2057\r\n+ [x] Pex lock creation does not handle wheels with non {cp,pp,py} pyver tag. #2059\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.122\"\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.123\"\n", "path": "pex/version.py"}]}
417
98
gh_patches_debug_14865
rasdani/github-patches
git_diff
spacetelescope__jwql-419
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Make JWQL pip installable Currently our `jwql` package is only installable by cloning the repository and running `setup.py`. It would be easier for users (and perhaps easier for us when distributing our code (#294)) if it were also uploaded to PyPI and `pip` installable. --- 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.20.0' 6 7 AUTHORS = 'Matthew Bourque, Sara Ogaz, Joe Filippazzo, Bryan Hilbert, Misty Cracraft, ' 8 AUTHORS += 'Graham Kanarek, Johannes Sahlmann, Lauren Chambers, Catherine Martlin' 9 10 REQUIRES = [ 11 'astropy', 12 'astroquery>=0.3.9', 13 'authlib', 14 'bokeh>=1.0', 15 'django>=2.0', 16 'jinja2', 17 'jwedb', 18 'jwst', 19 'matplotlib', 20 'numpy', 21 'numpydoc', 22 'pandas', 23 'psycopg2', 24 'pysiaf', 25 'pytest', 26 'sphinx', 27 'sqlalchemy', 28 'stsci_rtd_theme' 29 ] 30 31 setup( 32 name='jwql', 33 version=VERSION, 34 description='The JWST Quicklook Project', 35 url='https://github.com/spacetelescope/jwql.git', 36 author=AUTHORS, 37 author_email='[email protected]', 38 license='BSD', 39 keywords=['astronomy', 'python'], 40 classifiers=['Programming Language :: Python'], 41 packages=find_packages(), 42 install_requires=REQUIRES, 43 include_package_data=True, 44 include_dirs=[np.get_include()], 45 ) 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/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,8 +4,10 @@ VERSION = '0.20.0' -AUTHORS = 'Matthew Bourque, Sara Ogaz, Joe Filippazzo, Bryan Hilbert, Misty Cracraft, ' -AUTHORS += 'Graham Kanarek, Johannes Sahlmann, Lauren Chambers, Catherine Martlin' +AUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Joe Filippazzo, Bryan Hilbert, ' +AUTHORS += 'Graham Kanarek, Catherine Martlin, Johannes Sahlmann' + +DESCRIPTION = 'The James Webb Space Telescope Quicklook Project' REQUIRES = [ 'astropy', @@ -31,7 +33,7 @@ setup( name='jwql', version=VERSION, - description='The JWST Quicklook Project', + description=DESCRIPTION, url='https://github.com/spacetelescope/jwql.git', author=AUTHORS, author_email='[email protected]',
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -4,8 +4,10 @@\n \n VERSION = '0.20.0'\n \n-AUTHORS = 'Matthew Bourque, Sara Ogaz, Joe Filippazzo, Bryan Hilbert, Misty Cracraft, '\n-AUTHORS += 'Graham Kanarek, Johannes Sahlmann, Lauren Chambers, Catherine Martlin'\n+AUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Joe Filippazzo, Bryan Hilbert, '\n+AUTHORS += 'Graham Kanarek, Catherine Martlin, Johannes Sahlmann'\n+\n+DESCRIPTION = 'The James Webb Space Telescope Quicklook Project'\n \n REQUIRES = [\n 'astropy',\n@@ -31,7 +33,7 @@\n setup(\n name='jwql',\n version=VERSION,\n- description='The JWST Quicklook Project',\n+ description=DESCRIPTION,\n url='https://github.com/spacetelescope/jwql.git',\n author=AUTHORS,\n author_email='[email protected]',\n", "issue": "Make JWQL pip installable\nCurrently our `jwql` package is only installable by cloning the repository and running `setup.py`. It would be easier for users (and perhaps easier for us when distributing our code (#294)) if it were also uploaded to PyPI and `pip` installable. \n", "before_files": [{"content": "import numpy as np\nfrom setuptools import setup\nfrom setuptools import find_packages\n\nVERSION = '0.20.0'\n\nAUTHORS = 'Matthew Bourque, Sara Ogaz, Joe Filippazzo, Bryan Hilbert, Misty Cracraft, '\nAUTHORS += 'Graham Kanarek, Johannes Sahlmann, Lauren Chambers, Catherine Martlin'\n\nREQUIRES = [\n 'astropy',\n 'astroquery>=0.3.9',\n 'authlib',\n 'bokeh>=1.0',\n 'django>=2.0',\n 'jinja2',\n 'jwedb',\n 'jwst',\n 'matplotlib',\n 'numpy',\n 'numpydoc',\n 'pandas',\n 'psycopg2',\n 'pysiaf',\n 'pytest',\n 'sphinx',\n 'sqlalchemy',\n 'stsci_rtd_theme'\n]\n\nsetup(\n name='jwql',\n version=VERSION,\n description='The JWST Quicklook Project',\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 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.20.0'\n\nAUTHORS = 'Matthew Bourque, Lauren Chambers, Misty Cracraft, Joe Filippazzo, Bryan Hilbert, '\nAUTHORS += 'Graham Kanarek, Catherine Martlin, Johannes Sahlmann'\n\nDESCRIPTION = 'The James Webb Space Telescope Quicklook Project'\n\nREQUIRES = [\n 'astropy',\n 'astroquery>=0.3.9',\n 'authlib',\n 'bokeh>=1.0',\n 'django>=2.0',\n 'jinja2',\n 'jwedb',\n 'jwst',\n 'matplotlib',\n 'numpy',\n 'numpydoc',\n 'pandas',\n 'psycopg2',\n 'pysiaf',\n 'pytest',\n 'sphinx',\n 'sqlalchemy',\n 'stsci_rtd_theme'\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 include_package_data=True,\n include_dirs=[np.get_include()],\n)\n", "path": "setup.py"}]}
705
244
gh_patches_debug_1991
rasdani/github-patches
git_diff
pypi__warehouse-3056
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Disable 'delete confirm' button until confirmation word is correct We currently have a modal on `warehouse/templates/manage/settings.html`, that allows the user to confirm that they want to delete their project: ![screenshot from 2018-02-03 14-43-29](https://user-images.githubusercontent.com/3323703/35768242-9dcfc21a-08f0-11e8-834d-fdcc3e6cd998.png) The user is required to enter the project name as an extra security measure. If they get it wrong, we show them this error: ![screenshot from 2018-02-03 14-44-19](https://user-images.githubusercontent.com/3323703/35768249-bba976d2-08f0-11e8-97ba-99c37bfc7479.png) ## Proposal It would be really nice if we could `disable` the delete button until the correct project name is given, e.g. ![screenshot from 2018-02-03 14-46-02](https://user-images.githubusercontent.com/3323703/35768271-fa2cdc64-08f0-11e8-848f-58433e60ae6b.png) ![screenshot from 2018-02-03 14-46-25](https://user-images.githubusercontent.com/3323703/35768274-0692bca8-08f1-11e8-9149-3aa7a5faad65.png) ## Notes We will have several other delete confirmation modals on other pages, sometimes with multiple modals on a single page (e.g. delete release, delete file) - so the code will need to be written to take this into account. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `warehouse/utils/project.py` Content: ``` 1 # Licensed under the Apache License, Version 2.0 (the "License"); 2 # you may not use this file except in compliance with the License. 3 # You may obtain a copy of the License at 4 # 5 # http://www.apache.org/licenses/LICENSE-2.0 6 # 7 # Unless required by applicable law or agreed to in writing, software 8 # distributed under the License is distributed on an "AS IS" BASIS, 9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 # See the License for the specific language governing permissions and 11 # limitations under the License. 12 13 from packaging.utils import canonicalize_name 14 from pyramid.httpexceptions import HTTPSeeOther 15 16 from warehouse.packaging.models import ( 17 Release, Dependency, File, Role, JournalEntry, release_classifiers 18 ) 19 20 21 def confirm_project(project, request, fail_route): 22 confirm = request.POST.get("confirm") 23 project_name = project.normalized_name 24 if not confirm: 25 request.session.flash( 26 "Must confirm the request.", 27 queue="error", 28 ) 29 raise HTTPSeeOther( 30 request.route_path(fail_route, project_name=project_name) 31 ) 32 if canonicalize_name(confirm) != project.normalized_name: 33 request.session.flash( 34 "Could not delete project - " + 35 f"{confirm!r} is not the same as {project.normalized_name!r}", 36 queue="error", 37 ) 38 raise HTTPSeeOther( 39 request.route_path(fail_route, project_name=project_name) 40 ) 41 42 43 def remove_project(project, request, flash=True): 44 # TODO: We don't actually delete files from the data store. We should add 45 # some kind of garbage collection at some point. 46 47 request.db.add( 48 JournalEntry( 49 name=project.name, 50 action="remove", 51 submitted_by=request.user, 52 submitted_from=request.remote_addr, 53 ) 54 ) 55 request.db.query(Role).filter(Role.project == project).delete() 56 request.db.query(File).filter(File.name == project.name).delete() 57 (request.db.query(Dependency).filter(Dependency.name == project.name) 58 .delete()) 59 (request.db.execute(release_classifiers.delete() 60 .where(release_classifiers.c.name == 61 project.name))) 62 63 # Load the following objects into the session and individually delete them 64 # so they are included in `session.deleted` and their cache keys are purged 65 66 # Delete releases first, otherwise they will get cascade-deleted by the 67 # project deletion and won't be purged 68 for release in ( 69 request.db.query(Release) 70 .filter(Release.project == project) 71 .all()): 72 request.db.delete(release) 73 74 # Finally, delete the project 75 request.db.delete(project) 76 77 # Flush so we can repeat this multiple times if necessary 78 request.db.flush() 79 80 if flash: 81 request.session.flash( 82 f"Successfully deleted the project {project.name!r}.", 83 queue="success", 84 ) 85 ``` --- 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/warehouse/utils/project.py b/warehouse/utils/project.py --- a/warehouse/utils/project.py +++ b/warehouse/utils/project.py @@ -19,7 +19,7 @@ def confirm_project(project, request, fail_route): - confirm = request.POST.get("confirm") + confirm = request.POST.get("confirm_project_name") project_name = project.normalized_name if not confirm: request.session.flash(
{"golden_diff": "diff --git a/warehouse/utils/project.py b/warehouse/utils/project.py\n--- a/warehouse/utils/project.py\n+++ b/warehouse/utils/project.py\n@@ -19,7 +19,7 @@\n \n \n def confirm_project(project, request, fail_route):\n- confirm = request.POST.get(\"confirm\")\n+ confirm = request.POST.get(\"confirm_project_name\")\n project_name = project.normalized_name\n if not confirm:\n request.session.flash(\n", "issue": "Disable 'delete confirm' button until confirmation word is correct\nWe currently have a modal on `warehouse/templates/manage/settings.html`, that allows the user to confirm that they want to delete their project:\r\n\r\n![screenshot from 2018-02-03 14-43-29](https://user-images.githubusercontent.com/3323703/35768242-9dcfc21a-08f0-11e8-834d-fdcc3e6cd998.png)\r\n\r\nThe user is required to enter the project name as an extra security measure. If they get it wrong, we show them this error:\r\n\r\n![screenshot from 2018-02-03 14-44-19](https://user-images.githubusercontent.com/3323703/35768249-bba976d2-08f0-11e8-97ba-99c37bfc7479.png)\r\n\r\n## Proposal\r\n\r\nIt would be really nice if we could `disable` the delete button until the correct project name is given, e.g.\r\n\r\n![screenshot from 2018-02-03 14-46-02](https://user-images.githubusercontent.com/3323703/35768271-fa2cdc64-08f0-11e8-848f-58433e60ae6b.png)\r\n\r\n![screenshot from 2018-02-03 14-46-25](https://user-images.githubusercontent.com/3323703/35768274-0692bca8-08f1-11e8-9149-3aa7a5faad65.png)\r\n\r\n## Notes\r\n\r\nWe will have several other delete confirmation modals on other pages, sometimes with multiple modals on a single page (e.g. delete release, delete file) - so the code will need to be written to take this into account.\r\n\n", "before_files": [{"content": "# 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 packaging.utils import canonicalize_name\nfrom pyramid.httpexceptions import HTTPSeeOther\n\nfrom warehouse.packaging.models import (\n Release, Dependency, File, Role, JournalEntry, release_classifiers\n)\n\n\ndef confirm_project(project, request, fail_route):\n confirm = request.POST.get(\"confirm\")\n project_name = project.normalized_name\n if not confirm:\n request.session.flash(\n \"Must confirm the request.\",\n queue=\"error\",\n )\n raise HTTPSeeOther(\n request.route_path(fail_route, project_name=project_name)\n )\n if canonicalize_name(confirm) != project.normalized_name:\n request.session.flash(\n \"Could not delete project - \" +\n f\"{confirm!r} is not the same as {project.normalized_name!r}\",\n queue=\"error\",\n )\n raise HTTPSeeOther(\n request.route_path(fail_route, project_name=project_name)\n )\n\n\ndef remove_project(project, request, flash=True):\n # TODO: We don't actually delete files from the data store. We should add\n # some kind of garbage collection at some point.\n\n request.db.add(\n JournalEntry(\n name=project.name,\n action=\"remove\",\n submitted_by=request.user,\n submitted_from=request.remote_addr,\n )\n )\n request.db.query(Role).filter(Role.project == project).delete()\n request.db.query(File).filter(File.name == project.name).delete()\n (request.db.query(Dependency).filter(Dependency.name == project.name)\n .delete())\n (request.db.execute(release_classifiers.delete()\n .where(release_classifiers.c.name ==\n project.name)))\n\n # Load the following objects into the session and individually delete them\n # so they are included in `session.deleted` and their cache keys are purged\n\n # Delete releases first, otherwise they will get cascade-deleted by the\n # project deletion and won't be purged\n for release in (\n request.db.query(Release)\n .filter(Release.project == project)\n .all()):\n request.db.delete(release)\n\n # Finally, delete the project\n request.db.delete(project)\n\n # Flush so we can repeat this multiple times if necessary\n request.db.flush()\n\n if flash:\n request.session.flash(\n f\"Successfully deleted the project {project.name!r}.\",\n queue=\"success\",\n )\n", "path": "warehouse/utils/project.py"}], "after_files": [{"content": "# 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 packaging.utils import canonicalize_name\nfrom pyramid.httpexceptions import HTTPSeeOther\n\nfrom warehouse.packaging.models import (\n Release, Dependency, File, Role, JournalEntry, release_classifiers\n)\n\n\ndef confirm_project(project, request, fail_route):\n confirm = request.POST.get(\"confirm_project_name\")\n project_name = project.normalized_name\n if not confirm:\n request.session.flash(\n \"Must confirm the request.\",\n queue=\"error\",\n )\n raise HTTPSeeOther(\n request.route_path(fail_route, project_name=project_name)\n )\n if canonicalize_name(confirm) != project.normalized_name:\n request.session.flash(\n \"Could not delete project - \" +\n f\"{confirm!r} is not the same as {project.normalized_name!r}\",\n queue=\"error\",\n )\n raise HTTPSeeOther(\n request.route_path(fail_route, project_name=project_name)\n )\n\n\ndef remove_project(project, request, flash=True):\n # TODO: We don't actually delete files from the data store. We should add\n # some kind of garbage collection at some point.\n\n request.db.add(\n JournalEntry(\n name=project.name,\n action=\"remove\",\n submitted_by=request.user,\n submitted_from=request.remote_addr,\n )\n )\n request.db.query(Role).filter(Role.project == project).delete()\n request.db.query(File).filter(File.name == project.name).delete()\n (request.db.query(Dependency).filter(Dependency.name == project.name)\n .delete())\n (request.db.execute(release_classifiers.delete()\n .where(release_classifiers.c.name ==\n project.name)))\n\n # Load the following objects into the session and individually delete them\n # so they are included in `session.deleted` and their cache keys are purged\n\n # Delete releases first, otherwise they will get cascade-deleted by the\n # project deletion and won't be purged\n for release in (\n request.db.query(Release)\n .filter(Release.project == project)\n .all()):\n request.db.delete(release)\n\n # Finally, delete the project\n request.db.delete(project)\n\n # Flush so we can repeat this multiple times if necessary\n request.db.flush()\n\n if flash:\n request.session.flash(\n f\"Successfully deleted the project {project.name!r}.\",\n queue=\"success\",\n )\n", "path": "warehouse/utils/project.py"}]}
1,520
95
gh_patches_debug_7415
rasdani/github-patches
git_diff
fonttools__fonttools-2439
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- ReemKufiInk crashes pyftsubset ``` pyftsubset --text=duck --output-file=/tmp/reem.otf ReemKufiInk-Bold.otf Traceback (most recent call last): File "/tmp/venv/bin/pyftsubset", line 8, in <module> sys.exit(main()) File "/tmp/venv/lib/python3.9/site-packages/fontTools/misc/loggingTools.py", line 372, in wrapper return func(*args, **kwds) File "/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py", line 3104, in main subsetter.subset(font) File "/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py", line 2908, in subset self._subset_glyphs(font) File "/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py", line 2846, in _subset_glyphs retain = table.subset_glyphs(self) File "/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py", line 2086, in subset_glyphs colorGlyphsV1 = unbuildColrV1(self.table.LayerList, self.table.BaseGlyphList) File "/tmp/venv/lib/python3.9/site-packages/fontTools/colorLib/unbuilder.py", line 6, in unbuildColrV1 unbuilder = LayerListUnbuilder(layerV1List.Paint) AttributeError: 'NoneType' object has no attribute 'Paint' ``` TTX handles the font just fine. File from https://github.com/aliftype/reem-kufi/commits/colr-v1 at 93d6dcd693ae42bb4295701e88a07cc4d04db73c --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `Lib/fontTools/colorLib/unbuilder.py` Content: ``` 1 from fontTools.ttLib.tables import otTables as ot 2 from .table_builder import TableUnbuilder 3 4 5 def unbuildColrV1(layerV1List, baseGlyphV1List): 6 unbuilder = LayerListUnbuilder(layerV1List.Paint) 7 return { 8 rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint) 9 for rec in baseGlyphV1List.BaseGlyphPaintRecord 10 } 11 12 13 def _flatten(lst): 14 for el in lst: 15 if isinstance(el, list): 16 yield from _flatten(el) 17 else: 18 yield el 19 20 21 class LayerListUnbuilder: 22 def __init__(self, layers): 23 self.layers = layers 24 25 callbacks = { 26 ( 27 ot.Paint, 28 ot.PaintFormat.PaintColrLayers, 29 ): self._unbuildPaintColrLayers, 30 } 31 self.tableUnbuilder = TableUnbuilder(callbacks) 32 33 def unbuildPaint(self, paint): 34 assert isinstance(paint, ot.Paint) 35 return self.tableUnbuilder.unbuild(paint) 36 37 def _unbuildPaintColrLayers(self, source): 38 assert source["Format"] == ot.PaintFormat.PaintColrLayers 39 40 layers = list( 41 _flatten( 42 [ 43 self.unbuildPaint(childPaint) 44 for childPaint in self.layers[ 45 source["FirstLayerIndex"] : source["FirstLayerIndex"] 46 + source["NumLayers"] 47 ] 48 ] 49 ) 50 ) 51 52 if len(layers) == 1: 53 return layers[0] 54 55 return {"Format": source["Format"], "Layers": layers} 56 57 58 if __name__ == "__main__": 59 from pprint import pprint 60 import sys 61 from fontTools.ttLib import TTFont 62 63 try: 64 fontfile = sys.argv[1] 65 except IndexError: 66 sys.exit("usage: fonttools colorLib.unbuilder FONTFILE") 67 68 font = TTFont(fontfile) 69 colr = font["COLR"] 70 if colr.version < 1: 71 sys.exit(f"error: No COLR table version=1 found in {fontfile}") 72 73 colorGlyphs = unbuildColrV1( 74 colr.table.LayerList, 75 colr.table.BaseGlyphList, 76 ignoreVarIdx=not colr.table.VarStore, 77 ) 78 79 pprint(colorGlyphs) 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/Lib/fontTools/colorLib/unbuilder.py b/Lib/fontTools/colorLib/unbuilder.py --- a/Lib/fontTools/colorLib/unbuilder.py +++ b/Lib/fontTools/colorLib/unbuilder.py @@ -2,11 +2,14 @@ from .table_builder import TableUnbuilder -def unbuildColrV1(layerV1List, baseGlyphV1List): - unbuilder = LayerListUnbuilder(layerV1List.Paint) +def unbuildColrV1(layerList, baseGlyphList): + layers = [] + if layerList: + layers = layerList.Paint + unbuilder = LayerListUnbuilder(layers) return { rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint) - for rec in baseGlyphV1List.BaseGlyphPaintRecord + for rec in baseGlyphList.BaseGlyphPaintRecord }
{"golden_diff": "diff --git a/Lib/fontTools/colorLib/unbuilder.py b/Lib/fontTools/colorLib/unbuilder.py\n--- a/Lib/fontTools/colorLib/unbuilder.py\n+++ b/Lib/fontTools/colorLib/unbuilder.py\n@@ -2,11 +2,14 @@\n from .table_builder import TableUnbuilder\n \n \n-def unbuildColrV1(layerV1List, baseGlyphV1List):\n- unbuilder = LayerListUnbuilder(layerV1List.Paint)\n+def unbuildColrV1(layerList, baseGlyphList):\n+ layers = []\n+ if layerList:\n+ layers = layerList.Paint\n+ unbuilder = LayerListUnbuilder(layers)\n return {\n rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)\n- for rec in baseGlyphV1List.BaseGlyphPaintRecord\n+ for rec in baseGlyphList.BaseGlyphPaintRecord\n }\n", "issue": "ReemKufiInk crashes pyftsubset\n```\r\npyftsubset --text=duck --output-file=/tmp/reem.otf ReemKufiInk-Bold.otf\r\n\r\nTraceback (most recent call last):\r\n File \"/tmp/venv/bin/pyftsubset\", line 8, in <module>\r\n sys.exit(main())\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/misc/loggingTools.py\", line 372, in wrapper\r\n return func(*args, **kwds)\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py\", line 3104, in main\r\n subsetter.subset(font)\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py\", line 2908, in subset\r\n self._subset_glyphs(font)\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py\", line 2846, in _subset_glyphs\r\n retain = table.subset_glyphs(self)\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/subset/__init__.py\", line 2086, in subset_glyphs\r\n colorGlyphsV1 = unbuildColrV1(self.table.LayerList, self.table.BaseGlyphList)\r\n File \"/tmp/venv/lib/python3.9/site-packages/fontTools/colorLib/unbuilder.py\", line 6, in unbuildColrV1\r\n unbuilder = LayerListUnbuilder(layerV1List.Paint)\r\nAttributeError: 'NoneType' object has no attribute 'Paint'\r\n```\r\n\r\nTTX handles the font just fine. File from https://github.com/aliftype/reem-kufi/commits/colr-v1 at 93d6dcd693ae42bb4295701e88a07cc4d04db73c\n", "before_files": [{"content": "from fontTools.ttLib.tables import otTables as ot\nfrom .table_builder import TableUnbuilder\n\n\ndef unbuildColrV1(layerV1List, baseGlyphV1List):\n unbuilder = LayerListUnbuilder(layerV1List.Paint)\n return {\n rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)\n for rec in baseGlyphV1List.BaseGlyphPaintRecord\n }\n\n\ndef _flatten(lst):\n for el in lst:\n if isinstance(el, list):\n yield from _flatten(el)\n else:\n yield el\n\n\nclass LayerListUnbuilder:\n def __init__(self, layers):\n self.layers = layers\n\n callbacks = {\n (\n ot.Paint,\n ot.PaintFormat.PaintColrLayers,\n ): self._unbuildPaintColrLayers,\n }\n self.tableUnbuilder = TableUnbuilder(callbacks)\n\n def unbuildPaint(self, paint):\n assert isinstance(paint, ot.Paint)\n return self.tableUnbuilder.unbuild(paint)\n\n def _unbuildPaintColrLayers(self, source):\n assert source[\"Format\"] == ot.PaintFormat.PaintColrLayers\n\n layers = list(\n _flatten(\n [\n self.unbuildPaint(childPaint)\n for childPaint in self.layers[\n source[\"FirstLayerIndex\"] : source[\"FirstLayerIndex\"]\n + source[\"NumLayers\"]\n ]\n ]\n )\n )\n\n if len(layers) == 1:\n return layers[0]\n\n return {\"Format\": source[\"Format\"], \"Layers\": layers}\n\n\nif __name__ == \"__main__\":\n from pprint import pprint\n import sys\n from fontTools.ttLib import TTFont\n\n try:\n fontfile = sys.argv[1]\n except IndexError:\n sys.exit(\"usage: fonttools colorLib.unbuilder FONTFILE\")\n\n font = TTFont(fontfile)\n colr = font[\"COLR\"]\n if colr.version < 1:\n sys.exit(f\"error: No COLR table version=1 found in {fontfile}\")\n\n colorGlyphs = unbuildColrV1(\n colr.table.LayerList,\n colr.table.BaseGlyphList,\n ignoreVarIdx=not colr.table.VarStore,\n )\n\n pprint(colorGlyphs)\n", "path": "Lib/fontTools/colorLib/unbuilder.py"}], "after_files": [{"content": "from fontTools.ttLib.tables import otTables as ot\nfrom .table_builder import TableUnbuilder\n\n\ndef unbuildColrV1(layerList, baseGlyphList):\n layers = []\n if layerList:\n layers = layerList.Paint\n unbuilder = LayerListUnbuilder(layers)\n return {\n rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)\n for rec in baseGlyphList.BaseGlyphPaintRecord\n }\n\n\ndef _flatten(lst):\n for el in lst:\n if isinstance(el, list):\n yield from _flatten(el)\n else:\n yield el\n\n\nclass LayerListUnbuilder:\n def __init__(self, layers):\n self.layers = layers\n\n callbacks = {\n (\n ot.Paint,\n ot.PaintFormat.PaintColrLayers,\n ): self._unbuildPaintColrLayers,\n }\n self.tableUnbuilder = TableUnbuilder(callbacks)\n\n def unbuildPaint(self, paint):\n assert isinstance(paint, ot.Paint)\n return self.tableUnbuilder.unbuild(paint)\n\n def _unbuildPaintColrLayers(self, source):\n assert source[\"Format\"] == ot.PaintFormat.PaintColrLayers\n\n layers = list(\n _flatten(\n [\n self.unbuildPaint(childPaint)\n for childPaint in self.layers[\n source[\"FirstLayerIndex\"] : source[\"FirstLayerIndex\"]\n + source[\"NumLayers\"]\n ]\n ]\n )\n )\n\n if len(layers) == 1:\n return layers[0]\n\n return {\"Format\": source[\"Format\"], \"Layers\": layers}\n\n\nif __name__ == \"__main__\":\n from pprint import pprint\n import sys\n from fontTools.ttLib import TTFont\n\n try:\n fontfile = sys.argv[1]\n except IndexError:\n sys.exit(\"usage: fonttools colorLib.unbuilder FONTFILE\")\n\n font = TTFont(fontfile)\n colr = font[\"COLR\"]\n if colr.version < 1:\n sys.exit(f\"error: No COLR table version=1 found in {fontfile}\")\n\n colorGlyphs = unbuildColrV1(\n colr.table.LayerList,\n colr.table.BaseGlyphList,\n ignoreVarIdx=not colr.table.VarStore,\n )\n\n pprint(colorGlyphs)\n", "path": "Lib/fontTools/colorLib/unbuilder.py"}]}
1,339
194
gh_patches_debug_6818
rasdani/github-patches
git_diff
sbi-dev__sbi-11
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Non-conditional density estimators are initialized with context_features=None, should support 0 as well the CDEs have a default input context_features which defaults to None. When this is a positive integer, we get a CDE, for a DE we need to set it to None. It should support a value of zero, though. --- 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 find_packages, setup 2 3 exec(open("lfi/version.py").read()) 4 5 setup( 6 name="lfi", 7 version=__version__, 8 description="LFI + CDE.", 9 url="https://github.com/mackelab/lfi", 10 author="Conor Durkan", 11 packages=find_packages(exclude=["tests"]), 12 license="GPLv3", 13 test_requires=["pytest", "deepdiff", "torchtestcase"], 14 install_requires=[ 15 "matplotlib", 16 "numpy", 17 "pyro-ppl", 18 "scipy", 19 "tensorboard", 20 "torch", 21 "tqdm", 22 ], 23 extras_requires={"dev": ["autoflake", "black", "flake8", "isort", "pytest"]}, 24 dependency_links=[], 25 ) 26 ``` --- 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 @@ -1,12 +1,12 @@ from setuptools import find_packages, setup -exec(open("lfi/version.py").read()) +exec(open("sbi/version.py").read()) setup( - name="lfi", + name="sbi", version=__version__, - description="LFI + CDE.", - url="https://github.com/mackelab/lfi", + description="Simulation-based inference", + url="https://github.com/mackelab/sbi", author="Conor Durkan", packages=find_packages(exclude=["tests"]), license="GPLv3",
{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -1,12 +1,12 @@\n from setuptools import find_packages, setup\n \n-exec(open(\"lfi/version.py\").read())\n+exec(open(\"sbi/version.py\").read())\n \n setup(\n- name=\"lfi\",\n+ name=\"sbi\",\n version=__version__,\n- description=\"LFI + CDE.\",\n- url=\"https://github.com/mackelab/lfi\",\n+ description=\"Simulation-based inference\",\n+ url=\"https://github.com/mackelab/sbi\",\n author=\"Conor Durkan\",\n packages=find_packages(exclude=[\"tests\"]),\n license=\"GPLv3\",\n", "issue": "Non-conditional density estimators are initialized with context_features=None, should support 0 as well\nthe CDEs have a default input context_features which defaults to None. When this is a positive integer, we get a CDE, for a DE we need to set it to None. It should support a value of zero, though.\n", "before_files": [{"content": "from setuptools import find_packages, setup\n\nexec(open(\"lfi/version.py\").read())\n\nsetup(\n name=\"lfi\",\n version=__version__,\n description=\"LFI + CDE.\",\n url=\"https://github.com/mackelab/lfi\",\n author=\"Conor Durkan\",\n packages=find_packages(exclude=[\"tests\"]),\n license=\"GPLv3\",\n test_requires=[\"pytest\", \"deepdiff\", \"torchtestcase\"],\n install_requires=[\n \"matplotlib\",\n \"numpy\",\n \"pyro-ppl\",\n \"scipy\",\n \"tensorboard\",\n \"torch\",\n \"tqdm\",\n ],\n extras_requires={\"dev\": [\"autoflake\", \"black\", \"flake8\", \"isort\", \"pytest\"]},\n dependency_links=[],\n)\n", "path": "setup.py"}], "after_files": [{"content": "from setuptools import find_packages, setup\n\nexec(open(\"sbi/version.py\").read())\n\nsetup(\n name=\"sbi\",\n version=__version__,\n description=\"Simulation-based inference\",\n url=\"https://github.com/mackelab/sbi\",\n author=\"Conor Durkan\",\n packages=find_packages(exclude=[\"tests\"]),\n license=\"GPLv3\",\n test_requires=[\"pytest\", \"deepdiff\", \"torchtestcase\"],\n install_requires=[\n \"matplotlib\",\n \"numpy\",\n \"pyro-ppl\",\n \"scipy\",\n \"tensorboard\",\n \"torch\",\n \"tqdm\",\n ],\n extras_requires={\"dev\": [\"autoflake\", \"black\", \"flake8\", \"isort\", \"pytest\"]},\n dependency_links=[],\n)\n", "path": "setup.py"}]}
536
155
gh_patches_debug_834
rasdani/github-patches
git_diff
craiga__will-of-the-prophets-26
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Clean up login form --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `will_of_the_prophets/settings/__init__.py` Content: ``` 1 """ 2 Django settings for will_of_the_prophets project. 3 4 Generated by 'django-admin startproject' using Django 2.0.4. 5 6 For more information on this file, see 7 https://docs.djangoproject.com/en/2.0/topics/settings/ 8 9 For the full list of settings and their values, see 10 https://docs.djangoproject.com/en/2.0/ref/settings/ 11 """ 12 13 import os 14 15 import django_heroku 16 17 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 18 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19 20 21 # Quick-start development settings - unsuitable for production 22 # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ 23 24 # SECURITY WARNING: keep the secret key used in production secret! 25 SECRET_KEY = os.environ.get( 26 'SECRET_KEY', 'bah!osmx@cpaoulc-!eohvd3ldoy*^oki#l25-v6tvq04=6npz') 27 28 # SECURITY WARNING: don't run with debug turned on in production! 29 DEBUG = os.environ.get('DEBUG', False) 30 31 ALLOWED_HOSTS = ['*.herokuapp.com', 'localhost'] 32 33 34 # Application definition 35 36 INSTALLED_APPS = [ 37 'raven.contrib.django.raven_compat', 38 'django.contrib.admin', 39 'django.contrib.auth', 40 'django.contrib.contenttypes', 41 'django.contrib.sessions', 42 'django.contrib.messages', 43 'django.contrib.staticfiles', 44 'sass_processor', 45 'bootstrap', 46 'will_of_the_prophets', 47 ] 48 49 MIDDLEWARE = [ 50 'django.middleware.security.SecurityMiddleware', 51 'django.contrib.sessions.middleware.SessionMiddleware', 52 'django.middleware.common.CommonMiddleware', 53 'django.middleware.csrf.CsrfViewMiddleware', 54 'django.contrib.auth.middleware.AuthenticationMiddleware', 55 'django.contrib.messages.middleware.MessageMiddleware', 56 'django.middleware.clickjacking.XFrameOptionsMiddleware', 57 ] 58 59 ROOT_URLCONF = 'will_of_the_prophets.urls' 60 61 TEMPLATES = [ 62 { 63 'BACKEND': 'django.template.backends.django.DjangoTemplates', 64 'DIRS': [], 65 'APP_DIRS': True, 66 'OPTIONS': { 67 'context_processors': [ 68 'django.template.context_processors.debug', 69 'django.template.context_processors.request', 70 'django.contrib.auth.context_processors.auth', 71 'django.contrib.messages.context_processors.messages', 72 ], 73 }, 74 }, 75 ] 76 77 WSGI_APPLICATION = 'will_of_the_prophets.wsgi.application' 78 79 80 # Database 81 # https://docs.djangoproject.com/en/2.0/ref/settings/#databases 82 83 DATABASES = { 84 'default': { 85 'ENGINE': 'django.db.backends.sqlite3', 86 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 87 } 88 } 89 90 91 # Password validation 92 # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators 93 94 AUTH_PASSWORD_VALIDATORS = [ 95 { 96 'NAME': ('django.contrib.auth.password_validation' 97 '.UserAttributeSimilarityValidator'), 98 }, 99 { 100 'NAME': ('django.contrib.auth.password_validation' 101 '.MinimumLengthValidator'), 102 }, 103 { 104 'NAME': ('django.contrib.auth.password_validation' 105 '.CommonPasswordValidator'), 106 }, 107 { 108 'NAME': ('django.contrib.auth.password_validation' 109 '.NumericPasswordValidator'), 110 }, 111 ] 112 113 114 # Internationalization 115 # https://docs.djangoproject.com/en/2.0/topics/i18n/ 116 117 LANGUAGE_CODE = 'en-us' 118 119 TIME_ZONE = 'UTC' 120 121 USE_I18N = True 122 123 USE_L10N = True 124 125 USE_TZ = True 126 127 128 # Static files (CSS, JavaScript, Images) 129 # https://docs.djangoproject.com/en/2.0/howto/static-files/ 130 131 STATIC_URL = '/static/' 132 133 STATICFILES_FINDERS = [ 134 'django.contrib.staticfiles.finders.FileSystemFinder', 135 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 136 # https://github.com/jrief/django-sass-processor 137 'sass_processor.finders.CssFinder', 138 ] 139 140 141 # django-sass-processor 142 # https://github.com/jrief/django-sass-processor 143 SASS_OUTPUT_STYLE = 'compressed' 144 145 146 # Configure Django App for Heroku. 147 django_heroku.settings(locals()) 148 ``` --- 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/will_of_the_prophets/settings/__init__.py b/will_of_the_prophets/settings/__init__.py --- a/will_of_the_prophets/settings/__init__.py +++ b/will_of_the_prophets/settings/__init__.py @@ -42,6 +42,7 @@ 'django.contrib.messages', 'django.contrib.staticfiles', 'sass_processor', + 'widget_tweaks', 'bootstrap', 'will_of_the_prophets', ]
{"golden_diff": "diff --git a/will_of_the_prophets/settings/__init__.py b/will_of_the_prophets/settings/__init__.py\n--- a/will_of_the_prophets/settings/__init__.py\n+++ b/will_of_the_prophets/settings/__init__.py\n@@ -42,6 +42,7 @@\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'sass_processor',\n+ 'widget_tweaks',\n 'bootstrap',\n 'will_of_the_prophets',\n ]\n", "issue": "Clean up login form\n\n", "before_files": [{"content": "\"\"\"\nDjango settings for will_of_the_prophets project.\n\nGenerated by 'django-admin startproject' using Django 2.0.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.0/ref/settings/\n\"\"\"\n\nimport os\n\nimport django_heroku\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\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get(\n 'SECRET_KEY', 'bah!osmx@cpaoulc-!eohvd3ldoy*^oki#l25-v6tvq04=6npz')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get('DEBUG', False)\n\nALLOWED_HOSTS = ['*.herokuapp.com', 'localhost']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'raven.contrib.django.raven_compat',\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 'sass_processor',\n 'bootstrap',\n 'will_of_the_prophets',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\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 = 'will_of_the_prophets.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\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 = 'will_of_the_prophets.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.UserAttributeSimilarityValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.MinimumLengthValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.CommonPasswordValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.NumericPasswordValidator'),\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_FINDERS = [\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n # https://github.com/jrief/django-sass-processor\n 'sass_processor.finders.CssFinder',\n]\n\n\n# django-sass-processor\n# https://github.com/jrief/django-sass-processor\nSASS_OUTPUT_STYLE = 'compressed'\n\n\n# Configure Django App for Heroku.\ndjango_heroku.settings(locals())\n", "path": "will_of_the_prophets/settings/__init__.py"}], "after_files": [{"content": "\"\"\"\nDjango settings for will_of_the_prophets project.\n\nGenerated by 'django-admin startproject' using Django 2.0.4.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.0/ref/settings/\n\"\"\"\n\nimport os\n\nimport django_heroku\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\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get(\n 'SECRET_KEY', 'bah!osmx@cpaoulc-!eohvd3ldoy*^oki#l25-v6tvq04=6npz')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get('DEBUG', False)\n\nALLOWED_HOSTS = ['*.herokuapp.com', 'localhost']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'raven.contrib.django.raven_compat',\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 'sass_processor',\n 'widget_tweaks',\n 'bootstrap',\n 'will_of_the_prophets',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\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 = 'will_of_the_prophets.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\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 = 'will_of_the_prophets.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.UserAttributeSimilarityValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.MinimumLengthValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.CommonPasswordValidator'),\n },\n {\n 'NAME': ('django.contrib.auth.password_validation'\n '.NumericPasswordValidator'),\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_FINDERS = [\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n # https://github.com/jrief/django-sass-processor\n 'sass_processor.finders.CssFinder',\n]\n\n\n# django-sass-processor\n# https://github.com/jrief/django-sass-processor\nSASS_OUTPUT_STYLE = 'compressed'\n\n\n# Configure Django App for Heroku.\ndjango_heroku.settings(locals())\n", "path": "will_of_the_prophets/settings/__init__.py"}]}
1,519
112
gh_patches_debug_9798
rasdani/github-patches
git_diff
netbox-community__netbox-15788
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- New User model has a 32-bit integer `id` field ### Deployment Type NetBox Cloud ### NetBox Version v4.0-beta1 ### Python Version 3.10 ### Steps to Reproduce 1. Upgrade a v3.7 database to v4.0 2. Inspect the `users_user` table ### Expected Behavior The `id` column of the `users_user` table should be a `bigint` (64-bit integer), like all other models in NetBox. ### Observed Behavior The `id` column is a regular 32-bit integer. This is because we renamed the stock Django table, which uses a 32-bit integer `id` field. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `netbox/users/migrations/0005_alter_user_table.py` Content: ``` 1 from django.db import migrations 2 3 4 def update_content_types(apps, schema_editor): 5 ContentType = apps.get_model('contenttypes', 'ContentType') 6 # Delete the new ContentTypes effected by the new models in the users app 7 ContentType.objects.filter(app_label='users', model='user').delete() 8 9 # Update the app labels of the original ContentTypes for auth.User to ensure 10 # that any foreign key references are preserved 11 ContentType.objects.filter(app_label='auth', model='user').update(app_label='users') 12 13 netboxuser_ct = ContentType.objects.filter(app_label='users', model='netboxuser').first() 14 if netboxuser_ct: 15 user_ct = ContentType.objects.filter(app_label='users', model='user').first() 16 CustomField = apps.get_model('extras', 'CustomField') 17 CustomField.objects.filter(related_object_type_id=netboxuser_ct.id).update(related_object_type_id=user_ct.id) 18 netboxuser_ct.delete() 19 20 21 class Migration(migrations.Migration): 22 23 dependencies = [ 24 ('users', '0002_squashed_0004'), 25 ] 26 27 operations = [ 28 # The User table was originally created as 'auth_user'. Now we nullify the model's 29 # db_table option, so that it defaults to the app & model name (users_user). This 30 # causes the database table to be renamed. 31 migrations.AlterModelTable( 32 name='user', 33 table=None, 34 ), 35 36 # Rename auth_user_* sequences 37 migrations.RunSQL("ALTER TABLE auth_user_groups_id_seq RENAME TO users_user_groups_id_seq"), 38 migrations.RunSQL("ALTER TABLE auth_user_id_seq RENAME TO users_user_id_seq"), 39 migrations.RunSQL("ALTER TABLE auth_user_user_permissions_id_seq RENAME TO users_user_user_permissions_id_seq"), 40 41 # Rename auth_user_* indexes 42 migrations.RunSQL("ALTER INDEX auth_user_pkey RENAME TO users_user_pkey"), 43 # Hash is deterministic; generated via schema_editor._create_index_name() 44 migrations.RunSQL("ALTER INDEX auth_user_username_6821ab7c_like RENAME TO users_user_username_06e46fe6_like"), 45 migrations.RunSQL("ALTER INDEX auth_user_username_key RENAME TO users_user_username_key"), 46 47 # Update ContentTypes 48 migrations.RunPython( 49 code=update_content_types, 50 reverse_code=migrations.RunPython.noop 51 ), 52 ] 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/netbox/users/migrations/0005_alter_user_table.py b/netbox/users/migrations/0005_alter_user_table.py --- a/netbox/users/migrations/0005_alter_user_table.py +++ b/netbox/users/migrations/0005_alter_user_table.py @@ -33,6 +33,9 @@ table=None, ), + # Convert the `id` column to a 64-bit integer (BigAutoField is implied by DEFAULT_AUTO_FIELD) + migrations.RunSQL("ALTER TABLE users_user ALTER COLUMN id TYPE bigint"), + # Rename auth_user_* sequences migrations.RunSQL("ALTER TABLE auth_user_groups_id_seq RENAME TO users_user_groups_id_seq"), migrations.RunSQL("ALTER TABLE auth_user_id_seq RENAME TO users_user_id_seq"),
{"golden_diff": "diff --git a/netbox/users/migrations/0005_alter_user_table.py b/netbox/users/migrations/0005_alter_user_table.py\n--- a/netbox/users/migrations/0005_alter_user_table.py\n+++ b/netbox/users/migrations/0005_alter_user_table.py\n@@ -33,6 +33,9 @@\n table=None,\n ),\n \n+ # Convert the `id` column to a 64-bit integer (BigAutoField is implied by DEFAULT_AUTO_FIELD)\n+ migrations.RunSQL(\"ALTER TABLE users_user ALTER COLUMN id TYPE bigint\"),\n+\n # Rename auth_user_* sequences\n migrations.RunSQL(\"ALTER TABLE auth_user_groups_id_seq RENAME TO users_user_groups_id_seq\"),\n migrations.RunSQL(\"ALTER TABLE auth_user_id_seq RENAME TO users_user_id_seq\"),\n", "issue": "New User model has a 32-bit integer `id` field\n### Deployment Type\n\nNetBox Cloud\n\n### NetBox Version\n\nv4.0-beta1\n\n### Python Version\n\n3.10\n\n### Steps to Reproduce\n\n1. Upgrade a v3.7 database to v4.0\r\n2. Inspect the `users_user` table\n\n### Expected Behavior\n\nThe `id` column of the `users_user` table should be a `bigint` (64-bit integer), like all other models in NetBox.\n\n### Observed Behavior\n\nThe `id` column is a regular 32-bit integer. This is because we renamed the stock Django table, which uses a 32-bit integer `id` field.\n", "before_files": [{"content": "from django.db import migrations\n\n\ndef update_content_types(apps, schema_editor):\n ContentType = apps.get_model('contenttypes', 'ContentType')\n # Delete the new ContentTypes effected by the new models in the users app\n ContentType.objects.filter(app_label='users', model='user').delete()\n\n # Update the app labels of the original ContentTypes for auth.User to ensure\n # that any foreign key references are preserved\n ContentType.objects.filter(app_label='auth', model='user').update(app_label='users')\n\n netboxuser_ct = ContentType.objects.filter(app_label='users', model='netboxuser').first()\n if netboxuser_ct:\n user_ct = ContentType.objects.filter(app_label='users', model='user').first()\n CustomField = apps.get_model('extras', 'CustomField')\n CustomField.objects.filter(related_object_type_id=netboxuser_ct.id).update(related_object_type_id=user_ct.id)\n netboxuser_ct.delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0002_squashed_0004'),\n ]\n\n operations = [\n # The User table was originally created as 'auth_user'. Now we nullify the model's\n # db_table option, so that it defaults to the app & model name (users_user). This\n # causes the database table to be renamed.\n migrations.AlterModelTable(\n name='user',\n table=None,\n ),\n\n # Rename auth_user_* sequences\n migrations.RunSQL(\"ALTER TABLE auth_user_groups_id_seq RENAME TO users_user_groups_id_seq\"),\n migrations.RunSQL(\"ALTER TABLE auth_user_id_seq RENAME TO users_user_id_seq\"),\n migrations.RunSQL(\"ALTER TABLE auth_user_user_permissions_id_seq RENAME TO users_user_user_permissions_id_seq\"),\n\n # Rename auth_user_* indexes\n migrations.RunSQL(\"ALTER INDEX auth_user_pkey RENAME TO users_user_pkey\"),\n # Hash is deterministic; generated via schema_editor._create_index_name()\n migrations.RunSQL(\"ALTER INDEX auth_user_username_6821ab7c_like RENAME TO users_user_username_06e46fe6_like\"),\n migrations.RunSQL(\"ALTER INDEX auth_user_username_key RENAME TO users_user_username_key\"),\n\n # Update ContentTypes\n migrations.RunPython(\n code=update_content_types,\n reverse_code=migrations.RunPython.noop\n ),\n ]\n", "path": "netbox/users/migrations/0005_alter_user_table.py"}], "after_files": [{"content": "from django.db import migrations\n\n\ndef update_content_types(apps, schema_editor):\n ContentType = apps.get_model('contenttypes', 'ContentType')\n # Delete the new ContentTypes effected by the new models in the users app\n ContentType.objects.filter(app_label='users', model='user').delete()\n\n # Update the app labels of the original ContentTypes for auth.User to ensure\n # that any foreign key references are preserved\n ContentType.objects.filter(app_label='auth', model='user').update(app_label='users')\n\n netboxuser_ct = ContentType.objects.filter(app_label='users', model='netboxuser').first()\n if netboxuser_ct:\n user_ct = ContentType.objects.filter(app_label='users', model='user').first()\n CustomField = apps.get_model('extras', 'CustomField')\n CustomField.objects.filter(related_object_type_id=netboxuser_ct.id).update(related_object_type_id=user_ct.id)\n netboxuser_ct.delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0002_squashed_0004'),\n ]\n\n operations = [\n # The User table was originally created as 'auth_user'. Now we nullify the model's\n # db_table option, so that it defaults to the app & model name (users_user). This\n # causes the database table to be renamed.\n migrations.AlterModelTable(\n name='user',\n table=None,\n ),\n\n # Convert the `id` column to a 64-bit integer (BigAutoField is implied by DEFAULT_AUTO_FIELD)\n migrations.RunSQL(\"ALTER TABLE users_user ALTER COLUMN id TYPE bigint\"),\n\n # Rename auth_user_* sequences\n migrations.RunSQL(\"ALTER TABLE auth_user_groups_id_seq RENAME TO users_user_groups_id_seq\"),\n migrations.RunSQL(\"ALTER TABLE auth_user_id_seq RENAME TO users_user_id_seq\"),\n migrations.RunSQL(\"ALTER TABLE auth_user_user_permissions_id_seq RENAME TO users_user_user_permissions_id_seq\"),\n\n # Rename auth_user_* indexes\n migrations.RunSQL(\"ALTER INDEX auth_user_pkey RENAME TO users_user_pkey\"),\n # Hash is deterministic; generated via schema_editor._create_index_name()\n migrations.RunSQL(\"ALTER INDEX auth_user_username_6821ab7c_like RENAME TO users_user_username_06e46fe6_like\"),\n migrations.RunSQL(\"ALTER INDEX auth_user_username_key RENAME TO users_user_username_key\"),\n\n # Update ContentTypes\n migrations.RunPython(\n code=update_content_types,\n reverse_code=migrations.RunPython.noop\n ),\n ]\n", "path": "netbox/users/migrations/0005_alter_user_table.py"}]}
1,037
183
gh_patches_debug_32866
rasdani/github-patches
git_diff
readthedocs__readthedocs.org-4451
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Documentation for the v2 of the configuration file At first, I was thinking to automate this given the schema, but the spec isn't very large so we can just hand-write this without too much effort. --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `docs/doc_extensions.py` Content: ``` 1 """ 2 Read the Docs documentation extensions for Sphinx 3 4 Adds the following roles: 5 6 djangosetting 7 Output an inline literal of the corresponding setting value. Useful for 8 keeping documentation up to date without editing on settings changes. 9 """ 10 11 from docutils import nodes, utils 12 13 from django.conf import settings 14 15 from readthedocs.projects.models import Feature 16 17 18 def django_setting_role(typ, rawtext, text, lineno, inliner, options=None, 19 content=None): 20 """Always up to date Django settings from the application""" 21 dj_setting = getattr(settings, utils.unescape(text), 'None') 22 node = nodes.literal(dj_setting, dj_setting) 23 return [node], [] 24 25 26 def feature_flags_role(typ, rawtext, text, lineno, inliner, options=None, 27 content=None): 28 """Up to date feature flags from the application.""" 29 all_features = Feature.FEATURES 30 requested_feature = utils.unescape(text) 31 for feature in all_features: 32 if requested_feature.lower() == feature[0].lower(): 33 desc = nodes.Text(feature[1], feature[1]) 34 return [desc], [] 35 36 37 def setup(_): 38 from docutils.parsers.rst import roles 39 roles.register_local_role( 40 'djangosetting', 41 django_setting_role 42 ) 43 roles.register_local_role( 44 'featureflags', 45 feature_flags_role 46 ) 47 48 return { 49 'version': 'builtin', 50 'parallel_read_safe': True, 51 'parallel_write_safe': True, 52 } 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/docs/doc_extensions.py b/docs/doc_extensions.py --- a/docs/doc_extensions.py +++ b/docs/doc_extensions.py @@ -6,11 +6,14 @@ djangosetting Output an inline literal of the corresponding setting value. Useful for keeping documentation up to date without editing on settings changes. -""" -from docutils import nodes, utils +buildpyversions + Output a comma separated list of the supported python versions for a + Read the Docs build image. +""" from django.conf import settings +from docutils import nodes, utils from readthedocs.projects.models import Feature @@ -23,8 +26,23 @@ return [node], [] +def python_supported_versions_role(typ, rawtext, text, lineno, inliner, + options=None, content=None): + """Up to date supported python versions for each build image.""" + image = '{}:{}'.format(settings.DOCKER_DEFAULT_IMAGE, text) + image_settings = settings.DOCKER_IMAGE_SETTINGS[image] + python_versions = image_settings['python']['supported_versions'] + node_list = [] + separator = ', ' + for i, version in enumerate(python_versions): + node_list.append(nodes.literal(version, version)) + if i < len(python_versions) - 1: + node_list.append(nodes.Text(separator)) + return (node_list, []) + + def feature_flags_role(typ, rawtext, text, lineno, inliner, options=None, - content=None): + content=None): """Up to date feature flags from the application.""" all_features = Feature.FEATURES requested_feature = utils.unescape(text) @@ -40,9 +58,13 @@ 'djangosetting', django_setting_role ) + roles.register_local_role( + 'buildpyversions', + python_supported_versions_role, + ) roles.register_local_role( 'featureflags', - feature_flags_role + feature_flags_role, ) return {
{"golden_diff": "diff --git a/docs/doc_extensions.py b/docs/doc_extensions.py\n--- a/docs/doc_extensions.py\n+++ b/docs/doc_extensions.py\n@@ -6,11 +6,14 @@\n djangosetting\n Output an inline literal of the corresponding setting value. Useful for\n keeping documentation up to date without editing on settings changes.\n-\"\"\"\n \n-from docutils import nodes, utils\n+buildpyversions\n+ Output a comma separated list of the supported python versions for a\n+ Read the Docs build image.\n+\"\"\"\n \n from django.conf import settings\n+from docutils import nodes, utils\n \n from readthedocs.projects.models import Feature\n \n@@ -23,8 +26,23 @@\n return [node], []\n \n \n+def python_supported_versions_role(typ, rawtext, text, lineno, inliner,\n+ options=None, content=None):\n+ \"\"\"Up to date supported python versions for each build image.\"\"\"\n+ image = '{}:{}'.format(settings.DOCKER_DEFAULT_IMAGE, text)\n+ image_settings = settings.DOCKER_IMAGE_SETTINGS[image]\n+ python_versions = image_settings['python']['supported_versions']\n+ node_list = []\n+ separator = ', '\n+ for i, version in enumerate(python_versions):\n+ node_list.append(nodes.literal(version, version))\n+ if i < len(python_versions) - 1:\n+ node_list.append(nodes.Text(separator))\n+ return (node_list, [])\n+\n+\n def feature_flags_role(typ, rawtext, text, lineno, inliner, options=None,\n- content=None):\n+ content=None):\n \"\"\"Up to date feature flags from the application.\"\"\"\n all_features = Feature.FEATURES\n requested_feature = utils.unescape(text)\n@@ -40,9 +58,13 @@\n 'djangosetting',\n django_setting_role\n )\n+ roles.register_local_role(\n+ 'buildpyversions',\n+ python_supported_versions_role,\n+ )\n roles.register_local_role(\n 'featureflags',\n- feature_flags_role\n+ feature_flags_role,\n )\n \n return {\n", "issue": "Documentation for the v2 of the configuration file\nAt first, I was thinking to automate this given the schema, but the spec isn't very large so we can just hand-write this without too much effort.\n", "before_files": [{"content": "\"\"\"\nRead the Docs documentation extensions for Sphinx\n\nAdds the following roles:\n\ndjangosetting\n Output an inline literal of the corresponding setting value. Useful for\n keeping documentation up to date without editing on settings changes.\n\"\"\"\n\nfrom docutils import nodes, utils\n\nfrom django.conf import settings\n\nfrom readthedocs.projects.models import Feature\n\n\ndef django_setting_role(typ, rawtext, text, lineno, inliner, options=None,\n content=None):\n \"\"\"Always up to date Django settings from the application\"\"\"\n dj_setting = getattr(settings, utils.unescape(text), 'None')\n node = nodes.literal(dj_setting, dj_setting)\n return [node], []\n\n\ndef feature_flags_role(typ, rawtext, text, lineno, inliner, options=None,\n content=None):\n \"\"\"Up to date feature flags from the application.\"\"\"\n all_features = Feature.FEATURES\n requested_feature = utils.unescape(text)\n for feature in all_features:\n if requested_feature.lower() == feature[0].lower():\n desc = nodes.Text(feature[1], feature[1])\n return [desc], []\n\n\ndef setup(_):\n from docutils.parsers.rst import roles\n roles.register_local_role(\n 'djangosetting',\n django_setting_role\n )\n roles.register_local_role(\n 'featureflags',\n feature_flags_role\n )\n\n return {\n 'version': 'builtin',\n 'parallel_read_safe': True,\n 'parallel_write_safe': True,\n }\n", "path": "docs/doc_extensions.py"}], "after_files": [{"content": "\"\"\"\nRead the Docs documentation extensions for Sphinx\n\nAdds the following roles:\n\ndjangosetting\n Output an inline literal of the corresponding setting value. Useful for\n keeping documentation up to date without editing on settings changes.\n\nbuildpyversions\n Output a comma separated list of the supported python versions for a\n Read the Docs build image.\n\"\"\"\n\nfrom django.conf import settings\nfrom docutils import nodes, utils\n\nfrom readthedocs.projects.models import Feature\n\n\ndef django_setting_role(typ, rawtext, text, lineno, inliner, options=None,\n content=None):\n \"\"\"Always up to date Django settings from the application\"\"\"\n dj_setting = getattr(settings, utils.unescape(text), 'None')\n node = nodes.literal(dj_setting, dj_setting)\n return [node], []\n\n\ndef python_supported_versions_role(typ, rawtext, text, lineno, inliner,\n options=None, content=None):\n \"\"\"Up to date supported python versions for each build image.\"\"\"\n image = '{}:{}'.format(settings.DOCKER_DEFAULT_IMAGE, text)\n image_settings = settings.DOCKER_IMAGE_SETTINGS[image]\n python_versions = image_settings['python']['supported_versions']\n node_list = []\n separator = ', '\n for i, version in enumerate(python_versions):\n node_list.append(nodes.literal(version, version))\n if i < len(python_versions) - 1:\n node_list.append(nodes.Text(separator))\n return (node_list, [])\n\n\ndef feature_flags_role(typ, rawtext, text, lineno, inliner, options=None,\n content=None):\n \"\"\"Up to date feature flags from the application.\"\"\"\n all_features = Feature.FEATURES\n requested_feature = utils.unescape(text)\n for feature in all_features:\n if requested_feature.lower() == feature[0].lower():\n desc = nodes.Text(feature[1], feature[1])\n return [desc], []\n\n\ndef setup(_):\n from docutils.parsers.rst import roles\n roles.register_local_role(\n 'djangosetting',\n django_setting_role\n )\n roles.register_local_role(\n 'buildpyversions',\n python_supported_versions_role,\n )\n roles.register_local_role(\n 'featureflags',\n feature_flags_role,\n )\n\n return {\n 'version': 'builtin',\n 'parallel_read_safe': True,\n 'parallel_write_safe': True,\n }\n", "path": "docs/doc_extensions.py"}]}
717
446
gh_patches_debug_2000
rasdani/github-patches
git_diff
automl__auto-sklearn-190
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Add warning if dependencies are not met There should be a warning if one of the following dependencies is not met: - scikit-learn==0.17 - smac==0.0.1 - lockfile>=0.10 - ConfigSpace>=0.2.1 - pyrfr==0.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: `autosklearn/util/dependencies.py` Content: ``` 1 from warnings import warn 2 3 import pkg_resources 4 import re 5 6 from distutils.version import LooseVersion 7 8 9 RE_PATTERN = re.compile('^(?P<name>[\w\-]+)((?P<operation>==|>=|>)(?P<version>(\d+\.)?(\d+\.)?(\d+)))?$') 10 11 12 def verify_packages(packages): 13 if not packages: 14 return 15 if isinstance(packages, str): 16 packages = packages.splitlines() 17 18 for package in packages: 19 if not package: 20 continue 21 22 match = RE_PATTERN.match(package) 23 if match: 24 name = match.group('name') 25 operation = match.group('operation') 26 version = match.group('version') 27 _verify_package(name, operation, version) 28 else: 29 raise ValueError('Unable to read requirement: %s' % package) 30 31 32 def _verify_package(name, operation, version): 33 try: 34 module = pkg_resources.get_distribution(name) 35 except pkg_resources.DistributionNotFound: 36 raise MissingPackageError(name) from None 37 38 if not operation: 39 return 40 41 required_version = LooseVersion(version) 42 installed_version = LooseVersion(module.version) 43 44 if operation == '==': 45 check = required_version == installed_version 46 elif operation == '>': 47 check = installed_version > required_version 48 elif operation == '>=': 49 check = installed_version > required_version or \ 50 installed_version == required_version 51 else: 52 raise NotImplementedError('operation \'%s\' is not supported' % operation) 53 if not check: 54 raise IncorrectPackageVersionError(name, installed_version, operation, required_version) 55 56 57 class MissingPackageError(Exception): 58 59 error_message = 'mandatory package \'{name}\' not found' 60 61 def __init__(self, package_name): 62 self.package_name = package_name 63 super(MissingPackageError, self).__init__(self.error_message.format(name=package_name)) 64 65 66 class IncorrectPackageVersionError(Exception): 67 68 error_message = '\'{name} {installed_version}\' version mismatch ({operation}{required_version})' 69 70 def __init__(self, package_name, installed_version, operation, required_version): 71 self.package_name = package_name 72 self.installed_version = installed_version 73 self.operation = operation 74 self.required_version = required_version 75 message = self.error_message.format(name=package_name, 76 installed_version=installed_version, 77 operation=operation, 78 required_version=required_version) 79 super(IncorrectPackageVersionError, self).__init__(message) 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/autosklearn/util/dependencies.py b/autosklearn/util/dependencies.py --- a/autosklearn/util/dependencies.py +++ b/autosklearn/util/dependencies.py @@ -33,7 +33,7 @@ try: module = pkg_resources.get_distribution(name) except pkg_resources.DistributionNotFound: - raise MissingPackageError(name) from None + raise MissingPackageError(name) if not operation: return
{"golden_diff": "diff --git a/autosklearn/util/dependencies.py b/autosklearn/util/dependencies.py\n--- a/autosklearn/util/dependencies.py\n+++ b/autosklearn/util/dependencies.py\n@@ -33,7 +33,7 @@\n try:\n module = pkg_resources.get_distribution(name)\n except pkg_resources.DistributionNotFound:\n- raise MissingPackageError(name) from None\n+ raise MissingPackageError(name)\n \n if not operation:\n return\n", "issue": "Add warning if dependencies are not met\nThere should be a warning if one of the following dependencies is not met:\r\n- scikit-learn==0.17\r\n- smac==0.0.1\r\n- lockfile>=0.10\r\n- ConfigSpace>=0.2.1\r\n- pyrfr==0.2.1\r\n\n", "before_files": [{"content": "from warnings import warn\n\nimport pkg_resources\nimport re\n\nfrom distutils.version import LooseVersion\n\n\nRE_PATTERN = re.compile('^(?P<name>[\\w\\-]+)((?P<operation>==|>=|>)(?P<version>(\\d+\\.)?(\\d+\\.)?(\\d+)))?$')\n\n\ndef verify_packages(packages):\n if not packages:\n return\n if isinstance(packages, str):\n packages = packages.splitlines()\n\n for package in packages:\n if not package:\n continue\n\n match = RE_PATTERN.match(package)\n if match:\n name = match.group('name')\n operation = match.group('operation')\n version = match.group('version')\n _verify_package(name, operation, version)\n else:\n raise ValueError('Unable to read requirement: %s' % package)\n\n\ndef _verify_package(name, operation, version):\n try:\n module = pkg_resources.get_distribution(name)\n except pkg_resources.DistributionNotFound:\n raise MissingPackageError(name) from None\n\n if not operation:\n return\n\n required_version = LooseVersion(version)\n installed_version = LooseVersion(module.version)\n\n if operation == '==':\n check = required_version == installed_version\n elif operation == '>':\n check = installed_version > required_version\n elif operation == '>=':\n check = installed_version > required_version or \\\n installed_version == required_version\n else:\n raise NotImplementedError('operation \\'%s\\' is not supported' % operation)\n if not check:\n raise IncorrectPackageVersionError(name, installed_version, operation, required_version)\n\n\nclass MissingPackageError(Exception):\n\n error_message = 'mandatory package \\'{name}\\' not found'\n\n def __init__(self, package_name):\n self.package_name = package_name\n super(MissingPackageError, self).__init__(self.error_message.format(name=package_name))\n\n\nclass IncorrectPackageVersionError(Exception):\n\n error_message = '\\'{name} {installed_version}\\' version mismatch ({operation}{required_version})'\n\n def __init__(self, package_name, installed_version, operation, required_version):\n self.package_name = package_name\n self.installed_version = installed_version\n self.operation = operation\n self.required_version = required_version\n message = self.error_message.format(name=package_name,\n installed_version=installed_version,\n operation=operation,\n required_version=required_version)\n super(IncorrectPackageVersionError, self).__init__(message)\n", "path": "autosklearn/util/dependencies.py"}], "after_files": [{"content": "from warnings import warn\n\nimport pkg_resources\nimport re\n\nfrom distutils.version import LooseVersion\n\n\nRE_PATTERN = re.compile('^(?P<name>[\\w\\-]+)((?P<operation>==|>=|>)(?P<version>(\\d+\\.)?(\\d+\\.)?(\\d+)))?$')\n\n\ndef verify_packages(packages):\n if not packages:\n return\n if isinstance(packages, str):\n packages = packages.splitlines()\n\n for package in packages:\n if not package:\n continue\n\n match = RE_PATTERN.match(package)\n if match:\n name = match.group('name')\n operation = match.group('operation')\n version = match.group('version')\n _verify_package(name, operation, version)\n else:\n raise ValueError('Unable to read requirement: %s' % package)\n\n\ndef _verify_package(name, operation, version):\n try:\n module = pkg_resources.get_distribution(name)\n except pkg_resources.DistributionNotFound:\n raise MissingPackageError(name)\n\n if not operation:\n return\n\n required_version = LooseVersion(version)\n installed_version = LooseVersion(module.version)\n\n if operation == '==':\n check = required_version == installed_version\n elif operation == '>':\n check = installed_version > required_version\n elif operation == '>=':\n check = installed_version > required_version or \\\n installed_version == required_version\n else:\n raise NotImplementedError('operation \\'%s\\' is not supported' % operation)\n if not check:\n raise IncorrectPackageVersionError(name, installed_version, operation, required_version)\n\n\nclass MissingPackageError(Exception):\n\n error_message = 'mandatory package \\'{name}\\' not found'\n\n def __init__(self, package_name):\n self.package_name = package_name\n super(MissingPackageError, self).__init__(self.error_message.format(name=package_name))\n\n\nclass IncorrectPackageVersionError(Exception):\n\n error_message = '\\'{name} {installed_version}\\' version mismatch ({operation}{required_version})'\n\n def __init__(self, package_name, installed_version, operation, required_version):\n self.package_name = package_name\n self.installed_version = installed_version\n self.operation = operation\n self.required_version = required_version\n message = self.error_message.format(name=package_name,\n installed_version=installed_version,\n operation=operation,\n required_version=required_version)\n super(IncorrectPackageVersionError, self).__init__(message)\n", "path": "autosklearn/util/dependencies.py"}]}
1,026
104
gh_patches_debug_12462
rasdani/github-patches
git_diff
dask__distributed-6306
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- parse_stdout.py produces malformed Junit reports parse_stdout.py has recently stopped working. This causes Windows timeouts to be reported as a white box instead of a red box in https://dask.org/distributed/test_report.html. https://github.com/dask/distributed/actions/runs/2293197167 > Publish test results: artifacts/windows-latest-3.10-notci1/pytest.xml#L976Error processing result file: not well-formed (invalid token): line 976, column 93 --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `continuous_integration/scripts/parse_stdout.py` Content: ``` 1 """On Windows, pytest-timeout kills off the whole test suite, leaving no junit report 2 behind. Parse the stdout of pytest to generate one. 3 """ 4 from __future__ import annotations 5 6 import re 7 import sys 8 from collections import Counter, defaultdict 9 from collections.abc import Iterable 10 from datetime import datetime 11 12 OUTCOMES = { 13 "PASSED", 14 "FAILED", 15 # Test timeout. Marked as a variant of FAILED in the junit report 16 None, 17 # Setup failed or teardown failed. 18 # In the latter case, if the test also failed, show both a FAILED and an ERROR line. 19 "ERROR", 20 # @pytest.mark.skip, @pytest.mark.skipif, or raise pytest.skip() 21 "SKIPPED", 22 # Reported as a variant of SKIPPED in the junit report 23 "XFAIL", 24 # These appear respectively before and after another status. Ignore. 25 "RERUN", 26 "LEAKED", 27 } 28 29 30 def parse_rows(rows: Iterable[str]) -> list[tuple[str, str, set[str | None]]]: 31 match = re.compile( 32 r"(distributed/.*test.*)::([^ ]*)" 33 r"( (.*)(PASSED|FAILED|ERROR|SKIPPED|XFAIL|RERUN|LEAKED).*| )$" 34 ) 35 36 out: defaultdict[tuple[str, str], set[str | None]] = defaultdict(set) 37 38 for row in rows: 39 m = match.match(row) 40 if not m: 41 continue 42 43 fname = m.group(1) 44 clsname = fname.replace("/", ".").replace(".py", "").replace("::", ".") 45 46 tname = m.group(2).strip() 47 if m.group(4) and "]" in m.group(4): 48 tname += " " + m.group(4).split("]")[0] + "]" 49 50 outcome = m.group(5) 51 assert outcome in OUTCOMES 52 if outcome not in {"RERUN", "LEAKED"}: 53 out[clsname, tname].add(outcome) 54 55 return [(clsname, tname, outcomes) for (clsname, tname), outcomes in out.items()] 56 57 58 def build_xml(rows: list[tuple[str, str, set[str | None]]]) -> None: 59 cnt = Counter(outcome for _, _, outcomes in rows for outcome in outcomes) 60 timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f") 61 62 # We could have used ElementTree but it feels like overkill here 63 print('<?xml version="1.0" encoding="utf-8"?>') 64 print("<testsuites>") 65 print( 66 '<testsuite name="distributed" ' 67 f'errors="{cnt["ERROR"]}" failures="{cnt["FAILED"] + cnt[None]}" ' 68 f'skipped="{cnt["SKIPPED"] + cnt["XFAIL"]}" tests="{sum(cnt.values())}" ' 69 f'time="0.0" timestamp="{timestamp}" hostname="">' 70 ) 71 72 for clsname, tname, outcomes in rows: 73 print(f'<testcase classname="{clsname}" name="{tname}" time="0.0"', end="") 74 if outcomes == {"PASSED"}: 75 print(" />") 76 elif outcomes == {"FAILED"}: 77 print('><failure message=""></failure></testcase>') 78 elif outcomes == {None}: 79 print('><failure message="pytest-timeout exceeded"></failure></testcase>') 80 elif outcomes == {"ERROR"}: 81 print('><error message="failed on setup"></error></testcase>') 82 elif outcomes == {"PASSED", "ERROR"}: 83 print('><error message="failed on teardown"></error></testcase>') 84 elif outcomes == {"FAILED", "ERROR"}: 85 print( 86 '><failure message=""></failure></testcase>\n' 87 f'<testcase classname="{clsname}" name="{tname}" time="0.0">' 88 '<error message="failed on teardown"></error></testcase>' 89 ) 90 elif outcomes == {"SKIPPED"}: 91 print('><skipped type="pytest.skip" message="skip"></skipped></testcase>') 92 elif outcomes == {"XFAIL"}: 93 print('><skipped type="pytest.xfail" message="xfail"></skipped></testcase>') 94 else: # pragma: nocover 95 # This should be unreachable. We would normally raise ValueError, except 96 # that a crash in this script would be pretty much invisible. 97 print( 98 f' />\n<testcase classname="parse_stdout" name="build_xml" time="0.0">' 99 f'><failure message="Unexpected {outcomes=}"></failure></testcase>' 100 ) 101 102 print("</testsuite>") 103 print("</testsuites>") 104 105 106 def main() -> None: # pragma: nocover 107 build_xml(parse_rows(sys.stdin)) 108 109 110 if __name__ == "__main__": 111 main() # pragma: nocover 112 ``` --- 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/continuous_integration/scripts/parse_stdout.py b/continuous_integration/scripts/parse_stdout.py --- a/continuous_integration/scripts/parse_stdout.py +++ b/continuous_integration/scripts/parse_stdout.py @@ -3,6 +3,7 @@ """ from __future__ import annotations +import html import re import sys from collections import Counter, defaultdict @@ -70,6 +71,8 @@ ) for clsname, tname, outcomes in rows: + clsname = html.escape(clsname) + tname = html.escape(tname) print(f'<testcase classname="{clsname}" name="{tname}" time="0.0"', end="") if outcomes == {"PASSED"}: print(" />")
{"golden_diff": "diff --git a/continuous_integration/scripts/parse_stdout.py b/continuous_integration/scripts/parse_stdout.py\n--- a/continuous_integration/scripts/parse_stdout.py\n+++ b/continuous_integration/scripts/parse_stdout.py\n@@ -3,6 +3,7 @@\n \"\"\"\n from __future__ import annotations\n \n+import html\n import re\n import sys\n from collections import Counter, defaultdict\n@@ -70,6 +71,8 @@\n )\n \n for clsname, tname, outcomes in rows:\n+ clsname = html.escape(clsname)\n+ tname = html.escape(tname)\n print(f'<testcase classname=\"{clsname}\" name=\"{tname}\" time=\"0.0\"', end=\"\")\n if outcomes == {\"PASSED\"}:\n print(\" />\")\n", "issue": "parse_stdout.py produces malformed Junit reports\nparse_stdout.py has recently stopped working.\r\nThis causes Windows timeouts to be reported as a white box instead of a red box in https://dask.org/distributed/test_report.html.\r\n\r\nhttps://github.com/dask/distributed/actions/runs/2293197167\r\n> Publish test results:\u00a0artifacts/windows-latest-3.10-notci1/pytest.xml#L976Error processing result file: not well-formed (invalid token): line 976, column 93\r\n\n", "before_files": [{"content": "\"\"\"On Windows, pytest-timeout kills off the whole test suite, leaving no junit report\nbehind. Parse the stdout of pytest to generate one.\n\"\"\"\nfrom __future__ import annotations\n\nimport re\nimport sys\nfrom collections import Counter, defaultdict\nfrom collections.abc import Iterable\nfrom datetime import datetime\n\nOUTCOMES = {\n \"PASSED\",\n \"FAILED\",\n # Test timeout. Marked as a variant of FAILED in the junit report\n None,\n # Setup failed or teardown failed.\n # In the latter case, if the test also failed, show both a FAILED and an ERROR line.\n \"ERROR\",\n # @pytest.mark.skip, @pytest.mark.skipif, or raise pytest.skip()\n \"SKIPPED\",\n # Reported as a variant of SKIPPED in the junit report\n \"XFAIL\",\n # These appear respectively before and after another status. Ignore.\n \"RERUN\",\n \"LEAKED\",\n}\n\n\ndef parse_rows(rows: Iterable[str]) -> list[tuple[str, str, set[str | None]]]:\n match = re.compile(\n r\"(distributed/.*test.*)::([^ ]*)\"\n r\"( (.*)(PASSED|FAILED|ERROR|SKIPPED|XFAIL|RERUN|LEAKED).*| )$\"\n )\n\n out: defaultdict[tuple[str, str], set[str | None]] = defaultdict(set)\n\n for row in rows:\n m = match.match(row)\n if not m:\n continue\n\n fname = m.group(1)\n clsname = fname.replace(\"/\", \".\").replace(\".py\", \"\").replace(\"::\", \".\")\n\n tname = m.group(2).strip()\n if m.group(4) and \"]\" in m.group(4):\n tname += \" \" + m.group(4).split(\"]\")[0] + \"]\"\n\n outcome = m.group(5)\n assert outcome in OUTCOMES\n if outcome not in {\"RERUN\", \"LEAKED\"}:\n out[clsname, tname].add(outcome)\n\n return [(clsname, tname, outcomes) for (clsname, tname), outcomes in out.items()]\n\n\ndef build_xml(rows: list[tuple[str, str, set[str | None]]]) -> None:\n cnt = Counter(outcome for _, _, outcomes in rows for outcome in outcomes)\n timestamp = datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n # We could have used ElementTree but it feels like overkill here\n print('<?xml version=\"1.0\" encoding=\"utf-8\"?>')\n print(\"<testsuites>\")\n print(\n '<testsuite name=\"distributed\" '\n f'errors=\"{cnt[\"ERROR\"]}\" failures=\"{cnt[\"FAILED\"] + cnt[None]}\" '\n f'skipped=\"{cnt[\"SKIPPED\"] + cnt[\"XFAIL\"]}\" tests=\"{sum(cnt.values())}\" '\n f'time=\"0.0\" timestamp=\"{timestamp}\" hostname=\"\">'\n )\n\n for clsname, tname, outcomes in rows:\n print(f'<testcase classname=\"{clsname}\" name=\"{tname}\" time=\"0.0\"', end=\"\")\n if outcomes == {\"PASSED\"}:\n print(\" />\")\n elif outcomes == {\"FAILED\"}:\n print('><failure message=\"\"></failure></testcase>')\n elif outcomes == {None}:\n print('><failure message=\"pytest-timeout exceeded\"></failure></testcase>')\n elif outcomes == {\"ERROR\"}:\n print('><error message=\"failed on setup\"></error></testcase>')\n elif outcomes == {\"PASSED\", \"ERROR\"}:\n print('><error message=\"failed on teardown\"></error></testcase>')\n elif outcomes == {\"FAILED\", \"ERROR\"}:\n print(\n '><failure message=\"\"></failure></testcase>\\n'\n f'<testcase classname=\"{clsname}\" name=\"{tname}\" time=\"0.0\">'\n '<error message=\"failed on teardown\"></error></testcase>'\n )\n elif outcomes == {\"SKIPPED\"}:\n print('><skipped type=\"pytest.skip\" message=\"skip\"></skipped></testcase>')\n elif outcomes == {\"XFAIL\"}:\n print('><skipped type=\"pytest.xfail\" message=\"xfail\"></skipped></testcase>')\n else: # pragma: nocover\n # This should be unreachable. We would normally raise ValueError, except\n # that a crash in this script would be pretty much invisible.\n print(\n f' />\\n<testcase classname=\"parse_stdout\" name=\"build_xml\" time=\"0.0\">'\n f'><failure message=\"Unexpected {outcomes=}\"></failure></testcase>'\n )\n\n print(\"</testsuite>\")\n print(\"</testsuites>\")\n\n\ndef main() -> None: # pragma: nocover\n build_xml(parse_rows(sys.stdin))\n\n\nif __name__ == \"__main__\":\n main() # pragma: nocover\n", "path": "continuous_integration/scripts/parse_stdout.py"}], "after_files": [{"content": "\"\"\"On Windows, pytest-timeout kills off the whole test suite, leaving no junit report\nbehind. Parse the stdout of pytest to generate one.\n\"\"\"\nfrom __future__ import annotations\n\nimport html\nimport re\nimport sys\nfrom collections import Counter, defaultdict\nfrom collections.abc import Iterable\nfrom datetime import datetime\n\nOUTCOMES = {\n \"PASSED\",\n \"FAILED\",\n # Test timeout. Marked as a variant of FAILED in the junit report\n None,\n # Setup failed or teardown failed.\n # In the latter case, if the test also failed, show both a FAILED and an ERROR line.\n \"ERROR\",\n # @pytest.mark.skip, @pytest.mark.skipif, or raise pytest.skip()\n \"SKIPPED\",\n # Reported as a variant of SKIPPED in the junit report\n \"XFAIL\",\n # These appear respectively before and after another status. Ignore.\n \"RERUN\",\n \"LEAKED\",\n}\n\n\ndef parse_rows(rows: Iterable[str]) -> list[tuple[str, str, set[str | None]]]:\n match = re.compile(\n r\"(distributed/.*test.*)::([^ ]*)\"\n r\"( (.*)(PASSED|FAILED|ERROR|SKIPPED|XFAIL|RERUN|LEAKED).*| )$\"\n )\n\n out: defaultdict[tuple[str, str], set[str | None]] = defaultdict(set)\n\n for row in rows:\n m = match.match(row)\n if not m:\n continue\n\n fname = m.group(1)\n clsname = fname.replace(\"/\", \".\").replace(\".py\", \"\").replace(\"::\", \".\")\n\n tname = m.group(2).strip()\n if m.group(4) and \"]\" in m.group(4):\n tname += \" \" + m.group(4).split(\"]\")[0] + \"]\"\n\n outcome = m.group(5)\n assert outcome in OUTCOMES\n if outcome not in {\"RERUN\", \"LEAKED\"}:\n out[clsname, tname].add(outcome)\n\n return [(clsname, tname, outcomes) for (clsname, tname), outcomes in out.items()]\n\n\ndef build_xml(rows: list[tuple[str, str, set[str | None]]]) -> None:\n cnt = Counter(outcome for _, _, outcomes in rows for outcome in outcomes)\n timestamp = datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n # We could have used ElementTree but it feels like overkill here\n print('<?xml version=\"1.0\" encoding=\"utf-8\"?>')\n print(\"<testsuites>\")\n print(\n '<testsuite name=\"distributed\" '\n f'errors=\"{cnt[\"ERROR\"]}\" failures=\"{cnt[\"FAILED\"] + cnt[None]}\" '\n f'skipped=\"{cnt[\"SKIPPED\"] + cnt[\"XFAIL\"]}\" tests=\"{sum(cnt.values())}\" '\n f'time=\"0.0\" timestamp=\"{timestamp}\" hostname=\"\">'\n )\n\n for clsname, tname, outcomes in rows:\n clsname = html.escape(clsname)\n tname = html.escape(tname)\n print(f'<testcase classname=\"{clsname}\" name=\"{tname}\" time=\"0.0\"', end=\"\")\n if outcomes == {\"PASSED\"}:\n print(\" />\")\n elif outcomes == {\"FAILED\"}:\n print('><failure message=\"\"></failure></testcase>')\n elif outcomes == {None}:\n print('><failure message=\"pytest-timeout exceeded\"></failure></testcase>')\n elif outcomes == {\"ERROR\"}:\n print('><error message=\"failed on setup\"></error></testcase>')\n elif outcomes == {\"PASSED\", \"ERROR\"}:\n print('><error message=\"failed on teardown\"></error></testcase>')\n elif outcomes == {\"FAILED\", \"ERROR\"}:\n print(\n '><failure message=\"\"></failure></testcase>\\n'\n f'<testcase classname=\"{clsname}\" name=\"{tname}\" time=\"0.0\">'\n '<error message=\"failed on teardown\"></error></testcase>'\n )\n elif outcomes == {\"SKIPPED\"}:\n print('><skipped type=\"pytest.skip\" message=\"skip\"></skipped></testcase>')\n elif outcomes == {\"XFAIL\"}:\n print('><skipped type=\"pytest.xfail\" message=\"xfail\"></skipped></testcase>')\n else: # pragma: nocover\n # This should be unreachable. We would normally raise ValueError, except\n # that a crash in this script would be pretty much invisible.\n print(\n f' />\\n<testcase classname=\"parse_stdout\" name=\"build_xml\" time=\"0.0\">'\n f'><failure message=\"Unexpected {outcomes=}\"></failure></testcase>'\n )\n\n print(\"</testsuite>\")\n print(\"</testsuites>\")\n\n\ndef main() -> None: # pragma: nocover\n build_xml(parse_rows(sys.stdin))\n\n\nif __name__ == \"__main__\":\n main() # pragma: nocover\n", "path": "continuous_integration/scripts/parse_stdout.py"}]}
1,680
165
gh_patches_debug_9502
rasdani/github-patches
git_diff
redis__redis-py-2112
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- Support CASESENSITIVE tag in Tag Field link: https://oss.redis.com/redisearch/Commands/#ftcreate --- END ISSUE --- Below are some code segments, each from a relevant file. One or more of these files may contain bugs. --- BEGIN FILES --- Path: `redis/commands/search/field.py` Content: ``` 1 from typing import List 2 3 from redis import DataError 4 5 6 class Field: 7 8 NUMERIC = "NUMERIC" 9 TEXT = "TEXT" 10 WEIGHT = "WEIGHT" 11 GEO = "GEO" 12 TAG = "TAG" 13 VECTOR = "VECTOR" 14 SORTABLE = "SORTABLE" 15 NOINDEX = "NOINDEX" 16 AS = "AS" 17 18 def __init__( 19 self, 20 name: str, 21 args: List[str] = None, 22 sortable: bool = False, 23 no_index: bool = False, 24 as_name: str = None, 25 ): 26 if args is None: 27 args = [] 28 self.name = name 29 self.args = args 30 self.args_suffix = list() 31 self.as_name = as_name 32 33 if sortable: 34 self.args_suffix.append(Field.SORTABLE) 35 if no_index: 36 self.args_suffix.append(Field.NOINDEX) 37 38 if no_index and not sortable: 39 raise ValueError("Non-Sortable non-Indexable fields are ignored") 40 41 def append_arg(self, value): 42 self.args.append(value) 43 44 def redis_args(self): 45 args = [self.name] 46 if self.as_name: 47 args += [self.AS, self.as_name] 48 args += self.args 49 args += self.args_suffix 50 return args 51 52 53 class TextField(Field): 54 """ 55 TextField is used to define a text field in a schema definition 56 """ 57 58 NOSTEM = "NOSTEM" 59 PHONETIC = "PHONETIC" 60 61 def __init__( 62 self, 63 name: str, 64 weight: float = 1.0, 65 no_stem: bool = False, 66 phonetic_matcher: str = None, 67 **kwargs, 68 ): 69 Field.__init__(self, name, args=[Field.TEXT, Field.WEIGHT, weight], **kwargs) 70 71 if no_stem: 72 Field.append_arg(self, self.NOSTEM) 73 if phonetic_matcher and phonetic_matcher in [ 74 "dm:en", 75 "dm:fr", 76 "dm:pt", 77 "dm:es", 78 ]: 79 Field.append_arg(self, self.PHONETIC) 80 Field.append_arg(self, phonetic_matcher) 81 82 83 class NumericField(Field): 84 """ 85 NumericField is used to define a numeric field in a schema definition 86 """ 87 88 def __init__(self, name: str, **kwargs): 89 Field.__init__(self, name, args=[Field.NUMERIC], **kwargs) 90 91 92 class GeoField(Field): 93 """ 94 GeoField is used to define a geo-indexing field in a schema definition 95 """ 96 97 def __init__(self, name: str, **kwargs): 98 Field.__init__(self, name, args=[Field.GEO], **kwargs) 99 100 101 class TagField(Field): 102 """ 103 TagField is a tag-indexing field with simpler compression and tokenization. 104 See http://redisearch.io/Tags/ 105 """ 106 107 SEPARATOR = "SEPARATOR" 108 109 def __init__(self, name: str, separator: str = ",", **kwargs): 110 Field.__init__( 111 self, name, args=[Field.TAG, self.SEPARATOR, separator], **kwargs 112 ) 113 114 115 class VectorField(Field): 116 """ 117 Allows vector similarity queries against the value in this attribute. 118 See https://oss.redis.com/redisearch/Vectors/#vector_fields. 119 """ 120 121 def __init__(self, name: str, algorithm: str, attributes: dict, **kwargs): 122 """ 123 Create Vector Field. Notice that Vector cannot have sortable or no_index tag, 124 although it's also a Field. 125 126 ``name`` is the name of the field. 127 128 ``algorithm`` can be "FLAT" or "HNSW". 129 130 ``attributes`` each algorithm can have specific attributes. Some of them 131 are mandatory and some of them are optional. See 132 https://oss.redis.com/redisearch/master/Vectors/#specific_creation_attributes_per_algorithm 133 for more information. 134 """ 135 sort = kwargs.get("sortable", False) 136 noindex = kwargs.get("no_index", False) 137 138 if sort or noindex: 139 raise DataError("Cannot set 'sortable' or 'no_index' in Vector fields.") 140 141 if algorithm.upper() not in ["FLAT", "HNSW"]: 142 raise DataError( 143 "Realtime vector indexing supporting 2 Indexing Methods:" 144 "'FLAT' and 'HNSW'." 145 ) 146 147 attr_li = [] 148 149 for key, value in attributes.items(): 150 attr_li.extend([key, value]) 151 152 Field.__init__( 153 self, 154 name, 155 args=[Field.VECTOR, algorithm, len(attr_li), *attr_li], 156 **kwargs, 157 ) 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/redis/commands/search/field.py b/redis/commands/search/field.py --- a/redis/commands/search/field.py +++ b/redis/commands/search/field.py @@ -105,11 +105,20 @@ """ SEPARATOR = "SEPARATOR" + CASESENSITIVE = "CASESENSITIVE" - def __init__(self, name: str, separator: str = ",", **kwargs): - Field.__init__( - self, name, args=[Field.TAG, self.SEPARATOR, separator], **kwargs - ) + def __init__( + self, + name: str, + separator: str = ",", + case_sensitive: bool = False, + **kwargs, + ): + args = [Field.TAG, self.SEPARATOR, separator] + if case_sensitive: + args.append(self.CASESENSITIVE) + + Field.__init__(self, name, args=args, **kwargs) class VectorField(Field):
{"golden_diff": "diff --git a/redis/commands/search/field.py b/redis/commands/search/field.py\n--- a/redis/commands/search/field.py\n+++ b/redis/commands/search/field.py\n@@ -105,11 +105,20 @@\n \"\"\"\n \n SEPARATOR = \"SEPARATOR\"\n+ CASESENSITIVE = \"CASESENSITIVE\"\n \n- def __init__(self, name: str, separator: str = \",\", **kwargs):\n- Field.__init__(\n- self, name, args=[Field.TAG, self.SEPARATOR, separator], **kwargs\n- )\n+ def __init__(\n+ self,\n+ name: str,\n+ separator: str = \",\",\n+ case_sensitive: bool = False,\n+ **kwargs,\n+ ):\n+ args = [Field.TAG, self.SEPARATOR, separator]\n+ if case_sensitive:\n+ args.append(self.CASESENSITIVE)\n+\n+ Field.__init__(self, name, args=args, **kwargs)\n \n \n class VectorField(Field):\n", "issue": "Support CASESENSITIVE tag in Tag Field \nlink: https://oss.redis.com/redisearch/Commands/#ftcreate\n", "before_files": [{"content": "from typing import List\n\nfrom redis import DataError\n\n\nclass Field:\n\n NUMERIC = \"NUMERIC\"\n TEXT = \"TEXT\"\n WEIGHT = \"WEIGHT\"\n GEO = \"GEO\"\n TAG = \"TAG\"\n VECTOR = \"VECTOR\"\n SORTABLE = \"SORTABLE\"\n NOINDEX = \"NOINDEX\"\n AS = \"AS\"\n\n def __init__(\n self,\n name: str,\n args: List[str] = None,\n sortable: bool = False,\n no_index: bool = False,\n as_name: str = None,\n ):\n if args is None:\n args = []\n self.name = name\n self.args = args\n self.args_suffix = list()\n self.as_name = as_name\n\n if sortable:\n self.args_suffix.append(Field.SORTABLE)\n if no_index:\n self.args_suffix.append(Field.NOINDEX)\n\n if no_index and not sortable:\n raise ValueError(\"Non-Sortable non-Indexable fields are ignored\")\n\n def append_arg(self, value):\n self.args.append(value)\n\n def redis_args(self):\n args = [self.name]\n if self.as_name:\n args += [self.AS, self.as_name]\n args += self.args\n args += self.args_suffix\n return args\n\n\nclass TextField(Field):\n \"\"\"\n TextField is used to define a text field in a schema definition\n \"\"\"\n\n NOSTEM = \"NOSTEM\"\n PHONETIC = \"PHONETIC\"\n\n def __init__(\n self,\n name: str,\n weight: float = 1.0,\n no_stem: bool = False,\n phonetic_matcher: str = None,\n **kwargs,\n ):\n Field.__init__(self, name, args=[Field.TEXT, Field.WEIGHT, weight], **kwargs)\n\n if no_stem:\n Field.append_arg(self, self.NOSTEM)\n if phonetic_matcher and phonetic_matcher in [\n \"dm:en\",\n \"dm:fr\",\n \"dm:pt\",\n \"dm:es\",\n ]:\n Field.append_arg(self, self.PHONETIC)\n Field.append_arg(self, phonetic_matcher)\n\n\nclass NumericField(Field):\n \"\"\"\n NumericField is used to define a numeric field in a schema definition\n \"\"\"\n\n def __init__(self, name: str, **kwargs):\n Field.__init__(self, name, args=[Field.NUMERIC], **kwargs)\n\n\nclass GeoField(Field):\n \"\"\"\n GeoField is used to define a geo-indexing field in a schema definition\n \"\"\"\n\n def __init__(self, name: str, **kwargs):\n Field.__init__(self, name, args=[Field.GEO], **kwargs)\n\n\nclass TagField(Field):\n \"\"\"\n TagField is a tag-indexing field with simpler compression and tokenization.\n See http://redisearch.io/Tags/\n \"\"\"\n\n SEPARATOR = \"SEPARATOR\"\n\n def __init__(self, name: str, separator: str = \",\", **kwargs):\n Field.__init__(\n self, name, args=[Field.TAG, self.SEPARATOR, separator], **kwargs\n )\n\n\nclass VectorField(Field):\n \"\"\"\n Allows vector similarity queries against the value in this attribute.\n See https://oss.redis.com/redisearch/Vectors/#vector_fields.\n \"\"\"\n\n def __init__(self, name: str, algorithm: str, attributes: dict, **kwargs):\n \"\"\"\n Create Vector Field. Notice that Vector cannot have sortable or no_index tag,\n although it's also a Field.\n\n ``name`` is the name of the field.\n\n ``algorithm`` can be \"FLAT\" or \"HNSW\".\n\n ``attributes`` each algorithm can have specific attributes. Some of them\n are mandatory and some of them are optional. See\n https://oss.redis.com/redisearch/master/Vectors/#specific_creation_attributes_per_algorithm\n for more information.\n \"\"\"\n sort = kwargs.get(\"sortable\", False)\n noindex = kwargs.get(\"no_index\", False)\n\n if sort or noindex:\n raise DataError(\"Cannot set 'sortable' or 'no_index' in Vector fields.\")\n\n if algorithm.upper() not in [\"FLAT\", \"HNSW\"]:\n raise DataError(\n \"Realtime vector indexing supporting 2 Indexing Methods:\"\n \"'FLAT' and 'HNSW'.\"\n )\n\n attr_li = []\n\n for key, value in attributes.items():\n attr_li.extend([key, value])\n\n Field.__init__(\n self,\n name,\n args=[Field.VECTOR, algorithm, len(attr_li), *attr_li],\n **kwargs,\n )\n", "path": "redis/commands/search/field.py"}], "after_files": [{"content": "from typing import List\n\nfrom redis import DataError\n\n\nclass Field:\n\n NUMERIC = \"NUMERIC\"\n TEXT = \"TEXT\"\n WEIGHT = \"WEIGHT\"\n GEO = \"GEO\"\n TAG = \"TAG\"\n VECTOR = \"VECTOR\"\n SORTABLE = \"SORTABLE\"\n NOINDEX = \"NOINDEX\"\n AS = \"AS\"\n\n def __init__(\n self,\n name: str,\n args: List[str] = None,\n sortable: bool = False,\n no_index: bool = False,\n as_name: str = None,\n ):\n if args is None:\n args = []\n self.name = name\n self.args = args\n self.args_suffix = list()\n self.as_name = as_name\n\n if sortable:\n self.args_suffix.append(Field.SORTABLE)\n if no_index:\n self.args_suffix.append(Field.NOINDEX)\n\n if no_index and not sortable:\n raise ValueError(\"Non-Sortable non-Indexable fields are ignored\")\n\n def append_arg(self, value):\n self.args.append(value)\n\n def redis_args(self):\n args = [self.name]\n if self.as_name:\n args += [self.AS, self.as_name]\n args += self.args\n args += self.args_suffix\n return args\n\n\nclass TextField(Field):\n \"\"\"\n TextField is used to define a text field in a schema definition\n \"\"\"\n\n NOSTEM = \"NOSTEM\"\n PHONETIC = \"PHONETIC\"\n\n def __init__(\n self,\n name: str,\n weight: float = 1.0,\n no_stem: bool = False,\n phonetic_matcher: str = None,\n **kwargs,\n ):\n Field.__init__(self, name, args=[Field.TEXT, Field.WEIGHT, weight], **kwargs)\n\n if no_stem:\n Field.append_arg(self, self.NOSTEM)\n if phonetic_matcher and phonetic_matcher in [\n \"dm:en\",\n \"dm:fr\",\n \"dm:pt\",\n \"dm:es\",\n ]:\n Field.append_arg(self, self.PHONETIC)\n Field.append_arg(self, phonetic_matcher)\n\n\nclass NumericField(Field):\n \"\"\"\n NumericField is used to define a numeric field in a schema definition\n \"\"\"\n\n def __init__(self, name: str, **kwargs):\n Field.__init__(self, name, args=[Field.NUMERIC], **kwargs)\n\n\nclass GeoField(Field):\n \"\"\"\n GeoField is used to define a geo-indexing field in a schema definition\n \"\"\"\n\n def __init__(self, name: str, **kwargs):\n Field.__init__(self, name, args=[Field.GEO], **kwargs)\n\n\nclass TagField(Field):\n \"\"\"\n TagField is a tag-indexing field with simpler compression and tokenization.\n See http://redisearch.io/Tags/\n \"\"\"\n\n SEPARATOR = \"SEPARATOR\"\n CASESENSITIVE = \"CASESENSITIVE\"\n\n def __init__(\n self,\n name: str,\n separator: str = \",\",\n case_sensitive: bool = False,\n **kwargs,\n ):\n args = [Field.TAG, self.SEPARATOR, separator]\n if case_sensitive:\n args.append(self.CASESENSITIVE)\n\n Field.__init__(self, name, args=args, **kwargs)\n\n\nclass VectorField(Field):\n \"\"\"\n Allows vector similarity queries against the value in this attribute.\n See https://oss.redis.com/redisearch/Vectors/#vector_fields.\n \"\"\"\n\n def __init__(self, name: str, algorithm: str, attributes: dict, **kwargs):\n \"\"\"\n Create Vector Field. Notice that Vector cannot have sortable or no_index tag,\n although it's also a Field.\n\n ``name`` is the name of the field.\n\n ``algorithm`` can be \"FLAT\" or \"HNSW\".\n\n ``attributes`` each algorithm can have specific attributes. Some of them\n are mandatory and some of them are optional. See\n https://oss.redis.com/redisearch/master/Vectors/#specific_creation_attributes_per_algorithm\n for more information.\n \"\"\"\n sort = kwargs.get(\"sortable\", False)\n noindex = kwargs.get(\"no_index\", False)\n\n if sort or noindex:\n raise DataError(\"Cannot set 'sortable' or 'no_index' in Vector fields.\")\n\n if algorithm.upper() not in [\"FLAT\", \"HNSW\"]:\n raise DataError(\n \"Realtime vector indexing supporting 2 Indexing Methods:\"\n \"'FLAT' and 'HNSW'.\"\n )\n\n attr_li = []\n\n for key, value in attributes.items():\n attr_li.extend([key, value])\n\n Field.__init__(\n self,\n name,\n args=[Field.VECTOR, algorithm, len(attr_li), *attr_li],\n **kwargs,\n )\n", "path": "redis/commands/search/field.py"}]}
1,680
230
gh_patches_debug_61829
rasdani/github-patches
git_diff
pulp__pulpcore-4010
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_10948
rasdani/github-patches
git_diff
dmlc__dgl-1305
We are currently solving the following issue within our repository. Here is the issue text: --- BEGIN ISSUE --- AttributeError: module 'dgl.nn' has no attribute 'pytorch' ## 🐛 Bug When I try to use some of the predefined modules of dgl by the following code, I encounter an error: AttributeError: module 'dgl.nn' has no attribute 'pytorch'. Similar problems also happen to other backends, including TensorFlow and MXNet. ## To Reproduce Steps to reproduce the behavior: ```python import dgl.nn # or import dgl c = dgl.nn.pytorch.conv.GraphConv(10,2) ``` ## Expected behavior The code should generate a GraphConv layer without any error. ## Environment - DGL Version (e.g., 1.0): 0.4.2 - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): Pytorch 1.4.0 - OS (e.g., Linux): Irrelelevent - How you installed DGL (`conda`, `pip`, source): conda - Build command you used (if compiling from source): - Python version: 3.7 - CUDA/cuDNN version (if applicable): Irrelelevent - GPU models and configuration (e.g. V100): Irrelelevent - Any other relevant information: ## Additional context I read the source code and **found the reason and solution** to this problem. ### Reason: The `__init__.py` file of `dgl/nn` is empty. Therefore, if i import dgl or dgl.nn, python cannot automatically find files of its sub-directories. I verified it by the following code: ```python import dgl.nn.python c = dgl.nn.pytorch.conv.GraphConv(10,2) ``` It works fine. ### Solution: Add 3 lines of code like `from . import pytorch` into file `dgl/nn/__init__.py` for PyTorch and the other 2 backends. It is better to automatically detect the backend library and import the correct sub-directory. --- 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/dgl/__init__.py` Content: ``` 1 """DGL root package.""" 2 # Windows compatibility 3 # This initializes Winsock and performs cleanup at termination as required 4 import socket 5 6 # Need to ensure that the backend framework is imported before load dgl libs, 7 # otherwise weird cuda problem happens 8 from .backend import load_backend 9 10 from . import function 11 from . import nn 12 from . import contrib 13 from . import container 14 from . import random 15 from . import sampling 16 17 from ._ffi.runtime_ctypes import TypeCode 18 from ._ffi.function import register_func, get_global_func, list_global_func_names, extract_ext_funcs 19 from ._ffi.base import DGLError, __version__ 20 21 from .base import ALL, NTYPE, NID, ETYPE, EID 22 from .readout import * 23 from .batched_heterograph import * 24 from .convert import * 25 from .graph import DGLGraph, batch, unbatch 26 from .generators import * 27 from .heterograph import DGLHeteroGraph 28 from .nodeflow import * 29 from .traversal import * 30 from .transform import * 31 from .propagate import * 32 from .udf import NodeBatch, EdgeBatch 33 ``` Path: `python/dgl/nn/__init__.py` Content: ``` 1 """Package for neural network common components.""" 2 ``` --- 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/dgl/__init__.py b/python/dgl/__init__.py --- a/python/dgl/__init__.py +++ b/python/dgl/__init__.py @@ -8,7 +8,6 @@ from .backend import load_backend from . import function -from . import nn from . import contrib from . import container from . import random diff --git a/python/dgl/nn/__init__.py b/python/dgl/nn/__init__.py --- a/python/dgl/nn/__init__.py +++ b/python/dgl/nn/__init__.py @@ -1 +1,12 @@ """Package for neural network common components.""" +import importlib +import sys +from ..backend import backend_name + +def _load_backend(mod_name): + mod = importlib.import_module('.%s' % mod_name, __name__) + thismod = sys.modules[__name__] + for api, obj in mod.__dict__.items(): + setattr(thismod, api, obj) + +_load_backend(backend_name)
{"golden_diff": "diff --git a/python/dgl/__init__.py b/python/dgl/__init__.py\n--- a/python/dgl/__init__.py\n+++ b/python/dgl/__init__.py\n@@ -8,7 +8,6 @@\n from .backend import load_backend\n \n from . import function\n-from . import nn\n from . import contrib\n from . import container\n from . import random\ndiff --git a/python/dgl/nn/__init__.py b/python/dgl/nn/__init__.py\n--- a/python/dgl/nn/__init__.py\n+++ b/python/dgl/nn/__init__.py\n@@ -1 +1,12 @@\n \"\"\"Package for neural network common components.\"\"\"\n+import importlib\n+import sys\n+from ..backend import backend_name\n+\n+def _load_backend(mod_name):\n+ mod = importlib.import_module('.%s' % mod_name, __name__)\n+ thismod = sys.modules[__name__]\n+ for api, obj in mod.__dict__.items():\n+ setattr(thismod, api, obj)\n+\n+_load_backend(backend_name)\n", "issue": "AttributeError: module 'dgl.nn' has no attribute 'pytorch'\n## \ud83d\udc1b Bug\r\n\r\nWhen I try to use some of the predefined modules of dgl by the following code, I encounter an error: AttributeError: module 'dgl.nn' has no attribute 'pytorch'.\r\n\r\nSimilar problems also happen to other backends, including TensorFlow and MXNet.\r\n\r\n## To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n```python\r\nimport dgl.nn\r\n# or import dgl\r\nc = dgl.nn.pytorch.conv.GraphConv(10,2)\r\n```\r\n\r\n## Expected behavior\r\n\r\nThe code should generate a GraphConv layer without any error.\r\n\r\n## Environment\r\n\r\n - DGL Version (e.g., 1.0): 0.4.2\r\n - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): Pytorch 1.4.0\r\n - OS (e.g., Linux): Irrelelevent \r\n - How you installed DGL (`conda`, `pip`, source): conda\r\n - Build command you used (if compiling from source):\r\n - Python version: 3.7\r\n - CUDA/cuDNN version (if applicable): Irrelelevent \r\n - GPU models and configuration (e.g. V100): Irrelelevent \r\n - Any other relevant information:\r\n\r\n## Additional context\r\n\r\nI read the source code and **found the reason and solution** to this problem.\r\n\r\n### Reason:\r\n\r\nThe `__init__.py` file of `dgl/nn` is empty. Therefore, if i import dgl or dgl.nn, python cannot automatically find files of its sub-directories.\r\n\r\nI verified it by the following code:\r\n```python\r\nimport dgl.nn.python\r\nc = dgl.nn.pytorch.conv.GraphConv(10,2)\r\n```\r\nIt works fine.\r\n\r\n### Solution:\r\n\r\nAdd 3 lines of code like `from . import pytorch` into file `dgl/nn/__init__.py` for PyTorch and the other 2 backends.\r\nIt is better to automatically detect the backend library and import the correct sub-directory.\n", "before_files": [{"content": "\"\"\"DGL root package.\"\"\"\n# Windows compatibility\n# This initializes Winsock and performs cleanup at termination as required\nimport socket\n\n# Need to ensure that the backend framework is imported before load dgl libs,\n# otherwise weird cuda problem happens\nfrom .backend import load_backend\n\nfrom . import function\nfrom . import nn\nfrom . import contrib\nfrom . import container\nfrom . import random\nfrom . import sampling\n\nfrom ._ffi.runtime_ctypes import TypeCode\nfrom ._ffi.function import register_func, get_global_func, list_global_func_names, extract_ext_funcs\nfrom ._ffi.base import DGLError, __version__\n\nfrom .base import ALL, NTYPE, NID, ETYPE, EID\nfrom .readout import *\nfrom .batched_heterograph import *\nfrom .convert import *\nfrom .graph import DGLGraph, batch, unbatch\nfrom .generators import *\nfrom .heterograph import DGLHeteroGraph\nfrom .nodeflow import *\nfrom .traversal import *\nfrom .transform import *\nfrom .propagate import *\nfrom .udf import NodeBatch, EdgeBatch\n", "path": "python/dgl/__init__.py"}, {"content": "\"\"\"Package for neural network common components.\"\"\"\n", "path": "python/dgl/nn/__init__.py"}], "after_files": [{"content": "\"\"\"DGL root package.\"\"\"\n# Windows compatibility\n# This initializes Winsock and performs cleanup at termination as required\nimport socket\n\n# Need to ensure that the backend framework is imported before load dgl libs,\n# otherwise weird cuda problem happens\nfrom .backend import load_backend\n\nfrom . import function\nfrom . import contrib\nfrom . import container\nfrom . import random\nfrom . import sampling\n\nfrom ._ffi.runtime_ctypes import TypeCode\nfrom ._ffi.function import register_func, get_global_func, list_global_func_names, extract_ext_funcs\nfrom ._ffi.base import DGLError, __version__\n\nfrom .base import ALL, NTYPE, NID, ETYPE, EID\nfrom .readout import *\nfrom .batched_heterograph import *\nfrom .convert import *\nfrom .graph import DGLGraph, batch, unbatch\nfrom .generators import *\nfrom .heterograph import DGLHeteroGraph\nfrom .nodeflow import *\nfrom .traversal import *\nfrom .transform import *\nfrom .propagate import *\nfrom .udf import NodeBatch, EdgeBatch\n", "path": "python/dgl/__init__.py"}, {"content": "\"\"\"Package for neural network common components.\"\"\"\nimport importlib\nimport sys\nfrom ..backend import backend_name\n\ndef _load_backend(mod_name):\n mod = importlib.import_module('.%s' % mod_name, __name__)\n thismod = sys.modules[__name__]\n for api, obj in mod.__dict__.items():\n setattr(thismod, api, obj)\n\n_load_backend(backend_name)\n", "path": "python/dgl/nn/__init__.py"}]}
1,034
234