ernie-research/MEnvData-SWE huggingface dataset:
Repository: pydantic/pydantic (Python)

Issue:
ModelField and ModelPrivateAttr should raise TypeError
as per https://github.com/samuelcolvin/pydantic/pull/2057#discussion_r513312681 both methods should raise `TypeError` not `ValueError` when called with the wrong arguments.

Pretty trivial change, but needs to wait for a major release.


Discussion:

Patch:
diff --git a/pydantic/fields.py b/pydantic/fields.py
index 36a31df3e28..a8a34d822ff 100644
--- a/pydantic/fields.py
+++ b/pydantic/fields.py
@@ -113,7 +113,7 @@ def __init__(self, **kwargs: Any) -> None:
         self.default_factory = kwargs.get('default_factory')
 
         if self.default is not Undefined and self.default_factory is not None:
-            raise ValueError('cannot specify both default and default_factory')
+            raise TypeError('cannot specify both default and default_factory')
 
         self.alias = kwargs.get('alias')
         self.alias_priority = kwargs.get('alias_priority') or 2 if self.alias is not None else None
@@ -732,7 +732,7 @@ def PrivateAttr(
         ValueError: If both `default` and `default_factory` are set.
     """
     if default is not Undefined and default_factory is not None:
-        raise ValueError('cannot specify both default and default_factory')
+        raise TypeError('cannot specify both default and default_factory')
 
     return ModelPrivateAttr(
         default,


Test patch:
diff --git a/tests/test_main.py b/tests/test_main.py
index a8f7b690885..c664720f03a 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -1376,7 +1376,7 @@ class MyModel(BaseModel):
 
 
 def test_two_defaults():
-    with pytest.raises(ValueError, match='^cannot specify both default and default_factory$'):
+    with pytest.raises(TypeError, match='^cannot specify both default and default_factory$'):
 
         class Model(BaseModel):
             a: int = Field(default=3, default_factory=lambda: 3)
diff --git a/tests/test_private_attributes.py b/tests/test_private_attributes.py
index 4c5783a0d7d..9119528da81 100644
--- a/tests/test_private_attributes.py
+++ b/tests/test_private_attributes.py
@@ -194,7 +194,7 @@ def __init__(self):
 
 
 def test_default_and_default_factory_used_error():
-    with pytest.raises(ValueError, match='cannot specify both default and default_factory'):
+    with pytest.raises(TypeError, match='cannot specify both default and default_factory'):
         PrivateAttr(default=123, default_factory=lambda: 321)
Repository: beeware/briefcase (Python)

Issue:
Creating a new project using quoted inputs results in an invalid pyproject.toml
### Describe the bug

Several of the user inputs for the `briefcase new` command are inserted verbatim in to the `pyproject.toml`. This TOML document uses double quotes to enclose these strings; therefore, if the user inputs contain double quotes, the TOML will be invalid.

While entering text with double quotes in to the prompts wouldn't normally be expected, at least for some of the fields, such as name (perhaps for a quoted nickname) or the description, this character should be supported.

### Steps to reproduce

1. Run `briefcase new`
2. For the author, enter `Harald "Bluetooth" Gormsson`
3. Run `briefcase dev` in the project

### Expected behavior

`pyproject.toml` is valid.

A similar tactic to https://github.com/beeware/briefcase-template/pull/66 seems reasonable.

### Screenshots

_No response_

### Environment

- Operating System: pop os 22.04
- Python version: 3.10.14
- Software versions:
  - Briefcase: `0.3.18.dev206+g38fbb22b.d20240422`


### Logs

```console
❯ briefcase dev

Briefcase configuration error: Invalid pyproject.toml: Expected newline or end of document after a statement (at line 8, column 19)
```

### Additional context

_No response_


Discussion:
Working on this at PyconUS 2024 sprints.
The supporting template pull request is [https://github.com/beeware/briefcase-template/pull/125](https://github.com/beeware/briefcase-template/pull/125)
Can we close this issue, or are some more changes required?
@mhsmith This also needs #1811, which is currently waiting for CI to complete.



Patch:
diff --git a/changes/1746.bugfix.rst b/changes/1746.bugfix.rst
new file mode 100644
index 000000000..0c9d3a96f
--- /dev/null
+++ b/changes/1746.bugfix.rst
@@ -0,0 +1,1 @@
+Escaping of quotation marks in TOML templates was corrected.
diff --git a/src/briefcase/integrations/cookiecutter.py b/src/briefcase/integrations/cookiecutter.py
index 25c0e5868..3c66ffd06 100644
--- a/src/briefcase/integrations/cookiecutter.py
+++ b/src/briefcase/integrations/cookiecutter.py
@@ -62,7 +62,7 @@ def __init__(self, environment):
 
         def escape_toml(obj):
             """Escapes double quotes and backslashes."""
-            return obj.replace('"', '"').replace("\\", "\\\\")
+            return obj.replace("\\", "\\\\").replace('"', '\\"')
 
         def escape_non_ascii(obj):
             """Quotes obj if non ascii characters are present."""


Test patch:
diff --git a/tests/integrations/cookiecutter/test_TOMLEscape.py b/tests/integrations/cookiecutter/test_TOMLEscape.py
index e80adc335..a3e6d05f5 100644
--- a/tests/integrations/cookiecutter/test_TOMLEscape.py
+++ b/tests/integrations/cookiecutter/test_TOMLEscape.py
@@ -10,7 +10,7 @@
     [
         # Single digit minor
         ("Hello World", "Hello World"),
-        ('Hello " World', 'Hello " World'),
+        ('Hello " World', 'Hello \\" World'),
         ("Hello \\ World", "Hello \\\\ World"),
     ],
 )
Repository: lightly-ai/lightly (Python)

Issue:
Bug in PMSNLoss
Nice implementation of the [PMSNLoss](https://github.com/lightly-ai/lightly/blob/ddfed3c4dc03a8d2722df24bfa537d24ac80bde6/lightly/loss/pmsn_loss.py)! But the computation of Kullback-Leibler divergence missed `.log()` in Line 71&142.



Discussion:
Hi, thanks for using Lightly and reporting the issue! You are right, I just made a PR to fix it.



Patch:
diff --git a/lightly/loss/pmsn_loss.py b/lightly/loss/pmsn_loss.py
index b8a66b9d2..15e97e2cb 100644
--- a/lightly/loss/pmsn_loss.py
+++ b/lightly/loss/pmsn_loss.py
@@ -68,7 +68,9 @@ def regularization_loss(self, mean_anchor_probs: Tensor) -> Tensor:
             exponent=self.power_law_exponent,
             device=mean_anchor_probs.device,
         )
-        loss = F.kl_div(input=mean_anchor_probs, target=power_dist, reduction="sum")
+        loss = F.kl_div(
+            input=mean_anchor_probs.log(), target=power_dist, reduction="sum"
+        )
         return loss
 
 
@@ -139,7 +141,9 @@ def regularization_loss(self, mean_anchor_probs: Tensor) -> Tensor:
         target_dist = self.target_distribution(mean_anchor_probs).to(
             mean_anchor_probs.device
         )
-        loss = F.kl_div(input=mean_anchor_probs, target=target_dist, reduction="sum")
+        loss = F.kl_div(
+            input=mean_anchor_probs.log(), target=target_dist, reduction="sum"
+        )
         return loss
 
 


Test patch:
diff --git a/tests/loss/test_PMSNLoss.py b/tests/loss/test_PMSNLoss.py
index 4919e965b..1ddc8b84e 100644
--- a/tests/loss/test_PMSNLoss.py
+++ b/tests/loss/test_PMSNLoss.py
@@ -12,7 +12,7 @@
 class TestPMSNLoss:
     def test_regularization_loss(self) -> None:
         criterion = PMSNLoss()
-        mean_anchor_probs = torch.Tensor([0.1, 0.3, 0.6]).log()
+        mean_anchor_probs = torch.Tensor([0.1, 0.3, 0.6])
         loss = criterion.regularization_loss(mean_anchor_probs=mean_anchor_probs)
         norm = 1 / (1**0.25) + 1 / (2**0.25) + 1 / (3**0.25)
         t0 = 1 / (1**0.25) / norm
@@ -45,7 +45,7 @@ def test_forward_cuda(self) -> None:
 class TestPMSNCustomLoss:
     def test_regularization_loss(self) -> None:
         criterion = PMSNCustomLoss(target_distribution=_uniform_distribution)
-        mean_anchor_probs = torch.Tensor([0.1, 0.3, 0.6]).log()
+        mean_anchor_probs = torch.Tensor([0.1, 0.3, 0.6])
         loss = criterion.regularization_loss(mean_anchor_probs=mean_anchor_probs)
         expected_loss = (
             1
Repository: albumentations-team/albumentations (Python)

Issue:
Error "Key image is not in available keys" for empty transform
## Describe the bug

Empty transform is not working anymore. Behavior changed from 1.4.6 to 1.4.7

### To Reproduce

The following code works with 1.4.6

```python
import numpy as np
import albumentations as A

print(A.__version__)

transform = A.Compose([])
image = np.ones((100, 100, 3), dtype=np.uint8)

transformed = transform(image=image)
print(transformed['image'].shape)
```
For 1.4.7 it raises an error:
```
ValueError: Key image is not in available keys.
```

### Additional context

I need an empty transform for the unification of the pipeline.
As a workaround `A.NoOp()` can be used, it works fine, just submitting this to notify.



Discussion:
Thanks! This is a really good one.

Never tried to use `Compose([])`, but I, guess, it is expected to work as `NoOp()` => `Compose([])`, `SomeOf`, `OneOf`, `SelectedChannels` should work on [] => Good test to add
> but I, guess, it is expected to work as `NoOp()` => `Compose([])`, `SomeOf`, `OneOf`, `SelectedChannels` should work on [] => Good test to add
Empty Compose make sense, but container with empty list not sure - one of "zero" or some of zero. By the way, probabilities of containers with empty list will crush with when divided by zero - will add check there. 




Patch:
diff --git a/albumentations/core/composition.py b/albumentations/core/composition.py
index 000f20655..d8b9bb46f 100644
--- a/albumentations/core/composition.py
+++ b/albumentations/core/composition.py
@@ -40,6 +40,8 @@
 TransformType = Union[BasicTransform, "BaseCompose"]
 TransformsSeqType = List[TransformType]
 
+AVAILABLE_KEYS = ("image", "mask", "masks", "bboxes", "keypoints", "global_label")
+
 
 def get_always_apply(transforms: Union["BaseCompose", TransformsSeqType]) -> TransformsSeqType:
     new_transforms: TransformsSeqType = []
@@ -207,6 +209,8 @@ def __init__(
             proc.ensure_transforms_valid(self.transforms)
 
         self.add_targets(additional_targets)
+        if not self.transforms:  # if no transforms -> do nothing, all keys will be available
+            self._available_keys.update(AVAILABLE_KEYS)
 
         self.is_check_args = True
         self._disable_check_args_for_transforms(self.transforms)


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index e729e04ad..698ea494b 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -514,7 +514,8 @@ def test_sequential_multiple_transformations(image, aug):
             A.RandomGamma(p=1),
             A.ImageCompression(quality_range=(75, 100), p=1),
             A.Crop(x_max=50, y_max=50),
-        ]
+        ],
+        [],  # empty
     ]
 )
 @pytest.mark.parametrize(
Repository: amoffat/sh (Python)

Issue:
Need way for await sh.command to return RunningCommand
I'm finally porting [Carthage](https://github.com/hadron/carthage)  from sh 1.x to sh 2.x. We had our own hack to enable async for sh, and we had a lot of code that did things like
```python
result = await sh.ssh(...)
```
And then for example looked at `result.stdout`.
So, part of this can be handled by setting `_return_cmd=True`, but the definition of `RunningCommand.__await__` is hard-coded to return `str(self)`.
Obviously, I can do something like
```python
result = sh.ssh(...)
await result
```
But that feels clumsy.
I'd like a kwarg that returns a RunningCommand even on async await.
My preference would be to try and convince you that `_return_cmd` should affect await as well as __call__, but if you are concerned about the API instability, I'm happy with anything that I can pass into bake.

Thanks for your consideration.



Discussion:
I think that's a reasonable request, and the way the api should work. The fact that it doesn't seems to be incorrect behavior. Do you feel comfortable making this change?

Yes. I'll send in a pull request tomorrow.
The change is trivial, learning your test system enough to propose tests
will take most of the time.
But I've been working with sh long enough I should go learn the test
system anyway.




Patch:
diff --git a/sh.py b/sh.py
index d52d8b60..b02d6e16 100644
--- a/sh.py
+++ b/sh.py
@@ -889,7 +889,10 @@ def __next__(self):
     def __await__(self):
         async def wait_for_completion():
             await self.aio_output_complete.wait()
-            return str(self)
+            if self.call_args["return_cmd"]:
+                return self
+            else:
+                return str(self)
 
         return wait_for_completion().__await__()
 


Test patch:
diff --git a/tests/sh_test.py b/tests/sh_test.py
index 8a87fd69..0fe03111 100644
--- a/tests/sh_test.py
+++ b/tests/sh_test.py
@@ -1732,7 +1732,7 @@ def test_async_exc(self):
         py = create_tmp_test("""exit(34)""")
 
         async def producer():
-            await python(py.name, _async=True)
+            await python(py.name, _async=True, _return_cmd=False)
 
         self.assertRaises(sh.ErrorReturnCode_34, asyncio.run, producer())
 
@@ -1786,6 +1786,22 @@ async def producer():
 
         self.assertRaises(sh.ErrorReturnCode_34, asyncio.run, producer())
 
+    def test_async_return_cmd(self):
+        py = create_tmp_test(
+            """
+import sys
+sys.exit(0)
+"""
+        )
+
+        async def main():
+            result = await python(py.name, _async=True, _return_cmd=True)
+            self.assertIsInstance(result, sh.RunningCommand)
+            result_str = await python(py.name, _async=True, _return_cmd=False)
+            self.assertIsInstance(result_str, str)
+
+        asyncio.run(main())
+
     def test_handle_both_out_and_err(self):
         py = create_tmp_test(
             """
Repository: Qiskit/qiskit (Python)

Issue:
Add insert_barrier argument to UnitaryOverlap
### What should we add?

This argument would insert a barrier between the two unitaries. This is useful if you want to prevent circuit optimization between the two parts.


Discussion:

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: pallets-eco/wtforms (Python)

Issue:
Form field errors not JSON serializable with default Flask JSONProvider
The decision in 3.0 to use None as a dictionary key for holding form level errors #595 has the unfortunate side-effect of not allowing the JSON serializer to sort keys - which is the default set up by Flask.

One gets the error: `TypeError: '<' not supported between instances of 'NoneType' and 'str'`

Not sure of a good solution since it has been this way for a couple years now - a simple but not great solution would be to offer a configuration option to change the key.

I also realize that wtforms isn't explicitly tied to Flask - though as a low level library it would be nice if it didn't force the behavior of applications and higher level frameworks.


### Environment

* Python version: 3.9
* wtforms version: 3.1.2



Discussion:
I don't mind just changing it to `""` or `"__form__"` in a feature release.
Thanks - a comment in #595 suggests '__all__' - same as django - I don't really care - though using anything that could be confused as core python I think would just cause confusion (also - it isn't all errors!).   '__form__' seems pretty safe.
I use the empty string `""` in another API library I maintain, which isn't otherwise valid as a form field name.



Patch:
diff --git a/CHANGES.rst b/CHANGES.rst
index b05d6e03a..5f12719bc 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -16,6 +16,14 @@ Unreleased
   can validate multiple valued fields like :class:`~fields.SelectMultipleField`
   :pr:`538` :pr:`807`
 
+- Breaking change: The key for form errors moved from :data:`None` to
+  empty string `""`. :issue:`829` :pr:`858`
+
+.. note::
+   If you need to keep the old behavior you can set the ``_form_error_key``
+   parameter of you form to :data:`None`.
+
+
 Version 3.1.2
 -------------
 
diff --git a/src/wtforms/form.py b/src/wtforms/form.py
index b462936b6..d0a77badc 100644
--- a/src/wtforms/form.py
+++ b/src/wtforms/form.py
@@ -30,6 +30,7 @@ def __init__(self, fields, prefix="", meta=_default_meta):
             prefix += "-"
 
         self.meta = meta
+        self._form_error_key = ""
         self._prefix = prefix
         self._fields = OrderedDict()
 
@@ -155,7 +156,7 @@ def data(self):
     def errors(self):
         errors = {name: f.errors for name, f in self._fields.items() if f.errors}
         if self.form_errors:
-            errors[None] = self.form_errors
+            errors[self._form_error_key] = self.form_errors
         return errors
 
 


Test patch:
diff --git a/tests/test_form.py b/tests/test_form.py
index e02e3e626..d64cc2182 100644
--- a/tests/test_form.py
+++ b/tests/test_form.py
@@ -204,7 +204,7 @@ def validate(self):
     f = F(a=0, b=1)
     assert not f.validate()
     assert ["a + b should be even"] == f.form_errors
-    assert ["a + b should be even"] == f.errors[None]
+    assert ["a + b should be even"] == f.errors[""]
 
 
 def test_field_adding_disabled():
Repository: langchain-ai/langchain (Python)

Issue:
Length Based Example Selector
I was reviewing the code for Length Based Example Selector and found:
https://github.com/hwchase17/langchain/blob/12dc7f26cca1744c0023792f81645214ffd0773c/langchain/prompts/example_selector/length_based.py#L54

I think this line should be checking if `new_length < 0` instead of `i  < 0`. 

`i` is the loop variable, and `new_length` is the remaining length after deducting the length of the example. I believe the goal is to break early if adding the current example would exceed the max length.


Discussion:

Patch:
diff --git a/langchain/prompts/example_selector/length_based.py b/langchain/prompts/example_selector/length_based.py
index 086b72ce55ec0..a6f6cd8d2353f 100644
--- a/langchain/prompts/example_selector/length_based.py
+++ b/langchain/prompts/example_selector/length_based.py
@@ -51,7 +51,7 @@ def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
         examples = []
         while remaining_length > 0 and i < len(self.examples):
             new_length = remaining_length - self.example_text_lengths[i]
-            if i < 0:
+            if new_length < 0:
                 break
             else:
                 examples.append(self.examples[i])


Test patch:
diff --git a/tests/unit_tests/prompts/test_length_based_example_selector.py b/tests/unit_tests/prompts/test_length_based_example_selector.py
index 45895871b80f5..38fd689c4e8d5 100644
--- a/tests/unit_tests/prompts/test_length_based_example_selector.py
+++ b/tests/unit_tests/prompts/test_length_based_example_selector.py
@@ -17,7 +17,7 @@ def selector() -> LengthBasedExampleSelector:
     selector = LengthBasedExampleSelector(
         examples=EXAMPLES,
         example_prompt=prompts,
-        max_length=25,
+        max_length=30,
     )
     return selector
Repository: ruby-i18n/i18n (Ruby)

Issue:
[BUG] Loading RB files with Pathname in `load_path` raises `TypeError`
## What I tried to do

Set `I18n.load_path` to `Pathname` instances rather than strings. This works for `.yml`, but for `.rb` files it raises.

This came up cause I allowed [Rubocop to auto correct a configuration](https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsrootpathnamemethods) from

`config.i18n.load_path += Dir[Rails.root.join("config/locales/**/*.{rb,yml}")] `

to

`config.i18n.load_path += Rails.root.glob("config/locales/**/*.{rb,yml}") `

where `glob` returns `Pathname`s

## What I expected to happen

It to not raise. It raises cause the 3rd argument to `eval()` should be a string to the file path

## What actually happened

```
`eval': no implicit conversion of Pathname into String (TypeError)

translations = eval(IO.read(filename), binding, filename)
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

## Versions of i18n, rails, and anything else you think is necessary

Rails 7.2, 
I18n 1.14.5


PR with fix coming soon. 

Thanks!



Discussion:

Patch:
diff --git a/lib/i18n/backend/base.rb b/lib/i18n/backend/base.rb
index 7ca9c28a..6e7c7df1 100644
--- a/lib/i18n/backend/base.rb
+++ b/lib/i18n/backend/base.rb
@@ -244,7 +244,7 @@ def load_file(filename)
         # Loads a plain Ruby translations file. eval'ing the file must yield
         # a Hash containing translation data with locales as toplevel keys.
         def load_rb(filename)
-          translations = eval(IO.read(filename), binding, filename)
+          translations = eval(IO.read(filename), binding, filename.to_s)
           [translations, false]
         end
 


Test patch:
diff --git a/test/i18n/load_path_test.rb b/test/i18n/load_path_test.rb
index 7d0d27a1..ab354c08 100644
--- a/test/i18n/load_path_test.rb
+++ b/test/i18n/load_path_test.rb
@@ -31,4 +31,14 @@ def setup
     I18n.load_path << Dir[locales_dir + '/*.{rb,yml}']
     assert_equal "baz", I18n.t(:'foo.bar')
   end
+
+  test "adding Pathnames to the load path does not break YML file locale loading" do
+    I18n.load_path << Pathname.new(locales_dir + '/en.yml')
+    assert_equal "baz", I18n.t(:'foo.bar')
+  end
+
+  test "adding Pathnames to the load path does not break Ruby file locale loading" do
+    I18n.load_path << Pathname.new(locales_dir + '/en.rb')
+    assert_equal "bas", I18n.t(:'fuh.bah')
+  end
 end
Repository: yippee-fun/phlex (Ruby)

Issue:
unsafe_raw with helper that returns nil gives LocalJumpError (no block given)
I'm using [`vite-rails`](https://vite-ruby.netlify.app/guide/rails.html#tag-helpers-%F0%9F%8F%B7) in a new project together with Phlex. They supply a few helpers to set up the assets:

```ruby
<%= vite_client_tag %>
<%= vite_javascript_tag "application" %>
<%= vite_stylesheet_tag "application" %>
```

I use them in my Phlex layout like so:

```ruby
unsafe_raw helpers.vite_client_tag
unsafe_raw helpers.vite_javascript_tag "application"
unsafe_raw helpers.vite_stylesheet_tag "application"
```

The first helper, `vite_client_tag` can return `nil` when the vite dev server is not running (in production or when you dont' explicitly start it in development):

https://github.com/ElMassimo/vite_ruby/blob/41441af83f5cf3b3d02dcdd01fee4aaa1b564a07/vite_rails/lib/vite_rails/tag_helpers.rb#L7

This leads to a `no block given`, since `unsafe_raw` expects either some content or a block:

https://github.com/joeldrapper/phlex/blob/b3324fa7ffdc4b65586ac3fec1b8df6eaa9eef4a/lib/phlex/html.rb#L227

I've fixed it for now with `unsafe_raw helpers.vite_client_tag if helpers.vite_client_tag`, but I think it's fair to assume that helpers can return nil without a block. 

I'm not sure what the correct fix is performance wise, would a simple `if block_given?` check be sufficient?


Discussion:
I think it should be reasonable to change `unsafe_raw` to just this. I can't remember exactly why it accepts a block, but I have a feeling it was to get around something that isn't an issue anymore.

```ruby
def unsafe_raw(content)
  return nil unless content
  @_target << content
end
```
That makes sense, I've created a PR with the fix you proposed #417 🎉 



Patch:
diff --git a/lib/phlex/html.rb b/lib/phlex/html.rb
index c4802c3e..afe24b88 100644
--- a/lib/phlex/html.rb
+++ b/lib/phlex/html.rb
@@ -224,8 +224,9 @@ def doctype
 		end
 
 		def unsafe_raw(content = nil, &block)
-			@_target << (content || instance_exec(&block))
-			nil
+			return nil unless content
+
+			@_target << content
 		end
 
 		def capture(&block)


Test patch:
diff --git a/test/phlex/view/unsafe_raw.rb b/test/phlex/view/unsafe_raw.rb
index 525f3c5a..e63e12ba 100644
--- a/test/phlex/view/unsafe_raw.rb
+++ b/test/phlex/view/unsafe_raw.rb
@@ -10,8 +10,20 @@ def template
 			end
 		end
 
-		it "renders produces the correct output" do
+		it "renders the correct output" do
 			expect(output).to be == %(<h1 class="test">Hello</h1>)
 		end
 	end
+
+	with "nil content" do
+		view do
+			def template
+				unsafe_raw nil
+			end
+		end
+
+		it "renders empty output" do
+			expect(output).to be == ""
+		end
+	end
 end
Repository: standardrb/standard (Ruby)

Issue:
LSP server fails to initialise in Helix editor
When using `standardrb --lsp` in Helix I get error messages in the log:

```
2023-03-31T18:05:48.225 helix_lsp [ERROR] failed to initialize language server: failed to parse: invalid type: boolean `true`, expected struct ExecuteCommandOptions
```

As this worked in Neovim, I initially reported the bug to Helix: https://github.com/helix-editor/helix/issues/6506 who responded:

> This is a bug in StandardRB: it's sending "executeCommandProvider":true in the initialization response but that field can't be a boolean in the spec: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#executeCommandOptions


Discussion:
Seems like the expected interface is [here](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#executeCommandOptions)



Patch:
diff --git a/lib/standard/lsp/routes.rb b/lib/standard/lsp/routes.rb
index 796d5ae7..f20e6687 100644
--- a/lib/standard/lsp/routes.rb
+++ b/lib/standard/lsp/routes.rb
@@ -28,7 +28,9 @@ def for(name)
           capabilities: Proto::Interface::ServerCapabilities.new(
             document_formatting_provider: true,
             diagnostic_provider: true,
-            execute_command_provider: true,
+            execute_command_provider: Proto::Interface::ExecuteCommandOptions.new(
+              commands: ["standardRuby.formatAutoFixes"]
+            ),
             text_document_sync: Proto::Interface::TextDocumentSyncOptions.new(
               change: Proto::Constant::TextDocumentSyncKind::FULL,
               open_close: true


Test patch:
diff --git a/test/standard/runners/lsp_test.rb b/test/standard/runners/lsp_test.rb
index cc436280..60492896 100644
--- a/test/standard/runners/lsp_test.rb
+++ b/test/standard/runners/lsp_test.rb
@@ -19,7 +19,7 @@ def test_server_initializes_and_responds_with_proper_capabilities
         textDocumentSync: {openClose: true, change: 1},
         documentFormattingProvider: true,
         diagnosticProvider: true,
-        executeCommandProvider: true
+        executeCommandProvider: {commands: ["standardRuby.formatAutoFixes"]}
       }},
       jsonrpc: "2.0"
     }
Repository: Shopify/liquid (Ruby)

Issue:
Unable to call "key?" and "[]=" on Liquid::Context when strict_variable is true
While building a Custom Tag, I want to check if a variable exist in the context, but calling "key?" gives an error

Example code:
```
>> context = Liquid::Context.new({})
#<Liquid::Context:0x00000003027ffe68

>> context.strict_variables=true
true

>> context.key?('test')
Liquid error: undefined variable test (Liquid::UndefinedVariable)
```

Seems counterintuitive to not be able to use "key?" to check if a variable is set.

Similar issue with using `[]=` which does not work as expected, instead of allowing to set the variable if it doesn't exist, it throws an error instead.


My current workaround is to access the scope and check for the key there...
```
context.scopes[0].key?('test')
```

Thanks


Discussion:
Hey @beld2107! I'm a little confused with what you're saying because the whole point of `strict_variables` is to raise when looking up a variable that doesn't exist.

But I see what you're saying: `key?` returns a boolean on the existence of a key, not the value itself so it might be reasonable to not raise here. I'll have a think on this, thanks!
Yes I guess it's always a question how you define strict variable! 
My belief is that it's would raise when trying to read the value using [], but it would not raise on "key?". As that would be the safe way to check.



Patch:
diff --git a/lib/liquid/context.rb b/lib/liquid/context.rb
index 1ef272d46..433b6d003 100644
--- a/lib/liquid/context.rb
+++ b/lib/liquid/context.rb
@@ -184,7 +184,7 @@ def [](expression)
     end
 
     def key?(key)
-      self[key] != nil
+      find_variable(key, raise_on_not_found: false) != nil
     end
 
     def evaluate(object)


Test patch:
diff --git a/test/integration/context_test.rb b/test/integration/context_test.rb
index f59147e29..d230734f6 100644
--- a/test/integration/context_test.rb
+++ b/test/integration/context_test.rb
@@ -639,6 +639,21 @@ def test_has_key_will_not_add_an_error_for_missing_keys
     end
   end
 
+  def test_key_lookup_will_raise_for_missing_keys_when_strict_variables_is_enabled
+    context = Context.new
+    context.strict_variables = true
+    assert_raises(Liquid::UndefinedVariable) do
+      context['unknown']
+    end
+  end
+
+  def test_has_key_will_not_raise_for_missing_keys_when_strict_variables_is_enabled
+    context = Context.new
+    context.strict_variables = true
+    refute(context.key?('unknown'))
+    assert_empty(context.errors)
+  end
+
   def test_context_always_uses_static_registers
     registers = {
       my_register: :my_value,
Repository: alexreisner/geocoder (Ruby)

Issue:
Unsupported field name 'id' error when using Google Places Search API
When attempting to perform a Places Search API lookup for a given location using the default fields specified by the gem, no results are returned, and an error is printed to the console due to the use of deprecated and now removed `id` and `reference` fields.

### Expected behavior

The default fieldset specified by the gem should be valid.

### Actual behavior

The following error is printed and no results are returned:

```
Google Places Search API error: invalid request (Error while parsing 'fields' parameter: Unsupported field name 'id'. ).
```

### Steps to reproduce
1. Make a `search` request with `lookup: :google_places_search` without specifying `field:`

### Environment info

* Geocoder version: 1.8.2
* Rails version: 7.0.5.1
* Database (if applicable): N/A
* Lookup (if applicable): `google_places_search`


Discussion:
Thanks for this. I'm open to a pull request to fix it. Looks like an easy change, [just two lines](https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/lookups/google_places_search.rb#L57).
I can open a PR tomorrow, just wanted to confirm that was an acceptable solution as it would change the default result set without a suitable replacement.
Good to take that into consideration. But we have to change it if the default is an error. Let's just get rid of those two "legacy" fields, right?
Sure, sounds good.



Patch:
diff --git a/lib/geocoder/lookups/google_places_search.rb b/lib/geocoder/lookups/google_places_search.rb
index 8b4e0ee2b..ecb9d38a4 100644
--- a/lib/geocoder/lookups/google_places_search.rb
+++ b/lib/geocoder/lookups/google_places_search.rb
@@ -49,12 +49,11 @@ def fields(query)
       end
 
       def default_fields
-        legacy = %w[id reference]
         basic = %w[business_status formatted_address geometry icon name 
           photos place_id plus_code types]
         contact = %w[opening_hours]
         atmosphere = %W[price_level rating user_ratings_total]
-        format_fields(legacy, basic, contact, atmosphere)
+        format_fields(basic, contact, atmosphere)
       end
 
       def format_fields(*fields)


Test patch:
diff --git a/test/unit/lookups/google_places_search_test.rb b/test/unit/lookups/google_places_search_test.rb
index 817a220b9..d096c57fa 100644
--- a/test/unit/lookups/google_places_search_test.rb
+++ b/test/unit/lookups/google_places_search_test.rb
@@ -51,7 +51,7 @@ def test_google_places_search_query_url_always_uses_https
 
   def test_google_places_search_query_url_contains_every_field_available_by_default
     url = lookup.query_url(Geocoder::Query.new("some-address"))
-    fields = %w[id reference business_status formatted_address geometry icon name 
+    fields = %w[business_status formatted_address geometry icon name 
       photos place_id plus_code types opening_hours price_level rating 
       user_ratings_total]
     assert_match(/fields=#{fields.join('%2C')}/, url)
Repository: puma/puma (Ruby)

Issue:
undefined method 'reset_max' for nil (NoMethodError)
**Describe the bug**
During a `GET /stats` request, we received the error message `undefined method “reset_max” for nil (NoMethodError) @thread_pool.reset_max`.


```ruby
    def stats
      stats = @thread_pool&.stats || {}          # considers that @thread_pool might be nil
      stats[:max_threads]    = @max_threads
      stats[:requests_count] = @requests_count
      stats[:reactor_max] = @reactor.reactor_max if @reactor
      reset_max                                  # calls reset_max
      stats
    end

    def reset_max
      @reactor.reactor_max = 0 if @reactor
      @thread_pool.reset_max                     # does not consider @thread_pool to be nil
    end
```
A quick look at the stack trace revealed that the method `Puma::Server.reset_max` does not consider `@thread_pool` to be `nil`. However, the calling method `Puma::Server.stats` considers `@thread_pool` to be nil. Therefore, I assume that `reset_max`, since it is called from `stats`, should apply the same consideration with regard to nil values.


https://github.com/puma/puma/blob/a23e6bdefb20d0578fb286ae82a9c9634dc89ab6/lib/puma/server.rb#L709

***Full Stack Trace***
```
NoMethodError: undefined method 'reset_max' for nil (NoMethodError)

      @thread_pool.reset_max
                  ^^^^^^^^^^
    from puma/server.rb:709:in 'reset_max'
    from puma/server.rb:703:in 'stats'
    from puma/single.rb:20:in 'stats'
    from puma/launcher.rb:116:in 'stats'
    from puma/app/status.rb:55:in 'call'
    from puma/request.rb:101:in 'block in Puma::Request#handle_request'
    from puma/thread_pool.rb:346:in 'with_force_shutdown'
    from puma/request.rb:100:in 'handle_request'
    from puma/server.rb:506:in 'process_client'
    from puma/server.rb:265:in 'block in Puma::Server#run'
    from puma/thread_pool.rb:173:in 'block in Puma::ThreadPool#spawn_thread'
```

**To Reproduce**
I'm actually not sure how we managed to cause it. Maybe just bad timing during shutdown? (wild guess)


**Desktop (please complete the following information):**
 - OS: Linux
 - Ruby: 3.4.2
 - Puma: 7.0.4



Discussion:
@eric-wtfoxtrot 

Thanks for opening an issue.   The mistake was mine.  Fixed by #3791.



Patch:
diff --git a/lib/puma/server.rb b/lib/puma/server.rb
index 510f611032..34f4f518a3 100644
--- a/lib/puma/server.rb
+++ b/lib/puma/server.rb
@@ -706,7 +706,7 @@ def stats
 
     def reset_max
       @reactor.reactor_max = 0 if @reactor
-      @thread_pool.reset_max
+      @thread_pool&.reset_max
     end
 
     # below are 'delegations' to binder


Test patch:
diff --git a/test/test_puma_server.rb b/test/test_puma_server.rb
index ec7b8b3d1d..983fa95b88 100644
--- a/test/test_puma_server.rb
+++ b/test/test_puma_server.rb
@@ -2257,4 +2257,8 @@ def test_auto_trim_with_fixed_pool_size
     server_run(min_threads: 2, max_threads: 2, auto_trim_time: 1)
     refute @pool.instance_variable_get(:@auto_trim)
   end
+
+  def test_stats_ok_before_run
+    assert_equal({max_threads: @server.max_threads, requests_count: 0}, @server.stats)
+  end
 end
Repository: ruby/rbs (Ruby)

Issue:
Resolve logic for superclass/self-types differs from Ruby
I just want to check whether this is intentional or not, as it could lead to confusion for users or issues when generating RBS code from Ruby code.

```
module A
  class C
  end

  class B < C
    class C
    end
  end
end
```

In Ruby, `B` will inherit from `A::C`. The same code in RBS has a different behaviour; in RBS `B` will inherit from `A::B::C`. This applies to superclass clauses and self-types only from what I can tell.

```
irb(main):010:0> A::B.ancestors
=> [A::B, A::C, Object, Kernel, BasicObject]
```

```
> rbs -Isig ancestors A::B
::A::B
::A::B::C
::Object
::Kernel
::BasicObject
```


Discussion:
Good find! ... 💦 
We should fix the library to make it compatible with Ruby.
Thank you!



Patch:
diff --git a/lib/rbs/environment.rb b/lib/rbs/environment.rb
index c8b924c9e..28578bc0e 100644
--- a/lib/rbs/environment.rb
+++ b/lib/rbs/environment.rb
@@ -240,6 +240,8 @@ def resolve_declaration(resolver, decl, outer:, prefix:)
         array.unshift(head + decl.name.to_namespace)
       end
 
+      outer_context = context.drop(1)
+
       case decl
       when AST::Declarations::Class
         outer_ = outer + [decl]
@@ -249,8 +251,8 @@ def resolve_declaration(resolver, decl, outer:, prefix:)
           type_params: decl.type_params,
           super_class: decl.super_class&.yield_self do |super_class|
             AST::Declarations::Class::Super.new(
-              name: absolute_type_name(resolver, super_class.name, context: context),
-              args: super_class.args.map {|type| absolute_type(resolver, type, context: context) },
+              name: absolute_type_name(resolver, super_class.name, context: outer_context),
+              args: super_class.args.map {|type| absolute_type(resolver, type, context: outer_context) },
               location: super_class.location
             )
           end,


Test patch:
diff --git a/test/rbs/environment_test.rb b/test/rbs/environment_test.rb
index 6a72b4e86..4660951c0 100644
--- a/test/rbs/environment_test.rb
+++ b/test/rbs/environment_test.rb
@@ -384,6 +384,31 @@ module ::Enumerable[A]
 RBS
   end
 
+  def test_absolute_type_super
+    env = Environment.new
+
+    decls = RBS::Parser.parse_signature(<<-RBS)
+module A
+  class C
+  end
+
+  class B < C
+    class C
+    end
+  end
+end
+    RBS
+
+    decls.each do |decl|
+      env << decl
+    end
+
+    env.resolve_type_names.tap do |env|
+      class_decl = env.class_decls[TypeName("::A::B")]
+      assert_equal TypeName("::A::C"), class_decl.primary.decl.super_class.name
+    end
+  end
+
   def test_reject
     env = Environment.new
Repository: soutaro/steep (Ruby)

Issue:
Returning multiple value
```ruby
# @type method foo: () -> [Integer, String]
def foo
  return 1, ""       # => should type check
end
```


Discussion:

Patch:
diff --git a/lib/steep/type_construction.rb b/lib/steep/type_construction.rb
index 9b626ab8b..c37506c8a 100644
--- a/lib/steep/type_construction.rb
+++ b/lib/steep/type_construction.rb
@@ -1100,12 +1100,9 @@ def synthesize(node, hint: nil, condition: false)
               return_value_node = node.children[0]
               value_type, constr = synthesize(return_value_node, hint: method_return_type)
             else
-              constr = synthesize_children(node)
-              return_types = node.children.map do |value|
-                constr.typing.type_of(node: value)
-              end
-
-              value_type = AST::Builtin::Array.instance_type(union_type(*return_types))
+              # It returns an array
+              array = node.updated(:array)
+              value_type, constr = synthesize(array, hint: method_return_type)
             end
 
             if method_return_type


Test patch:
diff --git a/test/type_construction_test.rb b/test/type_construction_test.rb
index f63b36c13..66cc2e10c 100644
--- a/test/type_construction_test.rb
+++ b/test/type_construction_test.rb
@@ -10469,4 +10469,25 @@ def test_opasgn_error_report
       end
     end
   end
+
+  def test_return__mvalue
+    with_checker(<<~RBS) do |checker|
+        class ReturnMultipleValues
+          def foo: () -> [String, Integer]
+        end
+      RBS
+      source = parse_ruby(<<~RUBY)
+        class ReturnMultipleValues
+          def foo
+            return "foo", 123
+          end
+        end
+      RUBY
+
+      with_standard_construction(checker, source) do |construction, typing|
+        type, _, context = construction.synthesize(source.node)
+        assert_no_error(typing)
+      end
+    end
+  end
 end
Repository: newrelic/newrelic-ruby-agent (Ruby)

Issue:
Create a way to record a metric only once
We need to know when our Concurrent Ruby instrumentation is lit up by our customers's codebases, not just when it is installed because it's a dependency of Rails. 

The working idea to solve this problem right now is to record a metric the first time one of the methods we instrument gets called. 

This prevents a bunch of metrics from being recorded unnecessarily and gives us the visibility we're after.
We have a strategy to `log_once`, let's make something similar for metrics.

Acceptance Criteria:
* record a supportability metric only the first time an instrumented method is invoked


Discussion:
https://issues.newrelic.com/browse/NEWRELIC-5810



Patch:
diff --git a/lib/new_relic/agent.rb b/lib/new_relic/agent.rb
index 8830de550f..0cd211c11a 100644
--- a/lib/new_relic/agent.rb
+++ b/lib/new_relic/agent.rb
@@ -109,6 +109,7 @@ class SerializationError < StandardError; end
     @logger = nil
     @tracer_lock = Mutex.new
     @tracer_queue = []
+    @metrics_already_recorded = Set.new
 
     # The singleton Agent instance.  Used internally.
     def agent # :nodoc:
@@ -203,6 +204,12 @@ def record_metric(metric_name, value) # THREAD_LOCAL_ACCESS
       agent.stats_engine.tl_record_unscoped_metrics(metric_name, value)
     end
 
+    def record_metric_once(metric_name, value = 0.0)
+      return unless @metrics_already_recorded.add?(metric_name)
+
+      record_metric(metric_name, value)
+    end
+
     # Increment a simple counter metric.
     #
     # +metric_name+ should follow a slash separated path convention. Application


Test patch:
diff --git a/test/new_relic/agent_test.rb b/test/new_relic/agent_test.rb
index b4863e6059..a6cd152188 100644
--- a/test/new_relic/agent_test.rb
+++ b/test/new_relic/agent_test.rb
@@ -206,6 +206,15 @@ def test_record_metric
       NewRelic::Agent.record_metric('foo', 12)
     end
 
+    def test_record_metric_once
+      dummy_engine = NewRelic::Agent.agent.stats_engine
+      dummy_engine.expects(:tl_record_unscoped_metrics).with('Supportability/API/record_metric')
+      dummy_engine.expects(:tl_record_unscoped_metrics).with('test/metric', 0.0).once
+      NewRelic::Agent.record_metric_once('test/metric')
+      NewRelic::Agent.record_metric_once('test/metric')
+      NewRelic::Agent.record_metric_once('test/metric')
+    end
+
     def test_record_metric_accepts_hash
       dummy_engine = NewRelic::Agent.agent.stats_engine
       stats_hash = {
diff --git a/test/performance/suites/agent_module.rb b/test/performance/suites/agent_module.rb
index 13e51dab2b..c60f8e6553 100644
--- a/test/performance/suites/agent_module.rb
+++ b/test/performance/suites/agent_module.rb
@@ -13,6 +13,13 @@ def test_increment_metric_by_1
     end
   end
 
+  def test_increment_metric
+    measure do
+      NewRelic::Agent.record_metric_once(METRIC)
+      NewRelic::Agent.record_metric_once(METRIC)
+    end
+  end
+
   def test_increment_metric_by_more_than_1
     measure do
       NewRelic::Agent.increment_metric(METRIC, 2)
Repository: fnando/browser (Ruby)

Issue:
`browser.safari?` should not return true for an Alipay UA
```
2.6.5 :001 > browser = Browser.new("Mozilla/5.0 (Linux; U; Android 4.2.1; zh-cn; HUAWEI G610-T00 Build/HuaweiG610-T00) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 AlipayDefined(nt:WIFI,ws:360|640|1.5) AliApp(AP/9.0.1.073001) AlipayClient/9.0.1.073001 GCanvas/1.4.2.15")
 => #<Browser::Alipay:0x00007fb86d2b0fe8 @ua="Mozilla/5.0 (Linux; U; Android 4.2.1; zh-cn; HUAWEI G610-T00 Build/HuaweiG610-T00) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 AlipayDefined(nt:WIFI,ws:360|640|1.5) AliApp(AP/9.0.1.073001) AlipayClient/9.0.1.073001 GCanvas/1.4.2.15", @accept_language=[]>
2.6.5 :002 > browser.name
 => "Alipay"
2.6.5 :003 > browser.safari?
 => true
```


Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14826a78..b0178d2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@
 - Add Miui Browser detection
 - Add `Browser::Base#qq?`
 - Fix QQ detection
+- Fix Alipay detection
 
 ## 4.2.0
 
diff --git a/lib/browser/safari.rb b/lib/browser/safari.rb
index f200801b..51be1f88 100644
--- a/lib/browser/safari.rb
+++ b/lib/browser/safari.rb
@@ -31,6 +31,7 @@ def match?
         !sputnik? &&
         !maxthon? &&
         !qq? &&
+        !alipay? &&
         !google_search_app?
     end
   end


Test patch:
diff --git a/test/unit/alipay_test.rb b/test/unit/alipay_test.rb
index b57a77f6..adfaf5d6 100644
--- a/test/unit/alipay_test.rb
+++ b/test/unit/alipay_test.rb
@@ -10,6 +10,9 @@ class AlipayTest < Minitest::Test
     assert browser.alipay?
     assert_equal "Alipay", browser.name
     assert_equal "2.3.4", browser.full_version
+
+    refute browser.chrome?
+    refute browser.safari?
   end
 
   test "detects alipay Android" do
@@ -19,6 +22,9 @@ class AlipayTest < Minitest::Test
     assert browser.alipay?
     assert_equal "Alipay", browser.name
     assert_equal "9.0.1.073001", browser.full_version
+
+    refute browser.chrome?
+    refute browser.safari?
   end
 
   test "detects version by range" do