internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: Bitmessage/PyBitmessage

Issue:
extPort bug
I think `extPort` was incorrectly refactored, and references in `src/protocol.py` to `state.extPort` should be replaced with `BMConfigParser().safeGetInt('bitmessagesettings', 'extport')`.


Discussion:

Resolving patch:
diff --git a/src/protocol.py b/src/protocol.py
--- a/src/protocol.py
+++ b/src/protocol.py
@@ -276,14 +276,18 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
     )
     # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
     payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack('>L', 2130706433)
-    # we have a separate extPort and incoming over clearnet or outgoing through clearnet
-    if BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and state.extPort \
-        and ((server and not checkSocksIP(remoteHost)) or
-             (BMConfigParser().get("bitmessagesettings", "socksproxytype") == "none" and not server)):
-        payload += pack('>H', state.extPort)
+    # we have a separate extPort and incoming over clearnet
+    # or outgoing through clearnet
+    extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport')
+    if (
+        extport and ((server and not checkSocksIP(remoteHost)) or (
+            BMConfigParser().get('bitmessagesettings', 'socksproxytype') ==
+            'none' and not server))
+    ):
+        payload += pack('>H', extport)
     elif checkSocksIP(remoteHost) and server:  # incoming connection over Tor
         payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'onionport'))
-    else:  # no extPort and not incoming over Tor
+    else:  # no extport and not incoming over Tor
         payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'port'))
 
     random.seed()
diff --git a/src/upnp.py b/src/upnp.py
--- a/src/upnp.py
+++ b/src/upnp.py
@@ -17,7 +17,6 @@
 from xml.dom.minidom import Document, parseString
 
 import queues
-import shared
 import state
 import tr
 from bmconfigparser import BMConfigParser
@@ -286,7 +285,6 @@ def run(self):
             if router.extPort is not None:
                 deleted = True
                 self.deletePortMapping(router)
-        shared.extPort = None
         if deleted:
             queues.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed')))
         logger.debug("UPnP thread done")
@@ -333,7 +331,6 @@ def createPortMapping(self, router):
                     self.localPort,
                     extPort)
                 router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage')
-                shared.extPort = extPort
                 self.extPort = extPort
                 BMConfigParser().set('bitmessagesettings', 'extport', str(extPort))
                 BMConfigParser().save()


Test patch:
Repository: Bitmessage/PyBitmessage

Issue:
SQL statement error when deleting in QT interface
`2019-08-16 08:12:03,023 - CRITICAL - Major error occurred when trying to execute
 a SQL statement within the sqlThread. Please tell Atheros about this error mess
age or post it in the forum! Error occurred while trying to execute statement: "
DELETE FROM inbox"  Here are the parameters; you might want to censor this data 
with asterisks (***) as it can contain private information: ('REDACTED',). Here is the actual error message thrown by the sqlThread: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.`

There was an independent report in a chan, but I somehow triggered it as well. @g1itch you did some refactoring with this recently, can you check it out?


Discussion:
Where it appeared? While deleting from which folder? Because I cannot reproduce it by deleting from chan's inbox. And more strange there is no result for `grep -r " DELETE FROM inbox" src`. I cannot found delete statement with leading space.
Oh, I see. You are deleting from trash. Maybe some regression in 0c1e5169
Yes, I believe it was from trash, but I'm not 100% sure.
```diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py
index 507e6ca0..2c5f1485 100644
--- a/src/bitmessageqt/__init__.py
+++ b/src/bitmessageqt/__init__.py
@@ -3270,8 +3270,8 @@ class MyForm(settingsmixin.SMainWindow):
             tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1)
         idCount = len(inventoryHashesToTrash)
         sqlExecuteChunked(
-            "DELETE FROM inbox" if folder == "trash" or shifted else
-            "UPDATE inbox SET folder='trash'"
+            ("DELETE FROM inbox" if folder == "trash" or shifted else
+             "UPDATE inbox SET folder='trash'") +
             " WHERE msgid IN ({0})", idCount, *inventoryHashesToTrash)
         tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
         tableWidget.setUpdatesEnabled(True)
```

String literals does not stick together in this case as I expected. My bad.
That makes sense.

Resolving patch:
diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py
--- a/src/bitmessageqt/__init__.py
+++ b/src/bitmessageqt/__init__.py
@@ -3270,8 +3270,8 @@ def on_action_InboxTrash(self):
             tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1)
         idCount = len(inventoryHashesToTrash)
         sqlExecuteChunked(
-            "DELETE FROM inbox" if folder == "trash" or shifted else
-            "UPDATE inbox SET folder='trash'"
+            ("DELETE FROM inbox" if folder == "trash" or shifted else
+             "UPDATE inbox SET folder='trash'") +
             " WHERE msgid IN ({0})", idCount, *inventoryHashesToTrash)
         tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
         tableWidget.setUpdatesEnabled(True)


Test patch:
Repository: Bitmessage/PyBitmessage

Issue:
BMProto.timeOffsetWrongCount unfinished
Forgot to finish it after moving to asyncore. There should be a check for a threshold, and a panel notification.


Discussion:
A related issue showed up when addressing this, the translation shouldn't be inside the network subsystem but in the UI. So at least the `bitmessageqt.UISignaler` should be refactored to do translations internally.
**EDIT** But this then creates problem with the translation preprocessor. I need to think about it.

Resolving patch:
diff --git a/src/network/tcp.py b/src/network/tcp.py
--- a/src/network/tcp.py
+++ b/src/network/tcp.py
@@ -2,6 +2,7 @@
 TCP protocol handler
 """
 # pylint: disable=too-many-ancestors
+import l10n
 import logging
 import math
 import random
@@ -29,11 +30,13 @@
 from network.tls import TLSDispatcher
 from node import Peer
 from queues import invQueue, receiveDataQueue, UISignalQueue
+from tr import _translate
 
 logger = logging.getLogger('default')
 
 
 maximumAgeOfNodesThatIAdvertiseToOthers = 10800  #: Equals three hours
+maximumTimeOffsetWrongCount = 3  #: Connections with wrong time offset
 
 
 class TCPConnection(BMProto, TLSDispatcher):
@@ -124,6 +127,22 @@ def antiIntersectionDelay(self, initial=False):
                     ' for %.2fs', delay)
                 self.skipUntil = time.time() + delay
 
+    def checkTimeOffsetNotification(self):
+        """
+        Check if we have connected to too many nodes which have too high
+        time offset from us
+        """
+        if BMProto.timeOffsetWrongCount > \
+                maximumTimeOffsetWrongCount and \
+                not self.fullyEstablished:
+            UISignalQueue.put((
+                'updateStatusBar',
+                _translate(
+                    "MainWindow",
+                    "The time on your computer, %1, may be wrong. "
+                    "Please verify your settings."
+                ).arg(l10n.formatTimestamp())))
+
     def state_connection_fully_established(self):
         """
         State after the bitmessage protocol handshake is completed
@@ -275,8 +294,10 @@ def handle_close(self):
                 knownnodes.addKnownNode(
                     self.streams, self.destination, time.time())
                 Dandelion().maybeRemoveStem(self)
-        elif host_is_global:
-            knownnodes.decreaseRating(self.destination)
+        else:
+            self.checkTimeOffsetNotification()
+            if host_is_global:
+                knownnodes.decreaseRating(self.destination)
         BMProto.handle_close(self)
 
 


Test patch:
Repository: Bitmessage/PyBitmessage

Issue:
Offline mode first time network settings
Reported in bitmessage chan:

> I am reporting a bug.
> To reproduce:
>
> 1. Backup $HOME/.config/PyBitmessage and remove the directory
> 2. Start bitmessagemain.py
> 3. When dialog popped, select "Work offline" and push "OK"
> 4. On "Settings" menu, go "Network Settings"
>   and select "Proxy server / Tor" "Type:" "SOCKS5",
>   then push "OK"
>   (In this case Tor is required, but I guess any changes may work)
> 5. Select "Network Status" tab, and wait few minutes
> 6. The client will be automatically connected to some nodes
>
> Tested on latest git version: commit e237534335d66748b27fb6251faf6cb72912ebd1

I'm not sure if this is just unintuitive UI, or there is a check to see if you're changing network settings for the first time which mis-checks.


Discussion:
It seems to be here: https://github.com/Bitmessage/PyBitmessage/commit/18392017c63c538f99fa0cf833c8d494b54bd449#diff-8c46c5f54d96f9eb2b91bb2b6bdd7d9fR316

Resolving patch:
diff --git a/src/bitmessageqt/__init__.py b/src/bitmessageqt/__init__.py
--- a/src/bitmessageqt/__init__.py
+++ b/src/bitmessageqt/__init__.py
@@ -1640,6 +1640,7 @@ def showConnectDialog(self):
         dialog = dialogs.ConnectDialog(self)
         if dialog.exec_():
             if dialog.radioButtonConnectNow.isChecked():
+                self.ui.updateNetworkSwitchMenuLabel(False)
                 BMConfigParser().remove_option(
                     'bitmessagesettings', 'dontconnect')
                 BMConfigParser().save()
diff --git a/src/bitmessageqt/settings.py b/src/bitmessageqt/settings.py
--- a/src/bitmessageqt/settings.py
+++ b/src/bitmessageqt/settings.py
@@ -49,6 +49,8 @@ def __init__(self, parent=None, firstrun=False):
         self.net_restart_needed = False
         self.timer = QtCore.QTimer()
 
+        if self.config.safeGetBoolean('bitmessagesettings', 'dontconnect'):
+            self.firstrun = False
         try:
             import pkg_resources
         except ImportError:
@@ -342,6 +344,8 @@ def accept(self):
         if proxytype_index == 0:
             if self._proxy_type and state.statusIconColor != 'red':
                 self.net_restart_needed = True
+        elif state.statusIconColor == 'red' and self.config.safeGetBoolean('bitmessagesettings', 'dontconnect'):
+            self.net_restart_needed = False
         elif self.comboBoxProxyType.currentText() != self._proxy_type:
             self.net_restart_needed = True
             self.parent.statusbar.clearMessage()


Test patch:
Repository: Bitmessage/PyBitmessage

Issue:
Object processor queue starts too early
Received a report. Looks like `objectProcessor` starts before `sqlThread` is ready. I can't actually reproduce it, it probably only happens ~if the `objectProcessorQueue` isn't empty~ under non-deterministic conditions. The problem was revealed in 184664d7583096e6cd7b828e08d112ff1727d81b. The solution is for the `objectProcessor.__init__` to wait for the `helper_sql.sql_ready` event.

```
2021-01-03 06:30:31,908 - CRITICAL - Unhandled exception
Traceback (most recent call last):
  File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 491, in <module>
  File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 487, in main
  File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 286, in start
  File "/home/*****/Documents/Software/PyBitmessage/src/class_objectProcessor.py", line 54, in __init__
    '''SELECT objecttype, data FROM objectprocessorqueue''')
  File "/home/*****/Documents/Software/PyBitmessage/src/helper_sql.py", line 44, in sqlQuery
    assert sql_available
AssertionError
Number of threads: 1

Operating system is Ubuntu 18.04.5 LTS 32-bit.
```


Discussion:

Resolving patch:
diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py
--- a/src/class_objectProcessor.py
+++ b/src/class_objectProcessor.py
@@ -29,7 +29,7 @@
 )
 from bmconfigparser import BMConfigParser
 from fallback import RIPEMD160Hash
-from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery
+from helper_sql import sql_ready, SqlBulkExecute, sqlExecute, sqlQuery
 from network import bmproto, knownnodes
 from network.node import Peer
 # pylint: disable=too-many-locals, too-many-return-statements, too-many-branches, too-many-statements
@@ -50,6 +50,7 @@ def __init__(self):
         # objectProcessorQueue. Assuming that Bitmessage wasn't closed
         # forcefully, it should have saved the data in the queue into the
         # objectprocessorqueue table. Let's pull it out.
+        sql_ready.wait()
         queryreturn = sqlQuery(
             '''SELECT objecttype, data FROM objectprocessorqueue''')
         for row in queryreturn:


Test patch:
Repository: Bitmessage/PyBitmessage

Issue:
Adding Protocol specification to docs (WIP)
I am slowly formatting Protocol Specification doc. I see some typos and mistakes in the wiki, which I also hope to fix.

[A quick preview](https://pybitmessage-test.readthedocs.io/en/doc/protocol.html)


Discussion:

Resolving patch:
diff --git a/docs/conf.py b/docs/conf.py
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -19,7 +19,7 @@
 # -- Project information -----------------------------------------------------
 
 project = u'PyBitmessage'
-copyright = u'2019, The Bitmessage Team'  # pylint: disable=redefined-builtin
+copyright = u'2019-2022, The Bitmessage Team'  # pylint: disable=redefined-builtin
 author = u'The Bitmessage Team'
 
 # The short X.Y version


Test patch:
Repository: cal-itp/benefits

Issue:
update favicon
current dev has old Cal-ITP Logo as favicon. 


Discussion:
https://github.com/cal-itp/transit-stop/blob/master/favicon.ico

Resolving patch:
diff --git a/benefits/core/views.py b/benefits/core/views.py
--- a/benefits/core/views.py
+++ b/benefits/core/views.py
@@ -22,7 +22,7 @@ def _index_content_title():
 
 def _index_image():
     """Helper returns a viewmodels.Image for the common index page."""
-    return viewmodels.Image("riderboardingbusandtapping.svg", pgettext("image alt text", "core.index.image"))
+    return viewmodels.Image("ridertappingbankcard.png", pgettext("image alt text", "core.index.image"))
 
 
 def _index_paragraphs():
diff --git a/benefits/discounts/views.py b/benefits/discounts/views.py
--- a/benefits/discounts/views.py
+++ b/benefits/discounts/views.py
@@ -153,7 +153,7 @@ def success(request):
     """View handler for the final success page."""
     page = viewmodels.Page(
         title=_("discounts.success.title"),
-        icon=viewmodels.Icon("paymentcardcheck", pgettext("image alt text", "core.icons.bankcardcheck")),
+        icon=viewmodels.Icon("bankcardcheck", pgettext("image alt text", "core.icons.bankcardcheck")),
         content_title=_("discounts.success.title"),
         paragraphs=[_("discounts.success.p1"), _("discounts.success.p2")],
     )


Test patch:
Repository: cal-itp/benefits

Issue:
Ensure cookies are enabled
Need a basic client-side check that cookies are enabled (and UI if not) as soon as the app loads, since we require cookies to store the temporary transaction data.


Discussion:

Resolving patch:
diff --git a/benefits/settings.py b/benefits/settings.py
--- a/benefits/settings.py
+++ b/benefits/settings.py
@@ -69,6 +69,7 @@
 
 if not DEBUG:
     CSRF_COOKIE_SECURE = True
+    CSRF_FAILURE_VIEW = "benefits.core.views.bad_request"
     SESSION_COOKIE_SECURE = True
 
 ROOT_URLCONF = "benefits.urls"
diff --git a/benefits/urls.py b/benefits/urls.py
--- a/benefits/urls.py
+++ b/benefits/urls.py
@@ -20,8 +20,8 @@
 
 urlpatterns = [
     path("", include("benefits.core.urls")),
-    path("enrollment/", include("benefits.enrollment.urls")),
     path("eligibility/", include("benefits.eligibility.urls")),
+    path("enrollment/", include("benefits.enrollment.urls")),
     path("i18n/", include("django.conf.urls.i18n")),
 ]
 


Test patch:
Repository: cal-itp/benefits

Issue:
Enrollment page is accessible without passing eligibility verification
If a user knows the `/enrollment` endpoint, and has configured their session with a Transit Agency, they can navigate to the credit card enrollment page and completely bypass the EV check. This is a serious bug! 

## Steps to reproduce

1. Visit https://test-benefits.calitp.org
2. Click either of the Agency buttons
3. Manually update the URL to https://test-benefits.calitp.org/enrollment
4. Profit

## Remediation

This page must ensure the user has previously verified eligibility criteria


Discussion:

Resolving patch:
diff --git a/benefits/core/middleware.py b/benefits/core/middleware.py
--- a/benefits/core/middleware.py
+++ b/benefits/core/middleware.py
@@ -26,6 +26,17 @@ def process_request(self, request):
             raise AttributeError("Session not configured with agency")
 
 
+class EligibleSessionRequired(MiddlewareMixin):
+    """Middleware raises an exception for sessions lacking confirmed eligibility."""
+
+    def process_request(self, request):
+        if session.eligible(request):
+            logger.debug("Session has confirmed eligibility")
+            return None
+        else:
+            raise AttributeError("Session has no confirmed eligibility")
+
+
 class DebugSession(MiddlewareMixin):
     """Middleware to configure debug context in the request session."""
 
diff --git a/benefits/enrollment/views.py b/benefits/enrollment/views.py
--- a/benefits/enrollment/views.py
+++ b/benefits/enrollment/views.py
@@ -78,17 +78,6 @@ def _index(request):
     return TemplateResponse(request, "enrollment/index.html", context)
 
 
-@decorator_from_middleware(middleware.AgencySessionRequired)
-def index(request):
-    """View handler for the enrollment landing page."""
-    if request.method == "POST":
-        response = _enroll(request)
-    else:
-        response = _index(request)
-
-    return response
-
-
 def _enroll(request):
     """Helper calls the enrollment APIs."""
     logger.debug("Read tokenized card")
@@ -113,7 +102,18 @@ def _enroll(request):
         raise Exception("Updated customer_id does not match enrolled customer_id")
 
 
-@decorator_from_middleware(middleware.AgencySessionRequired)
+@decorator_from_middleware(middleware.EligibleSessionRequired)
+def index(request):
+    """View handler for the enrollment landing page."""
+    if request.method == "POST":
+        response = _enroll(request)
+    else:
+        response = _index(request)
+
+    return response
+
+
+@decorator_from_middleware(middleware.EligibleSessionRequired)
 def retry(request):
     """View handler for a recoverable failure condition."""
     if request.method == "POST":


Test patch:
Repository: cal-itp/benefits

Issue:
Secure Django's language cookie
The following can be configured in [`settings.py`](https://github.com/cal-itp/benefits/blob/dev/benefits/settings.py)

* [x] [`LANGUAGE_COOKIE_HTTPONLY`](https://docs.djangoproject.com/en/3.2/ref/settings/#language-cookie-httponly) = True (same as `SESSION_COOKIE_HTTPONLY`)
* [x] [`LANGUAGE_COOKIE_SAMESITE`](https://docs.djangoproject.com/en/3.2/ref/settings/#language-cookie-samesite) = "Strict" (same as `SESSION_COOKIE_SAMESITE`)
* [x] [`LANGUAGE_COOKIE_SECURE`](https://docs.djangoproject.com/en/3.2/ref/settings/#language-cookie-secure) = True (same as `SESSION_COOKIE_SECURE`)



Discussion:

Resolving patch:
diff --git a/benefits/settings.py b/benefits/settings.py
--- a/benefits/settings.py
+++ b/benefits/settings.py
@@ -142,6 +142,10 @@
 
 LANGUAGE_CODE = "en"
 
+LANGUAGE_COOKIE_HTTPONLY = True
+LANGUAGE_COOKIE_SAMESITE = "Strict"
+LANGUAGE_COOKIE_SECURE = True
+
 LANGUAGES = [("en", "English"), ("es", "Español")]
 
 LOCALE_PATHS = [os.path.join(BASE_DIR, "benefits", "locale")]


Test patch:
Repository: cal-itp/benefits

Issue:
Secure critical Django cookies
The following can be configured in [`settings.py`](https://github.com/cal-itp/benefits/blob/dev/benefits/settings.py).

Setting these ensures the cookies expire and are deleted when the user's browser closes (makes them session cookies)

* [x] [`CSRF_COOKIE_AGE`](https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-age) = None
* [x] ~[`SESSION_COOKIE_AGE`](https://docs.djangoproject.com/en/3.2/ref/settings/#session-cookie-age) = None~
* [x] [`SESSION_EXPIRE_AT_BROWSER_CLOSE `](https://docs.djangoproject.com/en/3.2/ref/settings/#session-cookie-age) = True

We also want to prevent the CSRF cookie from being sent in cross-browser requests. E.g. a user clicks on a link to our site, from another site - in this case we don't want any previous CSRF cookie already in their browser sent. It's unlikely to be an issue in our app since there are no user logins etc. but for consistency with our other cookies (session and language).

* [x] [`CSRF_COOKIE_SAMESITE`](https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-samesite) = "Strict"


Discussion:
Setting `CSRF_COOKIE_AGE` to `None` accomplishes what we want. 👍 

Setting `SESSION_COOKIE_AGE` to `None` however results in a `TypeError`:
![image](https://user-images.githubusercontent.com/25497886/142540185-0e661587-28b5-497e-b514-1552aa2b67bd.png)

I tried out setting it to 0, but then we have no session data 🤦 
![image](https://user-images.githubusercontent.com/25497886/142539787-e2b69a9d-667b-4e37-80ac-d238ba86c7e8.png)

It appears that [`SESSION_EXPIRE_AT_BROWSER_CLOSE`](https://docs.djangoproject.com/en/3.2/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions) set to `True` is what we want.

I tried that out and verified that there is a new session cookie value when closing and re-opening my browser. 👍 

(It took me a while to realize that it was actually changing because for me, the `sessionid` cookie value is an array of length 3, where the first part doesn't seem to change much.)

![image](https://user-images.githubusercontent.com/25497886/142547794-0bced9e3-1b9d-425b-9158-f9f500635017.png)




Resolving patch:
diff --git a/benefits/settings.py b/benefits/settings.py
--- a/benefits/settings.py
+++ b/benefits/settings.py
@@ -62,11 +62,13 @@
         ]
     )
 
+CSRF_COOKIE_AGE = None
+CSRF_COOKIE_SAMESITE = "Strict"
 CSRF_COOKIE_HTTPONLY = True
 
-SESSION_COOKIE_AGE = 3600
 SESSION_COOKIE_SAMESITE = "Strict"
 SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
+SESSION_EXPIRE_AT_BROWSER_CLOSE = True
 
 if not DEBUG:
     CSRF_COOKIE_SECURE = True


Test patch: