internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: litestar-org/litestar

Issue:
Docs:  Build errors
### Summary

```
/home/peter/PycharmProjects/litestar/litestar/plugins/base.py:docstring of litestar.plugins.base.InitPluginProtocol.on_app_init:5: ERROR: Error in "code-block" directive:
maximum 1 argument(s) allowed, 14 supplied.

.. code-block:: python
    from litestar import Litestar, get
    from litestar.di import Provide
    from litestar.plugins import InitPluginProtocol


    def get_name() -> str:
        return "world"


    @get("/my-path")
    def my_route_handler(name: str) -> dict[str, str]:
        return {"hello": name}


    class MyPlugin(InitPluginProtocol):
        def on_app_init(self, app_config: AppConfig) -> AppConfig:
            app_config.dependencies["name"] = Provide(get_name)
            app_config.route_handlers.append(my_route_handler)
            return app_config


    app = Litestar(plugins=[MyPlugin()])
```

And

```
/home/peter/PycharmProjects/litestar/docs/topics/deployment/manually-with-asgi-server.rst:2: WARNING: Title underline too short.

Manually with ASGI server
==========
```

<!-- POLAR PLEDGE BADGE START -->
---
> [!NOTE]  
> While we are open for sponsoring on [GitHub Sponsors](https://github.com/sponsors/litestar-org/) and 
> [OpenCollective](https://opencollective.com/litestar), we also utilize [Polar.sh](https://polar.sh/) to engage in pledge-based sponsorship.
>
> Check out all issues funded or available for funding [on our Polar.sh Litestar dashboard](https://polar.sh/litestar-org)
> * If you would like to see an issue prioritized, make a pledge towards it!
> * We receive the pledge once the issue is completed & verified
> * This, along with engagement in the community, helps us know which features are a priority to our users.

<a href="https://polar.sh/litestar-org/litestar/issues/2680">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/litestar-org/litestar/issues/2680/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/litestar-org/litestar/issues/2680/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->



Discussion:

Resolving patch:
diff --git a/litestar/plugins/base.py b/litestar/plugins/base.py
--- a/litestar/plugins/base.py
+++ b/litestar/plugins/base.py
@@ -33,6 +33,7 @@ def on_app_init(self, app_config: AppConfig) -> AppConfig:
 
         Examples:
             .. code-block:: python
+
                 from litestar import Litestar, get
                 from litestar.di import Provide
                 from litestar.plugins import InitPluginProtocol


Test patch:
Repository: larq/larq

Issue:
tf.sign(0) = 0



Discussion:

Resolving patch:
diff --git a/xquant/quantizers.py b/xquant/quantizers.py
--- a/xquant/quantizers.py
+++ b/xquant/quantizers.py
@@ -2,12 +2,22 @@
 from xquant import utils
 
 
+def sign(x):
+    """A sign function that will never be zero"""
+    return tf.sign(tf.sign(x) + 1e-10)
+
+
 @utils.register_keras_custom_object
 @tf.custom_gradient
 def ste_sign(x):
     r"""
     Sign binarization function.
-    \\[q(x) = \mathrm{Sign}(x)\\]
+    \\[
+    q(x) = \begin{cases}
+      -1 & x < 0 \\\
+      1 & x \geq 0
+   \end{cases}
+   \\]
 
     The gradient is estimated using the Straight-Through Estimator.
     \\[\frac{\partial q(x)}{\partial x} = x\\]
@@ -26,7 +36,7 @@ def ste_sign(x):
     def grad(dy):
         return dy
 
-    return tf.sign(x), grad
+    return sign(x), grad
 
 
 @utils.register_keras_custom_object
@@ -34,7 +44,12 @@ def grad(dy):
 def approx_sign(x):
     r"""
     Sign binarization function.
-    \\[q(x) = \mathrm{Sign}(x)\\]
+    \\[
+    q(x) = \begin{cases}
+      -1 & x < 0 \\\
+      1 & x \geq 0
+   \end{cases}
+   \\]
 
     The gradient is estimated using the ApproxSign method.
     \\[\frac{\partial q(x)}{\partial x} = (2 - 2 \left|x\right|))\\]
@@ -54,7 +69,7 @@ def approx_sign(x):
     def grad(dy):
         return (1 - tf.abs(x)) * 2 * dy
 
-    return tf.sign(x), grad
+    return sign(x), grad
 
 
 def serialize(initializer):


Test patch:
Repository: larq/larq

Issue:
Add test coverage report to Azure Pipelines
https://docs.microsoft.com/en-us/azure/devops/pipelines/languages/python?view=azure-devops#test-with-pytest-and-collect-coverage-metrics-with-pytest-cov


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -21,7 +21,7 @@ def readme():
     extras_require={
         "tensorflow": ["tensorflow>=1.13.1"],
         "tensorflow_gpu": ["tensorflow-gpu>=1.13.1"],
-        "test": ["absl-py>=0.7.0", "pytest>=4.3.1"],
+        "test": ["absl-py>=0.7.0", "pytest>=4.3.1", "pytest-cov>=2.6.1"],
         "docs": [
             "pydoc-markdown@https://github.com/lgeiger/pydoc-markdown/archive/master.zip",
             "mkdocs-material>=4.1.0",


Test patch:
Repository: larq/larq

Issue:
Add docs on how to define your own quantizer



Discussion:

Resolving patch:
diff --git a/larq/quantizers.py b/larq/quantizers.py
--- a/larq/quantizers.py
+++ b/larq/quantizers.py
@@ -64,7 +64,7 @@ def ste_sign(x):
 @utils.register_keras_custom_object
 def magnitude_aware_sign(x):
     r"""
-    Magnitude-aware sign for birealnet.
+    Magnitude-aware sign for Bi-Real Net.
 
 
     # Arguments


Test patch:
Repository: larq/larq

Issue:
Docs: Add links to source code
This is really handy if people want to understand what's going on behind the scenes or want to implement more advanced stuff


Discussion:

Resolving patch:
diff --git a/generate_api_docs.py b/generate_api_docs.py
--- a/generate_api_docs.py
+++ b/generate_api_docs.py
@@ -1,5 +1,6 @@
 """https://github.com/NiklasRosenstein/pydoc-markdown/blob/master/pydocmd/__main__.py"""
 
+import inspect
 import os
 import sys
 import yaml
@@ -10,6 +11,23 @@
 from pydocmd.preprocessor import Preprocessor
 
 
+def callable_to_source_link(obj, scope):
+    path = scope.__file__.lstrip(".")
+    source = inspect.getsourcelines(obj)
+    line = source[-1] + 1 if source[0][0].startswith("@") else source[-1]
+    link = f"https://github.com/plumerai/larq/blob/master{path}#L{line}"
+    return f'<a class="headerlink code-link" style="float:right;" href="{link}" title="Source Code"></a>'
+
+
+class PythonLoaderWithSource(PythonLoader):
+    def load_section(self, section):
+        super().load_section(section)
+        obj = section.loader_context["obj"]
+        if callable(obj):
+            scope = section.loader_context["scope"]
+            section.title += callable_to_source_link(obj, scope)
+
+
 with open("apidocs.yml", "r") as stream:
     api_structure = yaml.safe_load(stream)
 
@@ -54,7 +72,7 @@ def create_sections(name, level):
         doc = index.new_document(fname)
         add_sections(doc, object_names)
 
-loader = PythonLoader({})
+loader = PythonLoaderWithSource({})
 preproc = Preprocessor({})
 
 preproc.link_lookup = {}


Test patch:
Repository: larq/larq

Issue:
Document how to use a quantizer as an activation function
`tf.keras.layers.Activation("ste_sign")`


Discussion:

Resolving patch:
diff --git a/larq/quantizers.py b/larq/quantizers.py
--- a/larq/quantizers.py
+++ b/larq/quantizers.py
@@ -1,5 +1,39 @@
 """A Quantizer defines the way of transforming a full precision input to a
-quantized output and the pseudo-gradient method used for the backwards pass."""
+quantized output and the pseudo-gradient method used for the backwards pass.
+
+Quantizers can either be used through quantizer arguments that are supported
+for Larq layers, such as `input_quantizer` and `kernel_quantizer`; or they
+can be used similar to activations, i.e. either through an `Activation` layer,
+or through the `activation` argument supported by all forward layer:
+
+```python
+import tensorflow as tf
+import larq as lq
+...
+x = lq.layers.QuantDense(64, activation=None)(x)
+x = lq.layers.QuantDense(64, input_quantizer="ste_sign")(x)
+```
+
+is equivalent to:
+
+```python
+x = lq.layers.QuantDense(64)(x)
+x = tf.keras.layers.Activation("ste_sign")(x)
+x = lq.layers.QuantDense(64)(x)
+```
+
+as well as:
+
+```python
+x = lq.layers.QuantDense(64, activation="ste_sign")(x)
+x = lq.layers.QuantDense(64)(x)
+```
+
+We highly recommend using the first of these formulations: for the
+other two formulations, intermediate layers - like batch normalization or
+average pooling - and shortcut connections may result in non-binary input
+to the convolutions.
+"""
 
 import tensorflow as tf
 from larq import utils, math


Test patch:
Repository: larq/larq

Issue:
Change default hyperparameters of Bop
The default hyperparameters for Bop are not really optimal (i.e. gamma is probably too high for most task): `Bop(threshold=1e-07, gamma=0.01, name='Bop', **kwargs)`

For example in our [paper](https://papers.nips.cc/paper/8971-latent-weights-do-not-exist-rethinking-binarized-neural-network-optimization.pdf) we used a gamma decayed from 1e-4 to 1e-6 and a threshold of 1e-8 for the ImageNet experiments.

I think we should update the default parameters to a more sensible choice. @MariaHeuss What do you think?


Discussion:
Yes, I agree that we should change the default. The values that you are mentioning are working well for a variety of models, although sometimes letting gamma start at 3e-4 works even better. I would set the threshold to 1e-8 and gamma to 1e-4 by default. I can make a PR later. 

Resolving patch:
diff --git a/larq/optimizers.py b/larq/optimizers.py
--- a/larq/optimizers.py
+++ b/larq/optimizers.py
@@ -238,7 +238,7 @@ class Bop(tf.keras.optimizers.Optimizer):
     - [Latent Weights Do Not Exist: Rethinking Binarized Neural Network Optimization](https://papers.nips.cc/paper/8971-latent-weights-do-not-exist-rethinking-binarized-neural-network-optimization)
     """
 
-    def __init__(self, threshold=1e-7, gamma=1e-2, name="Bop", **kwargs):
+    def __init__(self, threshold=1e-8, gamma=1e-4, name="Bop", **kwargs):
         super().__init__(name=name, **kwargs)
 
         self._set_hyper("threshold", threshold)


Test patch:
Repository: larq/larq

Issue:
CaseOptimizer should throw if optimizer matches no variable
### Feature motivation
We are changing the default behaviour of Bop in #442. If users are not careful this could lead to hard to debug errors when no variable matches any optimizer.

### Feature description
We should throw if one optimizer in used by `CaseOptimizer` doesn't receive any variables.

### Feature implementation
We should throw if any of the [`len(opt_grads_and_vars) == 0`](https://github.com/larq/larq/blob/c44ed976812edc2cc7d60c98155513942fc3af98/larq/optimizers.py#L140).


Discussion:

Resolving patch:
diff --git a/larq/optimizers.py b/larq/optimizers.py
--- a/larq/optimizers.py
+++ b/larq/optimizers.py
@@ -210,6 +210,13 @@ def _compute_var_opt_mapping(self, grads_and_vars):
                         f"No `default_optimizer` provided to train variable `{var}`."
                     )
 
+        # Make sure that each optimizer touches at least one variable
+        for optimizer_index, (_, optimizer) in enumerate(self.pred_opt_pairs):
+            if optimizer_index not in self.var_opt_mapping.values():
+                raise ValueError(
+                    f"Optimizer `{optimizer}` did not claim any variables."
+                )
+
 
 @utils.register_keras_custom_object
 class Bop(tf.keras.optimizers.Optimizer):


Test patch:
diff --git a/larq/optimizers_test.py b/larq/optimizers_test.py
--- a/larq/optimizers_test.py
+++ b/larq/optimizers_test.py
@@ -82,7 +82,40 @@ def test_overlapping_predicates(self):
     def test_missing_default(self):
         with pytest.warns(Warning):
             naughty_case_opt = lq.optimizers.CaseOptimizer(
-                (lambda var: False, lq.optimizers.Bop())
+                (lq.optimizers.Bop.is_binary_variable, lq.optimizers.Bop()),
+            )
+
+            # Simple MNIST model
+            mnist = tf.keras.datasets.mnist
+            (train_images, train_labels), _ = mnist.load_data()
+            model = tf.keras.Sequential(
+                [
+                    tf.keras.layers.Flatten(input_shape=(28, 28)),
+                    lq.layers.QuantDense(
+                        64,
+                        input_quantizer="ste_sign",
+                        kernel_quantizer=lq.quantizers.NoOpQuantizer(precision=1),
+                        activation="relu",
+                    ),
+                    tf.keras.layers.Dense(10, activation="softmax"),
+                ]
+            )
+            model.compile(
+                loss="sparse_categorical_crossentropy",
+                optimizer=naughty_case_opt,
+                metrics=["acc"],
+            )
+
+            # Should raise on first call to apply_gradients()
+            model.fit(train_images[:1], train_labels[:1], epochs=1)
+
+    def test_wrong_predicate(self):
+        """Make sure we throw when an optimizer does not claim variables."""
+
+        with pytest.raises(ValueError):
+            naughty_case_opt = lq.optimizers.CaseOptimizer(
+                (lambda var: False, lq.optimizers.Bop()),
+                default_optimizer=tf.keras.optimizers.Adam(0.01),
             )
 
             # Simple MNIST model
Repository: larq/larq

Issue:
__version__
### Feature motivation
Is there a way to dynamically poll the version of larq (or lce or larq-zoo for that matter)?
If not, could it be done using `__version__` as usual for standard library modules?

### Feature description
```
import larq
print(larq.__version__)
```


Discussion:
Currently we don't have a `__version__` identifier in larq, but I agree that it would be good to add since many other Python packages adhere to this convention as well.

Would you like to send a PR to fix this? Probably the first solution mentioned in https://packaging.python.org/guides/single-sourcing-package-version/ is the easiest to maintain, but I'm not sure what the general best practices here are.

In the meantime you can retrieve the version using:
```python
from importlib import metadata;
print(metadata.version("larq"))
```


Resolving patch:
diff --git a/larq/__init__.py b/larq/__init__.py
--- a/larq/__init__.py
+++ b/larq/__init__.py
@@ -12,6 +12,14 @@
     utils,
 )
 
+try:
+    from importlib import metadata  # type: ignore
+except ImportError:
+    # Running on pre-3.8 Python; use importlib-metadata package
+    import importlib_metadata as metadata  # type: ignore
+
+__version__ = metadata.version("larq")
+
 __all__ = [
     "layers",
     "activations",
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -22,6 +22,7 @@ def readme():
         "numpy >= 1.15.4, < 2.0",
         "terminaltables>=3.1.0",
         "dataclasses ; python_version<'3.7'",
+        "importlib-metadata ~= 2.0 ; python_version<'3.8'",
     ],
     extras_require={
         "tensorflow": ["tensorflow>=1.14.0"],


Test patch:
diff --git a/larq/version_test.py b/larq/version_test.py
new file mode 100644
--- /dev/null
+++ b/larq/version_test.py
@@ -0,0 +1,5 @@
+import larq
+
+
+def test_version():
+    assert hasattr(larq, "__version__") and "." in larq.__version__
Repository: larq/larq

Issue:
build() call not forwarded via base class
My use case: I develop a custom quantizer class, which derives from *larq.quantizers.BaseQuantizer* and which is then used like any other pre-defined quantizer. The custom quantizer defines a *build()* method.

Inside [BaseQuantizer.build](https://github.com/larq/larq/blob/094eaf1cca5017cdc643bf68bbb1301ab3f1af0f/larq/quantizers.py#L157) the method call to *build* is not forwarded via its base class *tf.keras.layers.Layer*.

In the [Tutorial about custom layers](https://www.tensorflow.org/guide/keras/custom_layers_and_models#best_practice_deferring_weight_creation_until_the_shape_of_the_inputs_is_known) this is also skipped. But when looking at [the build-method code in the base class](https://github.com/tensorflow/tensorflow/blob/85c8b2a817f95a3e979ecd1ed95bff1dc1335cff/tensorflow/python/keras/engine/base_layer.py#L448-L467), it is seen that the call should be forwarded, in order to set *self.built*, such that it is ensured, that the build triggered via *call* is only done once.

This is not an issue in most cases, as most users do not use explicit calls to *build* and use implicit builds triggered via *tf.keras.layers.Layer.call*, only. In my case, the quantizer is built explicitly before using *call* the first time and *call* tries to build the layer again, which then fails, eventhough I use
```python
super().build(shape)
```
in my custom *build()* to forward the call into larq. If the build call would be forward in larq, too, the *self.built* attribute would be set during the first (explicit) *build* call and the second (implicit) *build* call triggered by *tf.keras.layers.Layer.call* would be skipped.

Thank you for reading this!


Discussion:

Resolving patch:
diff --git a/larq/quantizers.py b/larq/quantizers.py
--- a/larq/quantizers.py
+++ b/larq/quantizers.py
@@ -157,6 +157,7 @@ def __init__(self, *args, metrics=None, **kwargs):
     def build(self, input_shape):
         if self._custom_metrics and "flip_ratio" in self._custom_metrics:
             self.flip_ratio = lq_metrics.FlipRatio(name=f"flip_ratio/{self.name}")
+        super().build(input_shape)
 
     def call(self, inputs):
         if hasattr(self, "flip_ratio"):


Test patch:
Repository: ycm-core/ycmd

Issue:
Tern completer: Tern server crashes on moderate sized files
## Problem

On moderate to large sized projects (such as Tern itself), the Tern server is quitting, and `:YcmDebugInfo` reports the Tern server crashed. Users get no completions/etc. until issuing `:YcmCompleter StartServer`. The Tern server may then crash again.
## Cause

ycmd's Tern completer uses a (conservative) 500ms timeout for requests to the Tern server. The Tern docs indicate this should return a HTTP error when time-out is hit, but it does not. Instead the server crashes. See Tern issue: https://github.com/ternjs/tern/issues/702
## Requirement

Ideally, get a fix upstream in Tern and update the submodule. Otherwise, if the linked Tern issue is not resolved, ycmd tern completer needs to handle this error, potentially including any or all of the following:
- removing or increasing the timeout sent to Tern server 
- using a client-side session timeout instead
- automatically restarting the crashed server



Discussion:

Resolving patch:
diff --git a/ycmd/completers/javascript/tern_completer.py b/ycmd/completers/javascript/tern_completer.py
--- a/ycmd/completers/javascript/tern_completer.py
+++ b/ycmd/completers/javascript/tern_completer.py
@@ -254,7 +254,7 @@ def _PostRequest( self, request, request_data ):
     the files are being updated.
 
     The request block should contain the optional query block only. The file
-    data and timeout are are added automatically."""
+    data are added automatically."""
 
     if not self._ServerIsRunning():
       raise ValueError( 'Not connected to server' )
@@ -271,7 +271,6 @@ def MakeIncompleteFile( name, file_data ):
     full_request = {
       'files': [ MakeIncompleteFile( x, file_data[ x ] )
                  for x in file_data.keys() ],
-      'timeout': 500,
     }
     full_request.update( request )
 
@@ -292,7 +291,7 @@ def _GetResponse( self, query, request_data ):
     just updating file data in which case _PostRequest should be used directly.
 
     The query block should contain the type and any parameters. The files,
-    position, timeout etc. are added automatically."""
+    position, etc. are added automatically."""
 
     def MakeTernLocation( request_data ):
       return {


Test patch:
Repository: ycm-core/ycmd

Issue:
LookupError: unknown encoding on Mac with Python 2
With latest `ycmd` I get the following error on Mac with Py2:

``` python
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/Users/peter/src/ycmd/ycmd/__main__.py", line 181, in <module>
    Main()
  File "/Users/peter/src/ycmd/ycmd/__main__.py", line 151, in Main
    options, hmac_secret = SetupOptions( args.options_file )
  File "/Users/peter/src/ycmd/ycmd/__main__.py", line 127, in SetupOptions
    options = user_options_store.DefaultOptions()
  File "/Users/peter/src/ycmd/ycmd/../ycmd/user_options_store.py", line 52, in DefaultOptions
    with open( settings_path ) as f:
LookupError: unknown encoding: 

Process ycmd-server exited abnormally with code 1
```

I have a python 2 installation from homebrew



Discussion:

Resolving patch:
diff --git a/ycmd/user_options_store.py b/ycmd/user_options_store.py
--- a/ycmd/user_options_store.py
+++ b/ycmd/user_options_store.py
@@ -27,8 +27,11 @@
 import os
 from frozendict import frozendict
 
+from ycmd.utils import ReadFile
+
 _USER_OPTIONS = {}
 
+
 def SetAll( new_options ):
   global _USER_OPTIONS
   _USER_OPTIONS = frozendict( new_options )
@@ -49,8 +52,6 @@ def LoadDefaults():
 def DefaultOptions():
   settings_path = os.path.join(
       os.path.dirname( os.path.abspath( __file__ ) ), 'default_settings.json' )
-  with open( settings_path ) as f:
-    options = json.loads( f.read() )
-    options.pop( 'hmac_secret', None )
-    return options
-
+  options = json.loads( ReadFile( settings_path ) )
+  options.pop( 'hmac_secret', None )
+  return options


Test patch: