nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: huge-success/sanic
Pull request #1909 (2020-08-13 06:41:43)

fix websocket ping variables issues
fixed the problem that the websocket ping_timeout and ping_interval parameter settings did not take effect


Patch:
diff --git a/sanic/server.py b/sanic/server.py
index 2e27d80b..07b755ed 100644
--- a/sanic/server.py
+++ b/sanic/server.py
@@ -14,7 +14,7 @@ from ipaddress import ip_address
 from signal import SIG_IGN, SIGINT, SIGTERM, Signals
 from signal import signal as signal_func
 from time import time
-from typing import Type
+from typing import Dict, Type, Union
 
 from httptools import HttpRequestParser  # type: ignore
 from httptools.parser.errors import HttpParserError  # type: ignore
@@ -955,15 +955,15 @@ def serve(
 
 def _build_protocol_kwargs(
     protocol: Type[HttpProtocol], config: Config
-) -> dict:
-    if hasattr(protocol, "websocket_timeout"):
+) -> Dict[str, Union[int, float]]:
+    if hasattr(protocol, "websocket_handshake"):
         return {
-            "max_size": config.WEBSOCKET_MAX_SIZE,
-            "max_queue": config.WEBSOCKET_MAX_QUEUE,
-            "read_limit": config.WEBSOCKET_READ_LIMIT,
-            "write_limit": config.WEBSOCKET_WRITE_LIMIT,
-            "ping_timeout": config.WEBSOCKET_PING_TIMEOUT,
-            "ping_interval": config.WEBSOCKET_PING_INTERVAL,
+            "websocket_max_size": config.WEBSOCKET_MAX_SIZE,
+            "websocket_max_queue": config.WEBSOCKET_MAX_QUEUE,
+            "websocket_read_limit": config.WEBSOCKET_READ_LIMIT,
+            "websocket_write_limit": config.WEBSOCKET_WRITE_LIMIT,
+            "websocket_ping_timeout": config.WEBSOCKET_PING_TIMEOUT,
+            "websocket_ping_interval": config.WEBSOCKET_PING_INTERVAL,
         }
     return {}
 


Test patch:
diff --git a/tests/test_app.py b/tests/test_app.py
index 5a7afa59..dab46061 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -170,12 +170,20 @@ def test_app_websocket_parameters(websocket_protocol_mock, app):
 
     websocket_protocol_call_args = websocket_protocol_mock.call_args
     ws_kwargs = websocket_protocol_call_args[1]
-    assert ws_kwargs["max_size"] == app.config.WEBSOCKET_MAX_SIZE
-    assert ws_kwargs["max_queue"] == app.config.WEBSOCKET_MAX_QUEUE
-    assert ws_kwargs["read_limit"] == app.config.WEBSOCKET_READ_LIMIT
-    assert ws_kwargs["write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT
-    assert ws_kwargs["ping_timeout"] == app.config.WEBSOCKET_PING_TIMEOUT
-    assert ws_kwargs["ping_interval"] == app.config.WEBSOCKET_PING_INTERVAL
+    assert ws_kwargs["websocket_max_size"] == app.config.WEBSOCKET_MAX_SIZE
+    assert ws_kwargs["websocket_max_queue"] == app.config.WEBSOCKET_MAX_QUEUE
+    assert ws_kwargs["websocket_read_limit"] == app.config.WEBSOCKET_READ_LIMIT
+    assert (
+        ws_kwargs["websocket_write_limit"] == app.config.WEBSOCKET_WRITE_LIMIT
+    )
+    assert (
+        ws_kwargs["websocket_ping_timeout"]
+        == app.config.WEBSOCKET_PING_TIMEOUT
+    )
+    assert (
+        ws_kwargs["websocket_ping_interval"]
+        == app.config.WEBSOCKET_PING_INTERVAL
+    )
 
 
 def test_handle_request_with_nested_exception(app, monkeypatch):
Repository: huge-success/sanic
Pull request #1334 (2018-09-29 10:26:17)

Fix TypeError when use Blueprint.group() to group blueprint with defa…
…ult url_prefix, Use os.path.normpath to avoid invalid url_prefix like api//v1


Patch:
diff --git a/sanic/blueprints.py b/sanic/blueprints.py
index 084013e1..087bb781 100644
--- a/sanic/blueprints.py
+++ b/sanic/blueprints.py
@@ -54,6 +54,8 @@ class Blueprint:
                     yield i
         bps = []
         for bp in chain(blueprints):
+            if bp.url_prefix is None:
+                bp.url_prefix = ''
             bp.url_prefix = url_prefix + bp.url_prefix
             bps.append(bp)
         return bps


Test patch:
diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py
index 4b821e91..7e25264d 100644
--- a/tests/test_blueprints.py
+++ b/tests/test_blueprints.py
@@ -499,3 +499,40 @@ def test_bp_group(app):
 
     request, response = app.test_client.get('/mid/deep1/bottom')
     assert response.text == 'D1B_OK'
+
+
+def test_bp_group_with_default_url_prefix(app):
+
+    from sanic.response import json
+    bp_resources = Blueprint('bp_resources')
+    @bp_resources.get('/')
+    def list_resources_handler(request):
+        resource = {}
+        return json([resource])
+
+    bp_resource = Blueprint('bp_resource', url_prefix='/<resource_id>')
+    @bp_resource.get('/')
+    def get_resource_hander(request, resource_id):
+        resource = {'resource_id': resource_id}
+        return json(resource)
+
+    bp_resources_group = Blueprint.group(bp_resources, bp_resource, url_prefix='/resources')
+    bp_api_v1 = Blueprint('bp_api_v1')
+    @bp_api_v1.get('/info')
+    def api_v1_info(request):
+        return text('api_version: v1')
+
+    bp_api_v1_group = Blueprint.group(bp_api_v1, bp_resources_group, url_prefix='/v1')
+    bp_api_group = Blueprint.group(bp_api_v1_group, url_prefix='/api')
+    app.blueprint(bp_api_group)
+
+    request, response = app.test_client.get('/api/v1/info')
+    assert response.text == 'api_version: v1'
+
+    request, response = app.test_client.get('/api/v1/resources')
+    assert response.json == [{}]
+
+    from uuid import uuid4
+    resource_id = str(uuid4())
+    request, response = app.test_client.get('/api/v1/resources/{0}'.format(resource_id))
+    assert response.json == {'resource_id': resource_id}
Repository: huge-success/sanic
Pull request #1342 (2018-10-03 12:28:41)

Handle syntax error in load config file.

hramezani: @vltr thanks, I added `happened in config file` to error. maybe it helps the user to find the location of the error.
If you feel it doesn't help I can undo the changes in `sanic/config.py` and just keep the tests. if not we can close the PR :)
abuckenheimer: I still like the spirit of this I just think we should use error chaining instead of manipulating the arguments, if we created a custom exception we could do something like this
```
class PyFileError(Exception):
    def __init__(self, file):
        super().__init__('could not execute config file %s', file)

... # back in from_pyfile
except Exception as e:
    raise PyFileError(filename) from e
```
vltr: @abuckenheimer that would be awesome.
@hramezani sorry for stepping on your toes on this :grimacing:

Patch:
diff --git a/sanic/config.py b/sanic/config.py
index c5e42de5..3e968117 100644
--- a/sanic/config.py
+++ b/sanic/config.py
@@ -1,6 +1,8 @@
 import os
 import types
 
+from sanic.exceptions import PyFileError
+
 
 SANIC_PREFIX = 'SANIC_'
 
@@ -83,6 +85,9 @@ class Config(dict):
         except IOError as e:
             e.strerror = 'Unable to load configuration file (%s)' % e.strerror
             raise
+        except Exception as e:
+            raise PyFileError(filename) from e
+
         self.from_object(module)
         return True
 
diff --git a/sanic/exceptions.py b/sanic/exceptions.py
index 25dbd47d..0b834e75 100644
--- a/sanic/exceptions.py
+++ b/sanic/exceptions.py
@@ -223,6 +223,11 @@ class InvalidRangeType(ContentRangeError):
     pass
 
 
+class PyFileError(Exception):
+    def __init__(self, file):
+        super().__init__('could not execute config file %s', file)
+
+
 @add_status_code(401)
 class Unauthorized(SanicException):
     """


Test patch:
diff --git a/tests/test_config.py b/tests/test_config.py
index 08461b81..f8322036 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -3,6 +3,7 @@ import pytest
 from tempfile import NamedTemporaryFile
 
 from sanic import Sanic
+from sanic.exceptions import PyFileError
 
 
 def test_load_from_object(app):
@@ -79,6 +80,16 @@ def test_load_from_missing_envvar(app):
                                 "could not be loaded.")
 
 
+def test_load_config_from_file_invalid_syntax(app):
+    config = b"VALUE = some value"
+    with NamedTemporaryFile() as config_file:
+        config_file.write(config)
+        config_file.seek(0)
+
+        with pytest.raises(PyFileError):
+            app.config.from_pyfile(config_file.name)
+
+
 def test_overwrite_exisiting_config(app):
     app.config.DEFAULT = 1
Repository: huge-success/sanic
Pull request #1364 (2018-10-13 06:09:48)

Raise exception when param conflicts
address https://github.com/huge-success/sanic/issues/1359


Patch:
diff --git a/sanic/router.py b/sanic/router.py
index 2864bf84..8ddba1a3 100644
--- a/sanic/router.py
+++ b/sanic/router.py
@@ -38,6 +38,10 @@ class RouteDoesNotExist(Exception):
     pass
 
 
+class ParameterNameConflicts(Exception):
+    pass
+
+
 class Router:
     """Router supports basic routing with parameters and method checks
 
@@ -195,12 +199,19 @@ class Router:
             methods = frozenset(methods)
 
         parameters = []
+        parameter_names = set()
         properties = {"unhashable": None}
 
         def add_parameter(match):
             name = match.group(1)
             name, _type, pattern = self.parse_parameter_string(name)
 
+            if name in parameter_names:
+                raise ParameterNameConflicts(
+                        "Multiple parameter named <{name}> "
+                        "in route uri {uri}".format(name=name, uri=uri))
+            parameter_names.add(name)
+
             parameter = Parameter(
                 name=name, cast=_type)
             parameters.append(parameter)
diff --git a/setup.py b/setup.py
index 027918bc..5e5eb2de 100644
--- a/setup.py
+++ b/setup.py
@@ -48,6 +48,7 @@ setup_kwargs = {
         'License :: OSI Approved :: MIT License',
         'Programming Language :: Python :: 3.5',
         'Programming Language :: Python :: 3.6',
+        'Programming Language :: Python :: 3.7',
     ],
 }
 


Test patch:
diff --git a/tests/test_routes.py b/tests/test_routes.py
index d5f1c90a..ac0b4bf6 100644
--- a/tests/test_routes.py
+++ b/tests/test_routes.py
@@ -3,7 +3,7 @@ import pytest
 
 from sanic import Sanic
 from sanic.response import text, json
-from sanic.router import RouteExists, RouteDoesNotExist
+from sanic.router import RouteExists, RouteDoesNotExist, ParameterNameConflicts
 from sanic.constants import HTTP_METHODS
 
 
@@ -935,3 +935,10 @@ def test_uri_with_different_method_and_different_params(app):
     assert response.json == {
         'action': 'post'
     }
+
+
+def test_route_raise_ParameterNameConflicts(app):
+    with pytest.raises(ParameterNameConflicts):
+        @app.get('/api/v1/<user>/<user>/')
+        def handler(request, user):
+            return text('OK')
Repository: huge-success/sanic
Pull request #1415 (2018-11-17 12:15:57)

Fix `remove_entity_headers` helper function
Based on the comment on `remove_entity_headers` helper function:

>  Removes all the entity headers present in the headers given.
    According to RFC 2616 Section 10.3.5,
    Content-Location and Expires are allowed as for the
    "strong cache validator".

`Content-Location` and `Expires` should be allowed.


Patch:
diff --git a/sanic/helpers.py b/sanic/helpers.py
index d992f92e..3312f0c7 100644
--- a/sanic/helpers.py
+++ b/sanic/helpers.py
@@ -128,6 +128,6 @@ def remove_entity_headers(headers, allowed=("content-location", "expires")):
     headers = {
         header: value
         for header, value in headers.items()
-        if not is_entity_header(header) and header.lower() not in allowed
+        if not is_entity_header(header) or header.lower() in allowed
     }
     return headers


Test patch:
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index eb08624e..b5f6dd16 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -34,3 +34,41 @@ def test_is_hop_by_hop_header():
     )
     for header, expected in tests:
         assert helpers.is_hop_by_hop_header(header) is expected
+
+
+def test_remove_entity_headers():
+    tests = (
+        (
+            {},
+            {}
+        ),
+        (
+            {
+                "Allow": "GET, POST, HEAD",
+            },
+            {}
+        ),
+        (
+            {
+                "Content-Type": "application/json",
+                "Expires": "Wed, 21 Oct 2015 07:28:00 GMT",
+                "Foo": "Bar"
+            },
+            {
+                "Expires": "Wed, 21 Oct 2015 07:28:00 GMT",
+                "Foo": "Bar"
+            },
+        ),
+        (
+            {
+                "Allow": "GET, POST, HEAD",
+                "Content-Location": "/test"
+            },
+            {
+                "Content-Location": "/test"
+            },
+        ),
+    )
+
+    for header, expected in tests:
+        assert helpers.remove_entity_headers(header) == expected
Repository: huge-success/sanic
Pull request #1541 (2019-03-27 13:53:09)

stop number route accepting excess '.'s
This stops this error

    ValueError: could not convert string to float: '12.34.56'

when passing 12.34.56 as a number route parameter argument.
By accepting ".12" and "12.", this is a non-breaking change. All valid
floats described by [0-9\.]+ are still accepted, just invalid ones are
now rejected.


Patch:
diff --git a/sanic/router.py b/sanic/router.py
index dcf3aeb5..4c1ea0a0 100644
--- a/sanic/router.py
+++ b/sanic/router.py
@@ -18,7 +18,7 @@ Parameter = namedtuple("Parameter", ["name", "cast"])
 REGEX_TYPES = {
     "string": (str, r"[^/]+"),
     "int": (int, r"-?\d+"),
-    "number": (float, r"-?[0-9\\.]+"),
+    "number": (float, r"-?(?:\d+(?:\.\d*)?|\.\d+)"),
     "alpha": (str, r"[A-Za-z]+"),
     "path": (str, r"[^/].*?"),
     "uuid": (


Test patch:
diff --git a/tests/test_routes.py b/tests/test_routes.py
index f3152935..3ccef135 100644
--- a/tests/test_routes.py
+++ b/tests/test_routes.py
@@ -365,9 +365,18 @@ def test_dynamic_route_number(app):
     request, response = app.test_client.get("/weight/1234.56")
     assert response.status == 200
 
+    request, response = app.test_client.get("/weight/.12")
+    assert response.status == 200
+
+    request, response = app.test_client.get("/weight/12.")
+    assert response.status == 200
+
     request, response = app.test_client.get("/weight/1234-56")
     assert response.status == 404
 
+    request, response = app.test_client.get("/weight/12.34.56")
+    assert response.status == 404
+
 
 def test_dynamic_route_regex(app):
     @app.route("/folder/<folder_id:[A-Za-z0-9]{0,4}>")
@@ -672,9 +681,18 @@ def test_dynamic_add_route_number(app):
     request, response = app.test_client.get("/weight/1234.56")
     assert response.status == 200
 
+    request, response = app.test_client.get("/weight/.12")
+    assert response.status == 200
+
+    request, response = app.test_client.get("/weight/12.")
+    assert response.status == 200
+
     request, response = app.test_client.get("/weight/1234-56")
     assert response.status == 404
 
+    request, response = app.test_client.get("/weight/12.34.56")
+    assert response.status == 404
+
 
 def test_dynamic_add_route_regex(app):
     async def handler(request, folder_id):
diff --git a/tests/test_url_building.py b/tests/test_url_building.py
index 5e1c300a..a246aabc 100644
--- a/tests/test_url_building.py
+++ b/tests/test_url_building.py
@@ -223,7 +223,7 @@ def test_fails_with_number_message(app):
 
     expected_error = (
         'Value "foo" for parameter `some_number` '
-        "does not match pattern for type `float`: -?[0-9\\\\.]+"
+        r"does not match pattern for type `float`: -?(?:\d+(?:\.\d*)?|\.\d+)"
     )
 
     assert str(e.value) == expected_error
Repository: pyg-team/pytorch_geometric
Pull request #8453 (2023-11-27 15:06:56)

Test `EdgeIndex` in `DataLoader` routines


Patch:
diff --git a/torch_geometric/data/edge_index.py b/torch_geometric/data/edge_index.py
index 0df14e3bd..3f6ed2958 100644
--- a/torch_geometric/data/edge_index.py
+++ b/torch_geometric/data/edge_index.py
@@ -311,6 +311,11 @@ def cuda(tensor: EdgeIndex, *args, **kwargs) -> EdgeIndex:
     return apply_(tensor, Tensor.cuda, *args, **kwargs)
 
 
+@implements(Tensor.share_memory_)
+def share_memory_(tensor: EdgeIndex) -> EdgeIndex:
+    return apply_(tensor, Tensor.share_memory_)
+
+
 @implements(torch.cat)
 def cat(
     tensors: List[Union[EdgeIndex, Tensor]],


Test patch:
diff --git a/test/data/test_edge_index.py b/test/data/test_edge_index.py
index e96ec97d5..0ccc81d41 100644
--- a/test/data/test_edge_index.py
+++ b/test/data/test_edge_index.py
@@ -1,5 +1,6 @@
 import os.path as osp
 
+import pytest
 import torch
 
 from torch_geometric.data.edge_index import EdgeIndex
@@ -180,3 +181,36 @@ def test_save_and_load(tmp_path):
     assert torch.equal(out, torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]]))
     assert out.sort_order == 'row'
     assert torch.equal(out._rowptr, torch.tensor([0, 1, 3, 4]))
+
+
+def test_share_memory():
+    adj = EdgeIndex([[0, 1, 1, 2], [1, 0, 2, 1]], sort_order='row')
+    adj.fill_cache()
+
+    adj = adj.share_memory_()
+    assert isinstance(adj, EdgeIndex)
+    assert adj.is_shared()
+    assert adj._rowptr.is_shared()
+
+
+@pytest.mark.parametrize('num_workers', [0, 2])
+def test_data_loader(num_workers):
+    adj = EdgeIndex([[0, 1, 1, 2], [1, 0, 2, 1]], sort_order='row')
+    adj.fill_cache()
+
+    loader = torch.utils.data.DataLoader(
+        [adj] * 4,
+        batch_size=2,
+        num_workers=num_workers,
+        collate_fn=lambda x: x,
+        drop_last=True,
+    )
+
+    assert len(loader) == 2
+    for batch in loader:
+        assert isinstance(batch, list)
+        assert len(batch) == 2
+        for adj in batch:
+            assert isinstance(adj, EdgeIndex)
+            assert adj.is_shared() == (num_workers > 0)
+            assert adj._rowptr.is_shared() == (num_workers > 0)
Repository: SpikeInterface/spikeinterface
Pull request #3990 (2025-06-17 10:25:41)

Propagate `relative_to` to `dump_to_pickle`
We don't propagate `relative_to` to `dump_to_pickle` in the `dump` method. This PR does.

The lack of propagation has a few consequences, including the fact that `recording.save_to_folder` and `analyzer.save(folder='...')` saves different recording info if `pickle`d (but not if `json`d).

Pretty sure it's a bug, but maybe there's a reason for this? 

Added a test to check that `pickle`ing and `json`ing are (almost) the same for a saved-then-loaded recording.


Patch:
diff --git a/src/spikeinterface/core/base.py b/src/spikeinterface/core/base.py
index f0f4e7604..495d92a38 100644
--- a/src/spikeinterface/core/base.py
+++ b/src/spikeinterface/core/base.py
@@ -699,7 +699,7 @@ class BaseExtractor:
         if str(file_path).endswith(".json"):
             self.dump_to_json(file_path, relative_to=relative_to, folder_metadata=folder_metadata)
         elif str(file_path).endswith(".pkl") or str(file_path).endswith(".pickle"):
-            self.dump_to_pickle(file_path, folder_metadata=folder_metadata)
+            self.dump_to_pickle(file_path, relative_to=relative_to, folder_metadata=folder_metadata)
         else:
             raise ValueError("Dump: file must .json or .pkl")
 


Test patch:
diff --git a/src/spikeinterface/core/tests/test_baserecording.py b/src/spikeinterface/core/tests/test_baserecording.py
index 15b1fcf36..08f314a0e 100644
--- a/src/spikeinterface/core/tests/test_baserecording.py
+++ b/src/spikeinterface/core/tests/test_baserecording.py
@@ -346,6 +346,38 @@ def test_BaseRecording(create_cache_folder):
         assert rec2.get_annotation(annotation_name) == rec_zarr2_loaded.get_annotation(annotation_name)
 
 
+def test_json_pickle_equivalence(create_cache_folder):
+    """
+    For a json-ifyable recording, the json and pickle outputs created by `dump` should be the same
+    (except for the probe information). We check this here for a saved-then-loaded recording,
+    which tests if relative paths are dealt with in the same way.
+    """
+
+    rec = generate_recording(durations=[1])
+    cache_folder = create_cache_folder
+
+    json_file_path = cache_folder / "recording.json"
+    pkl_file_path = cache_folder / "recording.pkl"
+
+    rec.dump(json_file_path, relative_to=cache_folder)
+    rec.dump(pkl_file_path, relative_to=cache_folder)
+
+    with open(json_file_path, "r") as f:
+        data_json = json.load(f)
+
+    with open(pkl_file_path, "rb") as f:
+        data_pickle = pickle.load(f)
+
+    for key, value in data_json.items():
+        # skip probe info, since pickle keeps some additional information
+        if key not in ["properties"]:
+            if isinstance(value, dict):
+                for sub_key, sub_value in value.items():
+                    assert np.all(sub_value == data_pickle[key][sub_key])
+            else:
+                assert np.all(value == data_pickle[key])
+
+
 def test_interleaved_probegroups():
     recording = generate_recording(durations=[1.0], num_channels=16)