czlll/Loc-Bench_V0.1 huggingface dataset:
Repository: dask/dask
Issue category: Feature Request

Deprecate Series.view
Same as the others, that's deprecated in pandas for 3.0 so we can move ahead with it already




Functions to edit:
dask/dataframe/core.py:Series.view
dask/dataframe/core.py:Series
dask/dataframe/core.py:_convert_to_numeric
Functions added: dask/dataframe/core.py:Series._view
dask/dataframe/core.py:Series

Patch:
diff --git a/dask/dataframe/core.py b/dask/dataframe/core.py
index e1e7904a4d5..9ac54c8ae8e 100644
--- a/dask/dataframe/core.py
+++ b/dask/dataframe/core.py
@@ -4652,8 +4652,17 @@ def is_monotonic_decreasing(self):
             token="monotonic_decreasing",
         )
 
+    @_deprecated(
+        message=(
+            "Will be removed in a future version. "
+            "Use `Series.astype()` as an alternative to change the dtype."
+        )
+    )
     @derived_from(pd.Series)
     def view(self, dtype):
+        return self._view(dtype)
+
+    def _view(self, dtype):
         meta = self._meta.view(dtype)
         return self.map_partitions(M.view, dtype, meta=meta)
 
@@ -8721,11 +8730,19 @@ def series_map(base_series, map_series):
 
 
 def _convert_to_numeric(series, skipna):
-    if skipna:
-        return series.dropna().view("i8")
+    if PANDAS_GE_200:
+        if skipna:
+            return series.dropna().astype("i8")
+
+        # series.view("i8") with pd.NaT produces -9223372036854775808 is why we need to do this
+        return series.astype("i8").mask(series.isnull(), np.nan)
+    else:
+        view = "_view" if isinstance(series, Series) else "view"
+        if skipna:
+            return getattr(series.dropna(), view)("i8")
 
-    # series.view("i8") with pd.NaT produces -9223372036854775808 is why we need to do this
-    return series.view("i8").mask(series.isnull(), np.nan)
+        # series.view("i8") with pd.NaT produces -9223372036854775808 is why we need to do this
+        return getattr(series, view)("i8").mask(series.isnull(), np.nan)
 
 
 def _sqrt_and_convert_to_timedelta(partition, axis, dtype=None, *args, **kwargs):

Test patch: diff --git a/dask/dataframe/tests/test_dataframe.py b/dask/dataframe/tests/test_dataframe.py
index 3c22cc60307..c50a0e28d1c 100644
--- a/dask/dataframe/tests/test_dataframe.py
+++ b/dask/dataframe/tests/test_dataframe.py
@@ -5669,8 +5669,11 @@ def test_view():
 
     df = pd.DataFrame(data)
     ddf = dd.from_pandas(df, npartitions=2)
-    assert_eq(ddf["x"].view("uint8"), df["x"].view("uint8"))
-    assert_eq(ddf["y"].view("int64"), df["y"].view("int64"))
+
+    msg = "Will be removed in a future version. Use "
+    with pytest.raises(FutureWarning, match=msg):
+        assert_eq(ddf["x"].view("uint8"), df["x"].view("uint8"))
+        assert_eq(ddf["y"].view("int64"), df["y"].view("int64"))
 
 
 def test_simple_map_partitions():
Repository: spotify/luigi
Issue category: Security Vulnerability

Overly permissive file permissions in `luigi/lock.py`
Hi,

I am reporting a potential security with overly permissive file permissions in

https://github.com/spotify/luigi/blob/master/luigi/lock.py#L103

When creating a file, POSIX systems allow permissions to be specified for the owner, group, and others separately. Permissions should be kept as strict as possible, preventing other users from accessing the file's contents. Additionally, they can be used to write and execute malicious code for privileged escalation.

## References
- Wikipedia: [File system permissions](https://en.wikipedia.org/wiki/File_system_permissions)
- Common Weakness Enumeration: [CWE-732](https://cwe.mitre.org/data/definitions/732.html)


Functions to edit:
luigi/lock.py:acquire_for

Patch:
diff --git a/luigi/lock.py b/luigi/lock.py
index dfa5acbcdb..5a9e1f8014 100644
--- a/luigi/lock.py
+++ b/luigi/lock.py
@@ -100,7 +100,7 @@ def acquire_for(pid_dir, num_available=1, kill_signal=None):
     # Create a pid file if it does not exist
     try:
         os.mkdir(pid_dir)
-        os.chmod(pid_dir, 0o777)
+        os.chmod(pid_dir, 0o700)
     except OSError as exc:
         if exc.errno != errno.EEXIST:
             raise

Test patch: diff --git a/test/lock_test.py b/test/lock_test.py
index 2701bd963f..b04726066e 100644
--- a/test/lock_test.py
+++ b/test/lock_test.py
@@ -100,7 +100,7 @@ def test_acquiring_partially_taken_lock(self):
         self.assertTrue(acquired)
 
         s = os.stat(self.pid_file)
-        self.assertEqual(s.st_mode & 0o777, 0o777)
+        self.assertEqual(s.st_mode & 0o700, 0o700)
 
     def test_acquiring_lock_from_missing_process(self):
         fake_pid = 99999
@@ -111,7 +111,7 @@ def test_acquiring_lock_from_missing_process(self):
         self.assertTrue(acquired)
 
         s = os.stat(self.pid_file)
-        self.assertEqual(s.st_mode & 0o777, 0o777)
+        self.assertEqual(s.st_mode & 0o700, 0o700)
 
     @mock.patch('os.kill')
     def test_take_lock_with_kill(self, kill_fn):
Repository: keras-team/keras
Issue category: Bug Report

Normalization layer fails to broadcast scalar mean and variance
Normalization layer errors out for scalar mean and variance arguments. The documentation states that these arguments will be broadcast to the necessary size and the examples include scalars, but instead the source code seems to only reshape them (see [here](https://github.com/keras-team/keras/blob/v3.7.0/keras/src/layers/preprocessing/normalization.py#L193)).

I'm using Python 3.12.1 and Keras 3.6.0.

```
>>> in1 = keras.Input(shape=(16, 16, 3))
>>> normLayer = keras.layers.Normalization(mean=0.1, variance=0.05)
>>> out1 = normLayer(in1)
I tensorflow/core/framework/local_rendezvous.cc:405] Local rendezvous is aborting with status: INVALID_ARGUMENT: Input to reshape is a tensor with 1 values, but the requested shape has 3
```


Functions to edit:
keras/src/layers/preprocessing/normalization.py:Normalization.build

Patch:
diff --git a/keras/src/layers/preprocessing/normalization.py b/keras/src/layers/preprocessing/normalization.py
index e39dae73d48..54ed025c988 100644
--- a/keras/src/layers/preprocessing/normalization.py
+++ b/keras/src/layers/preprocessing/normalization.py
@@ -190,8 +190,8 @@ def build(self, input_shape):
             # with proper broadcast shape for use during call.
             mean = ops.convert_to_tensor(self.input_mean)
             variance = ops.convert_to_tensor(self.input_variance)
-            mean = ops.reshape(mean, self._broadcast_shape)
-            variance = ops.reshape(variance, self._broadcast_shape)
+            mean = ops.broadcast_to(mean, self._broadcast_shape)
+            variance = ops.broadcast_to(variance, self._broadcast_shape)
             self.mean = ops.cast(mean, dtype=self.compute_dtype)
             self.variance = ops.cast(variance, dtype=self.compute_dtype)
             self.built = True

Test patch: diff --git a/keras/src/layers/preprocessing/normalization_test.py b/keras/src/layers/preprocessing/normalization_test.py
index 4278272a522..473f5daf6ad 100644
--- a/keras/src/layers/preprocessing/normalization_test.py
+++ b/keras/src/layers/preprocessing/normalization_test.py
@@ -164,3 +164,8 @@ def test_tf_data_compatibility(self):
         )
         for output in ds.map(layer).take(1):
             output.numpy()
+
+    def test_normalization_with_scalar_mean_var(self):
+        input_data = np.array([[1,2,3]], dtype='float32')
+        layer = layers.Normalization(mean=3., variance=2.)
+        layer(input_data)
Repository: keras-team/keras
Issue category: Bug Report

BUG in load_weights_from_hdf5_group_by_name
https://github.com/keras-team/keras/blob/5d36ee1f219bb650dd108c35b257c783cd034ffd/keras/src/legacy/saving/legacy_h5_format.py#L521-L525

model.trainable_weights + model.non_trainable_weights references all weights instead of top-level


Functions to edit:
keras/src/legacy/saving/legacy_h5_format.py:load_weights_from_hdf5_group_by_name

Patch:
diff --git a/keras/src/legacy/saving/legacy_h5_format.py b/keras/src/legacy/saving/legacy_h5_format.py
index 0e284f5a9db..cc5ef63d97a 100644
--- a/keras/src/legacy/saving/legacy_h5_format.py
+++ b/keras/src/legacy/saving/legacy_h5_format.py
@@ -519,7 +519,7 @@ def load_weights_from_hdf5_group_by_name(f, model, skip_mismatch=False):
             )
 
     if "top_level_model_weights" in f:
-        symbolic_weights = model.trainable_weights + model.non_trainable_weights
+        symbolic_weights = model._trainable_variables + model._non_trainable_variables
         weight_values = load_subset_weights_from_hdf5_group(
             f["top_level_model_weights"]
         )

Test patch: diff --git a/keras/src/legacy/saving/legacy_h5_format_test.py b/keras/src/legacy/saving/legacy_h5_format_test.py
index 6909e79a4ca..52d6ad11a9c 100644
--- a/keras/src/legacy/saving/legacy_h5_format_test.py
+++ b/keras/src/legacy/saving/legacy_h5_format_test.py
@@ -53,8 +53,21 @@ def __init__(self, **kwargs):
             self.dense_1 = keras.layers.Dense(3, activation="relu")
             self.dense_2 = keras.layers.Dense(1, activation="sigmoid")
 
+            # top_level_model_weights
+            self.bias = self.add_weight(
+                name="bias",
+                shape=[1],
+                trainable=True,
+                initializer=keras.initializers.Zeros(),
+            )
+
         def call(self, x):
-            return self.dense_2(self.dense_1(x))
+            x = self.dense_1(x)
+            x = self.dense_2(x)
+
+            # top_level_model_weights
+            x += ops.cast(self.bias, x.dtype)
+
 
     model = MyModel()
     model(np.random.random((2, 3)))
Repository: keras-team/keras
Issue category: Feature Request

Add a warning for mismatched inputs structure in `Functional`
There are several issues related to mismatched inputs structure:
- #20166
- #20136
- #20086
and more...

As a result, it would be beneficial to add a warning for users.
Ultimately, we might want to raise an error when a mismatch occurs. Otherwise, it could lead to subtle issues if the inputs have the same shape and dtype, as the computation could be incorrect even though the code runs.


Functions to edit:
keras/src/models/functional.py:Functional._maybe_warn_inputs_struct_mismatch

Patch:
diff --git a/keras/src/models/functional.py b/keras/src/models/functional.py
index 0acb84ed028..9c71308a651 100644
--- a/keras/src/models/functional.py
+++ b/keras/src/models/functional.py
@@ -214,8 +214,12 @@ def _assert_input_compatibility(self, *args):
 
     def _maybe_warn_inputs_struct_mismatch(self, inputs):
         try:
+            # We first normalize to tuples before performing the check to
+            # suppress warnings when encountering mismatched tuples and lists.
             tree.assert_same_structure(
-                inputs, self._inputs_struct, check_types=False
+                tree.lists_to_tuples(inputs),
+                tree.lists_to_tuples(self._inputs_struct),
+                check_types=False,
             )
         except:
             model_inputs_struct = tree.map_structure(

Test patch: diff --git a/keras/src/models/functional_test.py b/keras/src/models/functional_test.py
index ef792fd7f11..44858d33811 100644
--- a/keras/src/models/functional_test.py
+++ b/keras/src/models/functional_test.py
@@ -1,4 +1,5 @@
 import os
+import warnings
 
 import numpy as np
 import pytest
@@ -503,13 +504,19 @@ def test_warning_for_mismatched_inputs_structure(self):
         model = Model({"i1": i1, "i2": i2}, outputs)
 
         with pytest.warns() as record:
-            model([np.ones((2, 2)), np.zeros((2, 2))])
+            model.predict([np.ones((2, 2)), np.zeros((2, 2))], verbose=0)
         self.assertLen(record, 1)
         self.assertStartsWith(
             str(record[0].message),
             r"The structure of `inputs` doesn't match the expected structure:",
         )
 
+        # No warning for mismatched tuples and lists.
+        model = Model([i1, i2], outputs)
+        with warnings.catch_warnings(record=True) as warning_logs:
+            model.predict((np.ones((2, 2)), np.zeros((2, 2))), verbose=0)
+            self.assertLen(warning_logs, 0)
+
     def test_for_functional_in_sequential(self):
         # Test for a v3.4.1 regression.
         if backend.image_data_format() == "channels_first":
Repository: joke2k/faker
Issue category: Bug Report

road_address for ko_KR locale should be changed
* Faker version: 30.8.2
* OS: Windows 11 Pro (22H2) -- does not matter. 

The road_address provider in locale 'ko_KR' should also generate building-number (건물 번호). Which noted in the source code comments but actually are not generated in result. 

### Expected behavior
With a locale 'ko_KR', address() method should generate road addresses such as: "서울특별시 중구 세종대로 110", or "서울특별시 용산구 서빙고로 137" which provides 'building numbers' at the end of the address. 

### Actual behavior
With a current version of Faker, faker only generates fake addresses without building numbers such as" "대전광역시 강서구 석촌호수거리", "전라남도 용인시 수지구 개포65길". 



Functions to edit:
faker/providers/address/ko_KR/__init__.py:Provider
Functions added: faker/providers/address/ko_KR/__init__.py:Provider

Patch:
diff --git a/faker/providers/address/ko_KR/__init__.py b/faker/providers/address/ko_KR/__init__.py
index 33af0b862b..437a2c00de 100644
--- a/faker/providers/address/ko_KR/__init__.py
+++ b/faker/providers/address/ko_KR/__init__.py
@@ -454,8 +454,12 @@ class Provider(AddressProvider):
         "{{building_name}} {{building_dong}}동 ###호",
     )
     road_formats = (
-        "{{road_name}}{{road_suffix}}",
-        "{{road_name}}{{road_number}}{{road_suffix}}",
+        "{{road_name}}{{road_suffix}} ###",
+        "{{road_name}}{{road_suffix}} 지하###",
+        "{{road_name}}{{road_suffix}} ###-##",
+        "{{road_name}}{{road_number}}{{road_suffix}} ###",
+        "{{road_name}}{{road_number}}{{road_suffix}} 지하###",
+        "{{road_name}}{{road_number}}{{road_suffix}} ###-##",
     )
     road_address_formats = (
         "{{metropolitan_city}} {{borough}} {{road}}",

Test patch: diff --git a/tests/providers/test_address.py b/tests/providers/test_address.py
index 1c229cdc26..a510132470 100644
--- a/tests/providers/test_address.py
+++ b/tests/providers/test_address.py
@@ -1316,6 +1316,11 @@ def test_building_dong(self, faker, num_samples):
             building_dong = faker.building_dong()
             assert isinstance(building_dong, str)
 
+    def test_road_address(self, faker, num_samples):
+        for _ in range(num_samples):
+            road_address = faker.road_address()
+            assert isinstance(road_address, str)
+
 
 class TestNeNp:
     """Test ne_NP address provider methods"""
Repository: Qiskit/qiskit
Issue category: Feature Request

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.


Functions to edit:
qiskit/circuit/library/overlap.py:UnitaryOverlap.__init__

Patch:
diff --git a/qiskit/circuit/library/overlap.py b/qiskit/circuit/library/overlap.py
index 38f5fb9184e1..2db6a80eedcc 100644
--- a/qiskit/circuit/library/overlap.py
+++ b/qiskit/circuit/library/overlap.py
@@ -59,7 +59,12 @@ class UnitaryOverlap(QuantumCircuit):
     """
 
     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 @@ def __init__(
                 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 @@ def __init__(
         # 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)
 
 

Test patch: diff --git a/test/python/circuit/library/test_overlap.py b/test/python/circuit/library/test_overlap.py
index a603f28037b1..1a95e3ba9155 100644
--- a/test/python/circuit/library/test_overlap.py
+++ b/test/python/circuit/library/test_overlap.py
@@ -131,6 +131,21 @@ def test_mismatching_qubits(self):
         with self.assertRaises(CircuitError):
             _ = UnitaryOverlap(unitary1, unitary2)
 
+    def test_insert_barrier(self):
+        """Test inserting barrier between circuits"""
+        unitary1 = EfficientSU2(1, reps=1)
+        unitary2 = EfficientSU2(1, reps=1)
+        overlap = UnitaryOverlap(unitary1, unitary2, insert_barrier=True)
+        self.assertEqual(overlap.count_ops()["barrier"], 1)
+        self.assertEqual(
+            str(overlap.draw(fold=-1, output="text")).strip(),
+            """
+   ┌───────────────────────────────────────┐ ░ ┌──────────────────────────────────────────┐
+q: ┤ EfficientSU2(p1[0],p1[1],p1[2],p1[3]) ├─░─┤ EfficientSU2_dg(p2[0],p2[1],p2[2],p2[3]) ├
+   └───────────────────────────────────────┘ ░ └──────────────────────────────────────────┘
+""".strip(),
+        )
+
 
 if __name__ == "__main__":
     unittest.main()
Repository: python/mypy
Issue category: Bug Report

Positional subpattern of a built-in type subclass with __match_args__ causes type confusion
Given

```python
class PrintableKey(bytes):
    __match_args__ = ('ch', )

    @property
    def ch(self) -> str:
        return self.decode('UTF-8')
```

now

```python
match event:
    case PrintableKey(ch):
        reveal_type(ch)  # mypy thinks it's PrintableKey
```

versus

```python
match event:
    case PrintableKey(ch=ch):
        reveal_type(ch)  # mypy correctly deduces it's str
```

_Originally posted by @mgedmin in https://github.com/python/mypy/issues/13804#issuecomment-2466177933_


Functions to edit:
mypy/checkpattern.py:PatternChecker.should_self_match

Patch:
diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py
index 6b4fa35f9c49..a7121712a6db 100644
--- a/mypy/checkpattern.py
+++ b/mypy/checkpattern.py
@@ -693,7 +693,9 @@ def visit_class_pattern(self, o: ClassPattern) -> PatternType:
 
     def should_self_match(self, typ: Type) -> bool:
         typ = get_proper_type(typ)
-        if isinstance(typ, Instance) and typ.type.is_named_tuple:
+        if isinstance(typ, Instance) and typ.type.get("__match_args__") is not None:
+            # Named tuples and other subtypes of builtins that define __match_args__
+            # should not self match.
             return False
         for other in self.self_match_types:
             if is_subtype(typ, other):

Test patch: diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test
index 58b70d7b74d8..8187f27353a9 100644
--- a/test-data/unit/check-python310.test
+++ b/test-data/unit/check-python310.test
@@ -648,6 +648,25 @@ match m:
         reveal_type(m)  # N: Revealed type is "builtins.tuple[Any, ...]"
 [builtins fixtures/primitives.pyi]
 
+[case testMatchClassPatternCaptureSelfSubtype]
+class A(str):
+    pass
+
+class B(str):
+    __match_args__ = ("b",)
+    b: int
+
+def f1(x: A):
+    match x:
+        case A(a):
+            reveal_type(a)  # N: Revealed type is "__main__.A"
+
+def f2(x: B):
+    match x:
+        case B(b):
+            reveal_type(b)  # N: Revealed type is "builtins.int"
+[builtins fixtures/tuple.pyi]
+
 [case testMatchInvalidClassPattern]
 m: object
Repository: pandas-dev/pandas
Issue category: Feature Request

ENH: increase verbosity on error
### Feature Type

- [ ] Adding new functionality to pandas

- [X] Changing existing functionality in pandas

- [ ] Removing existing functionality in pandas


### Problem Description

On a specific type error the error causing type is not logged in the error

### Feature Description

By replacing:
`raise AttributeError("Can only use .str accessor with string values!")`
with
`raise AttributeError(f"Can only use .str accessor with string values! Inferred dType: {inferred_dtype}")`
the problem would be solved

Details can be found in [here](https://github.com/pandas-dev/pandas/pull/59649/files)

### Alternative Solutions

Use a debugger and set a break point

### Additional Context

_No response_


Functions to edit:
pandas/core/strings/accessor.py:StringMethods._validate

Patch:
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 3cb0e75cfb815..05e1a36877e06 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -255,7 +255,9 @@ def _validate(data):
         inferred_dtype = lib.infer_dtype(values, skipna=True)
 
         if inferred_dtype not in allowed_types:
-            raise AttributeError("Can only use .str accessor with string values!")
+            raise AttributeError(
+                f"Can only use .str accessor with string values, not {inferred_dtype}"
+            )
         return inferred_dtype
 
     def __getitem__(self, key):

Test patch: diff --git a/pandas/tests/series/accessors/test_str_accessor.py b/pandas/tests/series/accessors/test_str_accessor.py
index 09d965ef1f322..ff530459b78fb 100644
--- a/pandas/tests/series/accessors/test_str_accessor.py
+++ b/pandas/tests/series/accessors/test_str_accessor.py
@@ -15,7 +15,8 @@ def test_str_attribute(self):
 
         # str accessor only valid with string values
         ser = Series(range(5))
-        with pytest.raises(AttributeError, match="only use .str accessor"):
+        msg = "Can only use .str accessor with string values, not integer"
+        with pytest.raises(AttributeError, match=msg):
             ser.str.repeat(2)
 
     def test_str_accessor_updates_on_inplace(self):
Repository: django/django
Issue category: Bug Report

Urlize incorrectly handles punctuation in email addresses
Description
	 
Several punctuation characters (%, &, +, !, etc.) can—and sometimes do—appear in the local part of an email address (before the @). The urlize template filter doesn't correctly encode them, which can result in broken mailto links.
Example (Django 5.1.4):
from django.template.defaultfilters import urlize
urlize("it%dept@example.org")
# '<a href="mailto:it%dept@example.org">it%dept@example.org</a>'
# Expected:
# '<a href="mailto:it%25dept@example.org">it%dept@example.org</a>'
Clicking the resulting mailto link might work as expected, or do nothing, or could launch a mail composer with a missing or incorrect email address, depending on the specific address, browser and email app. Sequences that could also be percent-encoded characters (like "%de" in the example) are especially prone to unpredictable results.
The mailto URI spec ​RFC 6068 requires percent encoding most punctuation in this situation (section 2, item 1; also see section 5, Encoding).
Proposed fix: apply urllib.parse.quote() to local where the ​mailto link is constructed in django.utils.html.Urlizer. (Although not strictly necessary, it wouldn't hurt to also quote domain there.)


Functions to edit:
django/utils/html.py:Urlizer.handle_word

Patch:
diff --git a/django/utils/html.py b/django/utils/html.py
index bc336d88a66c..0d107a0da9fe 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -357,6 +357,8 @@ def handle_word(
                     domain = punycode(domain)
                 except UnicodeError:
                     return word
+                local = quote(local, safe="")
+                domain = quote(domain, safe="")
                 url = self.mailto_template.format(local=local, domain=domain)
                 nofollow_attr = ""
             # Make link.

Test patch: diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
index dc3768e6fae0..0beaf98bff2b 100644
--- a/tests/utils_tests/test_html.py
+++ b/tests/utils_tests/test_html.py
@@ -376,6 +376,19 @@ def test_urlize(self):
                 + "한.글." * 15
                 + "aaa</a>",
             ),
+            (
+                # RFC 6068 requires a mailto URI to percent-encode a number of
+                # characters that can appear in <addr-spec>.
+                "yes;this=is&a%valid!email@example.com",
+                '<a href="mailto:yes%3Bthis%3Dis%26a%25valid%21email@example.com"'
+                ">yes;this=is&a%valid!email@example.com</a>",
+            ),
+            (
+                # Urlizer shouldn't urlize the "?org" part of this. But since
+                # it does, RFC 6068 requires percent encoding the "?".
+                "test@example.com?org",
+                '<a href="mailto:test@example.com%3Forg">test@example.com?org</a>',
+            ),
         )
         for value, output in tests:
             with self.subTest(value=value):
Repository: django/django
Issue category: Bug Report

makemessages: is_valid_locale regex fails to validate locales with numeric region codes
Description
		
(last modified by Juan Pablo Mallarino)		
The is_valid_locale function in the makemessages management command uses a regular expression that doesn't account for locales with numeric region codes, such as es_419. The current regex only allows uppercase letters after the underscore. This excludes valid locale codes that use numbers in the region subtag.
This can cause issues when trying to generate message files for these locales. For example, running makemessages with es_419 will not generate the expected message files, potentially leading to missing translations.
Proposed Solution
Modify the regular expression in is_valid_locale to include numeric characters in the region subtag validation. The suggested change is:
From:
r"^[a-z]+_[A-Z].*$"
To:
r"^[a-z]+_[A-Z0-9].*$"
This change would allow the validation of locales while still maintaining the expected format for other locale codes. This simple modification would ensure broader compatibility and avoid unexpected behavior when working with valid locales containing numeric region codes.


Functions to edit:
django/core/management/commands/makemessages.py:is_valid_locale

Patch:
diff --git a/django/core/management/commands/makemessages.py b/django/core/management/commands/makemessages.py
index 076667d41a8c..23ad424c5c31 100644
--- a/django/core/management/commands/makemessages.py
+++ b/django/core/management/commands/makemessages.py
@@ -40,7 +40,7 @@ def check_programs(*programs):
 
 
 def is_valid_locale(locale):
-    return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z].*$", locale)
+    return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z0-9].*$", locale)
 
 
 @total_ordering

Test patch: diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 7aa600c4c1e2..e4a6260c336a 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -179,6 +179,15 @@ def test_valid_locale_with_country(self):
         self.assertIn("processing locale en_GB", out.getvalue())
         self.assertIs(Path("locale/en_GB/LC_MESSAGES/django.po").exists(), True)
 
+    def test_valid_locale_with_numeric_region_code(self):
+        out = StringIO()
+        management.call_command(
+            "makemessages", locale=["ar_002"], stdout=out, verbosity=1
+        )
+        self.assertNotIn("invalid locale ar_002", out.getvalue())
+        self.assertIn("processing locale ar_002", out.getvalue())
+        self.assertIs(Path("locale/ar_002/LC_MESSAGES/django.po").exists(), True)
+
     def test_valid_locale_tachelhit_latin_morocco(self):
         out = StringIO()
         management.call_command(
Repository: django/django
Issue category: Bug Report

"view on site" URL doesn't accept non-integer ContentType pks
Description
	 
Most admin URL paths use the path converter to allow any type of ID, however, the "view on site" uses the int converter for content_type_id.
This doesn't work on MongoDB which uses ObjectIdAutoField (bson.ObjectId) for all models since AutoField isn't supported.


Functions to edit:
django/contrib/admin/sites.py:AdminSite.get_urls

Patch:
diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
index dc67262afc50..3399bd87b85a 100644
--- a/django/contrib/admin/sites.py
+++ b/django/contrib/admin/sites.py
@@ -282,7 +282,7 @@ def wrapper(*args, **kwargs):
             path("autocomplete/", wrap(self.autocomplete_view), name="autocomplete"),
             path("jsi18n/", wrap(self.i18n_javascript, cacheable=True), name="jsi18n"),
             path(
-                "r/<int:content_type_id>/<path:object_id>/",
+                "r/<path:content_type_id>/<path:object_id>/",
                 wrap(contenttype_views.shortcut),
                 name="view_on_site",
             ),

Test patch: diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index c5d8b8f4f668..3f106f681418 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -8664,6 +8664,19 @@ def test_custom_admin_site(self):
             ),
         )
 
+    def test_view_on_site_url_non_integer_ids(self):
+        """The view_on_site URL accepts non-integer ids."""
+        self.assertEqual(
+            reverse(
+                "admin:view_on_site",
+                kwargs={
+                    "content_type_id": "37156b6a-8a82",
+                    "object_id": "37156b6a-8a83",
+                },
+            ),
+            "/test_admin/admin/r/37156b6a-8a82/37156b6a-8a83/",
+        )
+
 
 @override_settings(ROOT_URLCONF="admin_views.urls")
 class InlineAdminViewOnSiteTest(TestCase):
Repository: django/django
Issue category: Bug Report

System check for default database values with expressions prohibits non-expressions
Description
	 
Since its introduction in Django 5.0, ​the fields.E011 system check for database backends that have DatabaseFeatures.supports_expression_defaults = False ​requires literal defaults to be wrapped in Value.
There are a number of test models that have ​int, float and ​string db_defaults that will raise a system check error if DatabaseFeatures.supports_expression_defaults = False
since these models don't have required_db_features = {"supports_expression_defaults"}.
I'm working on MongoDB which doesn't support any database defaults, literal or expressions.


Functions to edit:
django/db/models/fields/__init__.py:Field._check_db_default

Patch:
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index d1f31f021135..f9cafdb4bb40 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -392,7 +392,10 @@ def _check_db_default(self, databases=None, **kwargs):
 
         if (
             self.db_default is NOT_PROVIDED
-            or isinstance(self.db_default, Value)
+            or (
+                isinstance(self.db_default, Value)
+                or not hasattr(self.db_default, "resolve_expression")
+            )
             or databases is None
         ):
             return []

Test patch: diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py
index e30d41113809..1fcf3f708d47 100644
--- a/tests/invalid_models_tests/test_ordinary_fields.py
+++ b/tests/invalid_models_tests/test_ordinary_fields.py
@@ -1207,6 +1207,23 @@ class Model(models.Model):
         expected_error = Error(msg=msg, obj=field, id="fields.E012")
         self.assertEqual(errors, [expected_error])
 
+    def test_literals_not_treated_as_expressions(self):
+        """
+        DatabaseFeatures.supports_expression_defaults = False shouldn't
+        prevent non-expression literals (integer, float, boolean, etc.) from
+        being used as database defaults.
+        """
+
+        class Model(models.Model):
+            field = models.FloatField(db_default=1.0)
+
+        field = Model._meta.get_field("field")
+        with unittest.mock.patch.object(
+            connection.features, "supports_expression_defaults", False
+        ):
+            errors = field.check(databases=self.databases)
+        self.assertEqual(errors, [])
+
 
 @isolate_apps("invalid_models_tests")
 class GeneratedFieldTests(TestCase):
Repository: django/django
Issue category: Feature Request

Improve non-first {% extends %} error message
Description
	 
Currently if you put {% extends %} after another tag, the error looks like:
TemplateSyntaxError: <ExtendsNode: extends 'base.html'> must be the first tag in the template.
ExtendsNode is a leaked internal detail. Showing its repr() is a bit confusing, especially for a beginner programmer.
The message would be clearer if it showed the actual text of the tag:
TemplateSyntaxError: {% extends 'base.html' %} must be the first tag in the template.


Functions to edit:
django/template/base.py:Parser.extend_nodelist

Patch:
diff --git a/django/template/base.py b/django/template/base.py
index ee2e145c041a..b974495c9c92 100644
--- a/django/template/base.py
+++ b/django/template/base.py
@@ -533,9 +533,13 @@ def skip_past(self, endtag):
     def extend_nodelist(self, nodelist, node, token):
         # Check that non-text nodes don't appear before an extends tag.
         if node.must_be_first and nodelist.contains_nontext:
+            if self.origin.template_name:
+                origin = repr(self.origin.template_name)
+            else:
+                origin = "the template"
             raise self.error(
                 token,
-                "%r must be the first tag in the template." % node,
+                "{%% %s %%} must be the first tag in %s." % (token.contents, origin),
             )
         if not isinstance(node, TextNode):
             nodelist.contains_nontext = True

Test patch: diff --git a/tests/template_tests/test_extends.py b/tests/template_tests/test_extends.py
index ce1838654bac..0d2a93468ce3 100644
--- a/tests/template_tests/test_extends.py
+++ b/tests/template_tests/test_extends.py
@@ -1,9 +1,9 @@
 import os
 
-from django.template import Context, Engine, TemplateDoesNotExist
+from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError
 from django.test import SimpleTestCase
 
-from .utils import ROOT
+from .utils import ROOT, setup
 
 RECURSIVE = os.path.join(ROOT, "recursive_templates")
 
@@ -181,3 +181,17 @@ def test_block_override_in_extended_included_template(self):
         )
         template = engine.get_template("base.html")
         self.assertEqual(template.render(Context({})), "12AB")
+
+    @setup(
+        {"index.html": "{% block content %}B{% endblock %}{% extends 'base.html' %}"}
+    )
+    def test_extends_not_first_tag_in_extended_template(self):
+        msg = "{% extends 'base.html' %} must be the first tag in 'index.html'."
+        with self.assertRaisesMessage(TemplateSyntaxError, msg):
+            self.engine.get_template("index.html")
+
+    def test_extends_not_first_tag_in_extended_template_from_string(self):
+        template_string = "{% block content %}B{% endblock %}{% extends 'base.html' %}"
+        msg = "{% extends 'base.html' %} must be the first tag in the template."
+        with self.assertRaisesMessage(TemplateSyntaxError, msg):
+            Engine().from_string(template_string)
Repository: django/django
Issue category: Feature Request

System check fields.E300 does not allow for related fields involving auto_created through models.
Description
	 
The model system checks will raise the fields.E300 error if you make an auto_created through model the target of a related field. Here is an example of models that will trigger this error:
class E300TestModelA(models.Model):
	pass
class E300TestModelB(models.Model):
	many_to_many_rel = models.ManyToManyField(E300TestModelA)
class E300TestModelC(models.Model):
	one_to_one_rel = models.OneToOneField("check_framework.E300TestModelB_many_to_many_rel", on_delete=models.CASCADE)
I realize this might be an unusual thing to do, however I have a use case that requires this and thought I would create this ticket in case others agree that this should be changed. I will create a pull request shortly.


Functions to edit:
django/db/models/fields/related.py:RelatedField._check_relation_model_exists

Patch:
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index 7d42d1ea38a1..8b6855fce2db 100644
--- a/django/db/models/fields/related.py
+++ b/django/db/models/fields/related.py
@@ -187,7 +187,9 @@ def _check_related_query_name_is_valid(self):
         return errors
 
     def _check_relation_model_exists(self):
-        rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
+        rel_is_missing = self.remote_field.model not in self.opts.apps.get_models(
+            include_auto_created=True
+        )
         rel_is_string = isinstance(self.remote_field.model, str)
         model_name = (
             self.remote_field.model

Test patch: diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py
index e539d4e6fbfc..9b69ae415138 100644
--- a/tests/invalid_models_tests/test_relative_fields.py
+++ b/tests/invalid_models_tests/test_relative_fields.py
@@ -89,6 +89,23 @@ class Model(models.Model):
         field = Model._meta.get_field("m2m")
         self.assertEqual(field.check(from_model=Model), [])
 
+    @isolate_apps("invalid_models_tests")
+    def test_auto_created_through_model(self):
+        class OtherModel(models.Model):
+            pass
+
+        class M2MModel(models.Model):
+            many_to_many_rel = models.ManyToManyField(OtherModel)
+
+        class O2OModel(models.Model):
+            one_to_one_rel = models.OneToOneField(
+                "invalid_models_tests.M2MModel_many_to_many_rel",
+                on_delete=models.CASCADE,
+            )
+
+        field = O2OModel._meta.get_field("one_to_one_rel")
+        self.assertEqual(field.check(from_model=O2OModel), [])
+
     def test_many_to_many_with_useless_options(self):
         class Model(models.Model):
             name = models.CharField(max_length=20)
Repository: django/django
Issue category: Performance Issue

Cache Options.verbose_name_raw
Description
		
(last modified by Adam Johnson)		
Another candidate for caching, like #35230, following the same system check profiling.
The Model._meta.verbose_name_raw property returns the stringified version of the verbose_name attribute whilst temporarily disabling translations. It is only used in django.contrib.auth for creating permission names.
I found this property was taking ~15% of the total runtime for system checks on a project with 118 models. calls. Turning it into a cached_property and adding a no-translation fast path saves nearly all this cost, with the below results.
Before: 520 calls taking 10ms
After: 105 calls taking ~0ms


Functions to edit:
django/db/models/options.py:Options.verbose_name_raw
django/db/models/options.py:Options
Functions added: django/db/models/options.py:Options

Patch:
diff --git a/django/db/models/options.py b/django/db/models/options.py
index 9b3106f67ef6..e63a81c2d8e7 100644
--- a/django/db/models/options.py
+++ b/django/db/models/options.py
@@ -395,9 +395,11 @@ def can_migrate(self, connection):
             )
         return True
 
-    @property
+    @cached_property
     def verbose_name_raw(self):
         """Return the untranslated verbose name."""
+        if isinstance(self.verbose_name, str):
+            return self.verbose_name
         with override(None):
             return str(self.verbose_name)
 

Test patch: diff --git a/tests/model_meta/models.py b/tests/model_meta/models.py
index 6da62be2ac26..bc69d61a59cd 100644
--- a/tests/model_meta/models.py
+++ b/tests/model_meta/models.py
@@ -1,6 +1,7 @@
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.contenttypes.models import ContentType
 from django.db import models
+from django.utils.translation import gettext_lazy as _
 
 
 class Relation(models.Model):
@@ -124,6 +125,9 @@ class Person(BasePerson):
     # GR fields
     generic_relation_concrete = GenericRelation(Relation)
 
+    class Meta:
+        verbose_name = _("Person")
+
 
 class ProxyPerson(Person):
     class Meta:
diff --git a/tests/model_meta/tests.py b/tests/model_meta/tests.py
index fe2f6e63da8d..7204a5e93a14 100644
--- a/tests/model_meta/tests.py
+++ b/tests/model_meta/tests.py
@@ -222,6 +222,17 @@ def test_get_fields_only_searches_forward_on_apps_not_ready(self):
             opts.apps.models_ready = True
 
 
+class VerboseNameRawTests(SimpleTestCase):
+    def test_string(self):
+        # Clear cached property.
+        Relation._meta.__dict__.pop("verbose_name_raw", None)
+        self.assertEqual(Relation._meta.verbose_name_raw, "relation")
+
+    def test_gettext(self):
+        Person._meta.__dict__.pop("verbose_name_raw", None)
+        self.assertEqual(Person._meta.verbose_name_raw, "Person")
+
+
 class RelationTreeTests(SimpleTestCase):
     all_models = (Relation, AbstractPerson, BasePerson, Person, ProxyPerson, Relating)
Repository: roboflow/supervision
Issue category: Bug Report

Crash when filtering empty detections: xyxy shape (0, 0, 4).
Reproduction code:

```python
import supervision as sv
import numpy as np

CLASSES = [0, 1, 2]

prediction = sv.Detections.empty()
prediction = prediction[np.isin(prediction["class_name"], CLASSES)]
```

Error:

```
Traceback (most recent call last):
  File "/Users/linasko/.settler_workspace/pr/supervision-fresh/run_detections.py", line 7, in <module>
    prediction = prediction[np.isin(prediction["class_name"], CLASSES)]
  File "/Users/linasko/.settler_workspace/pr/supervision-fresh/supervision/detection/core.py", line 1206, in __getitem__
    return Detections(
  File "<string>", line 10, in __init__
  File "/Users/linasko/.settler_workspace/pr/supervision-fresh/supervision/detection/core.py", line 144, in __post_init__
    validate_detections_fields(
  File "/Users/linasko/.settler_workspace/pr/supervision-fresh/supervision/validators/__init__.py", line 120, in validate_detections_fields
    validate_xyxy(xyxy)
  File "/Users/linasko/.settler_workspace/pr/supervision-fresh/supervision/validators/__init__.py", line 11, in validate_xyxy
    raise ValueError(
ValueError: xyxy must be a 2D np.ndarray with shape (_, 4), but got shape (0, 0, 4)
```



Functions to edit:
supervision/detection/core.py:Detections.__getitem__

Patch:
diff --git a/supervision/detection/core.py b/supervision/detection/core.py
index 74c663a89..14f4c0ef8 100644
--- a/supervision/detection/core.py
+++ b/supervision/detection/core.py
@@ -1201,6 +1201,8 @@ def __getitem__(
         """
         if isinstance(index, str):
             return self.data.get(index)
+        if self.is_empty():
+            return Detections.empty()
         if isinstance(index, int):
             index = [index]
         return Detections(

Test patch: diff --git a/test/detection/test_core.py b/test/detection/test_core.py
index 61796bef2..dfa784fcb 100644
--- a/test/detection/test_core.py
+++ b/test/detection/test_core.py
@@ -223,6 +223,12 @@
             None,
             pytest.raises(IndexError),
         ),
+        (
+            Detections.empty(),
+            np.isin(Detections.empty()["class_name"], ["cat", "dog"]),
+            Detections.empty(),
+            DoesNotRaise(),
+        ),  # Filter an empty detections by specific class names
     ],
 )
 def test_getitem(
Repository: rq/rq
Issue category: Bug Report

Dangling job occurs when job_id contains the character ":"
Hi,

After updating to v2.0.0, job_id cannot contain the character ":"; otherwise, the job is never picked up or started by a worker.

I'll investigate this over the next few days, but I suspect that [PR #1964](https://github.com/rq/rq/pull/1964) might restrict the job_id format. We may need to add validation when creating jobs to address this.



Functions to edit:
rq/job.py:Job.set_id

Patch:
diff --git a/rq/job.py b/rq/job.py
index 918f7fdc1..7a964aef0 100644
--- a/rq/job.py
+++ b/rq/job.py
@@ -729,6 +729,10 @@ def set_id(self, value: str) -> None:
         """
         if not isinstance(value, str):
             raise TypeError('id must be a string, not {0}'.format(type(value)))
+
+        if ":" in value:
+            raise ValueError('id must not contain ":"')
+
         self._id = value
 
     def heartbeat(self, timestamp: datetime, ttl: int, pipeline: Optional['Pipeline'] = None, xx: bool = False):

Test patch: diff --git a/tests/test_job.py b/tests/test_job.py
index 36c356e50..9f93cfbf8 100644
--- a/tests/test_job.py
+++ b/tests/test_job.py
@@ -900,6 +900,13 @@ def test_create_job_with_id(self):
 
         self.assertRaises(TypeError, queue.enqueue, fixtures.say_hello, job_id=1234)
 
+    def test_create_job_with_invalid_id(self):
+        """test creating jobs with a custom invalid ID (with character :)"""
+        queue = Queue(connection=self.connection)
+
+        with self.assertRaises(ValueError):
+            queue.enqueue(fixtures.say_hello, job_id="1234:4321")
+
     def test_create_job_with_async(self):
         """test creating jobs with async function"""
         queue = Queue(connection=self.connection)
Repository: tobymao/sqlglot
Issue category: Bug Report

TSQL fails on parsing DATEDIFF function with literals
Hello,
I just discovered that this code generates an error while parsing DATEDIFF second argument:
```
import sqlglot
statement = """
SELECT DATEADD(DAY, DATEDIFF(DAY, -3, CREATION_TIME_NEW), '08:00:00')
FROM y
"""

ast = sqlglot.parse_one(statement, 'tsql')
print(ast.sql('tsql'))
```

Error:
```
Python312\Lib\site-packages\sqlglot\dialects\tsql.py:235, in _build_date_delta.<locals>._builder(args)

    232 if start_date and start_date.is_number:
    233     # Numeric types are valid DATETIME values
    234     if start_date.is_int:
--> 235         adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this))
    236         start_date = exp.Literal.string(adds.strftime("%F"))
    237     else:
    238         # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs.
    239         # This is not a problem when generating T-SQL code, it is when transpiling to other dialects.

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Literal'
```
start_date at this point is:
```
Neg(
  this=Literal(this=3, is_string=False))
```

So `int(start_date.this)` fails.


Functions to edit:
sqlglot/dialects/tsql.py:_build_date_delta

Patch:
diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py
index 856142edc4..1acc5ca8a7 100644
--- a/sqlglot/dialects/tsql.py
+++ b/sqlglot/dialects/tsql.py
@@ -232,7 +232,7 @@ def _builder(args: t.List) -> E:
         if start_date and start_date.is_number:
             # Numeric types are valid DATETIME values
             if start_date.is_int:
-                adds = DEFAULT_START_DATE + datetime.timedelta(days=int(start_date.this))
+                adds = DEFAULT_START_DATE + datetime.timedelta(days=start_date.to_py())
                 start_date = exp.Literal.string(adds.strftime("%F"))
             else:
                 # We currently don't handle float values, i.e. they're not converted to equivalent DATETIMEs.

Test patch: diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py
index 61365994bd..e8cd69648b 100644
--- a/tests/dialects/test_tsql.py
+++ b/tests/dialects/test_tsql.py
@@ -1579,6 +1579,11 @@ def test_date_diff(self):
             },
         )
 
+        self.validate_identity(
+            "SELECT DATEADD(DAY, DATEDIFF(DAY, -3, GETDATE()), '08:00:00')",
+            "SELECT DATEADD(DAY, DATEDIFF(DAY, CAST('1899-12-29' AS DATETIME2), CAST(GETDATE() AS DATETIME2)), '08:00:00')",
+        )
+
     def test_lateral_subquery(self):
         self.validate_all(
             "SELECT x.a, x.b, t.v, t.y FROM x CROSS APPLY (SELECT v, y FROM t) t(v, y)",