internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: mirumee/ariadne

Issue:
Remove superfluous schema validation
It turns out that  `validate_schema` called in https://github.com/mirumee/ariadne/blob/master/ariadne/executable_schema.py#L26 is not needed here. 
In the other hand, `assert_validate_schema` is called here: https://github.com/mirumee/ariadne/blob/master/ariadne/executable_schema.py#L40 which is sufficient. 

Fixes #523 


Discussion:

Resolving patch:
diff --git a/ariadne/executable_schema.py b/ariadne/executable_schema.py
--- a/ariadne/executable_schema.py
+++ b/ariadne/executable_schema.py
@@ -5,7 +5,6 @@
     assert_valid_schema,
     build_ast_schema,
     parse,
-    validate_schema,
 )
 
 from .enums import set_default_enum_values_on_schema
@@ -23,7 +22,6 @@ def make_executable_schema(
 
     ast_document = parse(type_defs)
     schema = build_ast_schema(ast_document)
-    validate_schema(schema)
 
     for bindable in bindables:
         if isinstance(bindable, list):


Test patch:
Repository: mirumee/ariadne

Issue:
Support Starlette 0.18.0
Was just released: https://github.com/encode/starlette/releases/tag/0.18.0
and currently the dependency is pinned at `<0.18.0`.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -33,7 +33,7 @@
     include_package_data=True,
     install_requires=[
         "graphql-core>=3.2.0,<3.3",
-        "starlette<0.18",
+        "starlette<0.19",
         "typing_extensions>=3.6.0",
     ],
     extras_require={"asgi-file-uploads": ["python-multipart>=0.0.5"]},


Test patch:
Repository: mirumee/ariadne

Issue:
Use `execute_sync` in `graphql_sync`
`graphql_sync` should use `execute_sync` instead of `execute`.

I run my code in a synchronous context, but a resolver was identified as asynchronous due to the fact that GraphQL core does a simple `hasattr(value, "__await__")` check instead of using `inspect.isawaitable`. This caused a false positive.

However, when using `graphql_sync` I expect that this check does not even happen. Consider using [`execute_sync`](https://github.com/graphql-python/graphql-core/blob/27768d3faac5bb8ebb2c6a151a7192b7fa498f2f/src/graphql/execution/execute.py#L1061) instead.


Discussion:
Thanks for reporting this, would you like to open an PR with the fix?

Resolving patch:
diff --git a/ariadne/graphql.py b/ariadne/graphql.py
--- a/ariadne/graphql.py
+++ b/ariadne/graphql.py
@@ -20,6 +20,7 @@
     GraphQLSchema,
     TypeInfo,
     execute,
+    execute_sync,
     parse,
     subscribe as _subscribe,
 )
@@ -179,7 +180,7 @@ def graphql_sync(
                         "in synchronous query executor."
                     )
 
-            result = execute(
+            result = execute_sync(
                 schema,
                 document,
                 root_value=root_value,


Test patch:
Repository: mirumee/ariadne

Issue:
Update Starlette dependency to 0.19
Starlette 0.19 has been released, we should bump Ariadne's version to it before releasing 0.15 


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -33,7 +33,7 @@
     include_package_data=True,
     install_requires=[
         "graphql-core>=3.2.0,<3.3",
-        "starlette<0.19",
+        "starlette>0.17<0.20",
         "typing_extensions>=3.6.0",
     ],
     extras_require={"asgi-file-uploads": ["python-multipart>=0.0.5"]},


Test patch:
Repository: mirumee/ariadne

Issue:
Incorrect typing for values on EnumType.__init__()
Ariadne 0.18.0 has updated the `EnumType` class in a way that causes the `values` argument of `__init__()` to become typed, but the typing is incorrect:

```
    def __init__(
        self, name: str, values: Union[Dict[str, Any], enum.Enum, enum.IntEnum]
    ) -> None:
```

should be:

```
    def __init__(
        self, name: str, values: Union[Dict[str, Any], Type[enum.Enum], Type[enum.IntEnum]]
    ) -> None:
```


Discussion:
Hey, thanks. Pull request is welcome

Resolving patch:
diff --git a/ariadne/enums.py b/ariadne/enums.py
--- a/ariadne/enums.py
+++ b/ariadne/enums.py
@@ -7,6 +7,7 @@
     Mapping,
     Optional,
     Tuple,
+    Type,
     TypeVar,
     Union,
     cast,
@@ -87,7 +88,9 @@ class EnumType(SchemaBindable):
     """
 
     def __init__(
-        self, name: str, values: Union[Dict[str, Any], enum.Enum, enum.IntEnum]
+        self,
+        name: str,
+        values: Union[Dict[str, Any], Type[enum.Enum], Type[enum.IntEnum]],
     ) -> None:
         """Initializes the `EnumType` with `name` and `values` mapping.
 


Test patch:
diff --git a/tests_mypy/enums.py b/tests_mypy/enums.py
new file mode 100644
--- /dev/null
+++ b/tests_mypy/enums.py
@@ -0,0 +1,18 @@
+from enum import Enum, IntEnum
+
+from ariadne import EnumType
+
+
+class TestEnum(Enum):
+    FOO = "foo"
+    BAR = "bar"
+
+
+class TestIntEnum(IntEnum):
+    FOO = 0
+    BAR = 1
+
+
+test_dict_enum_type = EnumType("TestDictEnum", {"FOO": "foo", "BAR": "bar"})
+test_enum_type = EnumType("TestEnum", TestEnum)
+test_int_enum_type = EnumType("TestIntEnumType", TestIntEnum)
Repository: mirumee/ariadne

Issue:
Python 3.12 has deprecation warnings
Ariadne produces few warnings when ran on Py3.12. Most of those are out of our hands as they are coming from dependencies, but there are some we should fix:

```

  /ariadne/ariadne/contrib/tracing/apollotracing.py:36: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
    self.start_date = datetime.utcnow()

  /ariadne/ariadne/contrib/tracing/apollotracing.py:96: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
    "end": datetime.utcnow(),
```


Discussion:

Resolving patch:
diff --git a/ariadne/contrib/tracing/apollotracing.py b/ariadne/contrib/tracing/apollotracing.py
--- a/ariadne/contrib/tracing/apollotracing.py
+++ b/ariadne/contrib/tracing/apollotracing.py
@@ -1,4 +1,3 @@
-from datetime import datetime
 from inspect import iscoroutinefunction
 from typing import Any, List, Optional, cast
 
@@ -20,6 +19,19 @@ def perf_counter_ns() -> int:
         return int(perf_counter() * NS_IN_SECOND)
 
 
+try:
+    from datetime import UTC, datetime  # type: ignore[attr-defined]
+
+    def utc_now():
+        return datetime.now(UTC)
+
+except ImportError:
+    from datetime import datetime
+
+    def utc_now():
+        return datetime.utcnow()
+
+
 TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
 
 
@@ -33,7 +45,7 @@ def __init__(self, trace_default_resolver: bool = False) -> None:
         self._totals = None
 
     def request_started(self, context: ContextValue):
-        self.start_date = datetime.utcnow()
+        self.start_date = utc_now()
         self.start_timestamp = perf_counter_ns()
 
     def resolve(self, next_: Resolver, obj: Any, info: GraphQLResolveInfo, **kwargs):
@@ -93,7 +105,7 @@ def get_totals(self):
     def _get_totals(self):
         return {
             "start": self.start_date,
-            "end": datetime.utcnow(),
+            "end": utc_now(),
             "duration": perf_counter_ns() - self.start_timestamp,
             "resolvers": self.resolvers,
         }


Test patch:
Repository: elastic/elasticsearch-py

Issue:
max_retries is ignored when using thrift
connection/thrift.py does not catch socket.error in perform_request which cause max_retries to be ignored in the transport.

One can argue that this socket.error exception should be translated into a TException in the offical thrift-library but I think it's better to have it included here aswell.



Discussion:

Resolving patch:
diff --git a/elasticsearch/connection/thrift.py b/elasticsearch/connection/thrift.py
--- a/elasticsearch/connection/thrift.py
+++ b/elasticsearch/connection/thrift.py
@@ -1,5 +1,6 @@
 from __future__ import absolute_import
 from socket import timeout as SocketTimeout
+from socket import error as SocketError
 import time
 import logging
 
@@ -69,7 +70,7 @@ def perform_request(self, method, url, params=None, body=None, timeout=None, ign
         except SocketTimeout as e:
             self.log_request_fail(method, url, body, time.time() - start, exception=e)
             raise ConnectionTimeout('TIMEOUT', str(e), e)
-        except (TException, SocketTimeout) as e:
+        except (TException, SocketError) as e:
             self.log_request_fail(method, url, body, time.time() - start, exception=e)
             if tclient:
                 try:


Test patch:
Repository: elastic/elasticsearch-py

Issue:
Support for custom authentication objects for requests module
Hi,

Several transport classes are available, one of them is "requests".
Requests supports basic-authentication but far more than that ([0](http://docs.python-requests.org/en/latest/user/advanced/#custom-authentication)). In order to support this a few lines would need to be changed to allow for providing an authentication object ([1](https://github.com/elastic/elasticsearch-py/compare/master...sim0nx:requests_custom_authentication)).

I have the code ready ([1](https://github.com/elastic/elasticsearch-py/compare/master...sim0nx:requests_custom_authentication)) for this and am actively using it.

Would you be willing to accept this contribution ?



Discussion:
Hi, yes, this makes sense, just make sure it will work on python 3 please.

Thanks!

Hi,

Thanks, good point. I implemented a check for the python version and test for either basestring (py2) or str (py3).

Does that look OK ?

We have a dependency on six, could you please just use `isinstance(http_auth, six.string_types)`? thanks!


Resolving patch:
diff --git a/elasticsearch/connection/http_requests.py b/elasticsearch/connection/http_requests.py
--- a/elasticsearch/connection/http_requests.py
+++ b/elasticsearch/connection/http_requests.py
@@ -1,3 +1,4 @@
+import six
 import time
 import warnings
 try:
@@ -32,8 +33,10 @@ def __init__(self, host='localhost', port=9200, http_auth=None,
         super(RequestsHttpConnection, self).__init__(host= host, port=port, **kwargs)
         self.session = requests.session()
         if http_auth is not None:
-            if not isinstance(http_auth, (tuple, list)):
-                http_auth = http_auth.split(':', 1)
+            if isinstance(http_auth, (tuple, list)):
+                http_auth = tuple(http_auth)
+            elif isinstance(http_auth, six.string_types):
+                http_auth = tuple(http_auth.split(':', 1))
             http_auth = tuple(http_auth)
             self.session.auth = http_auth
         self.base_url = 'http%s://%s:%d%s' % (


Test patch:
Repository: speechbrain/speechbrain

Issue:
Rename `logging.yaml`
Perhaps a better name could be used for this file to indicate that it does configuration of the logger, not actual logging.


Discussion:
Will the logger manage all the logging, including tensorboard? It would make sense to not split too much. 
Hmm, good question. I don't know the best way to integrate tensorboard logging.
I think it is pretty simple: https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html We can think of a simple flag: Yes or No. And a path for the logs (this is important, tensor board writes a LOT, and peoples might want to put the logs outside of an NFS). Then we just provide some very basic logs like losses + acc + Attention Weights, and peoples can then just add writer.add_* somewhere and this will automatically added


Resolving patch:
diff --git a/recipes/ASR_CTC/TIMIT/VGG2_BLSTM_MLP/experiment.py b/recipes/ASR_CTC/TIMIT/VGG2_BLSTM_MLP/experiment.py
--- a/recipes/ASR_CTC/TIMIT/VGG2_BLSTM_MLP/experiment.py
+++ b/recipes/ASR_CTC/TIMIT/VGG2_BLSTM_MLP/experiment.py
@@ -21,7 +21,7 @@
     experiment_directory=params.output_folder,
     params_to_save=params_file,
     overrides=overrides,
-    log_config="logging.yaml",
+    log_config="log-config.yaml",
 )
 
 
diff --git a/speechbrain/core.py b/speechbrain/core.py
--- a/speechbrain/core.py
+++ b/speechbrain/core.py
@@ -26,7 +26,7 @@ def create_experiment_directory(
     experiment_directory,
     params_to_save=None,
     overrides={},
-    log_config="logging.yaml",
+    log_config="log-config.yaml",
 ):
     """Create the output folder and relevant experimental files.
 
diff --git a/speechbrain/utils/logger.py b/speechbrain/utils/logger.py
--- a/speechbrain/utils/logger.py
+++ b/speechbrain/utils/logger.py
@@ -10,7 +10,7 @@
 
 
 def setup_logging(
-    config_path="logging.yaml", overrides={}, default_level=logging.INFO,
+    config_path="log-config.yaml", overrides={}, default_level=logging.INFO,
 ):
     """Setup logging configuration
 


Test patch:
Repository: speechbrain/speechbrain

Issue:
Do not lint generated YAML files
Currently if an experiment has been run, the yaml linter chokes on generated yaml files

- [ ] Fix generated params.yaml
- [ ] Fix generated ckpt.yaml

This can be fixed by adding `# yamllint disable` at the top of these files.


Discussion:

Resolving patch:
diff --git a/speechbrain/core.py b/speechbrain/core.py
--- a/speechbrain/core.py
+++ b/speechbrain/core.py
@@ -12,6 +12,7 @@
 import inspect
 import argparse
 import subprocess
+from datetime import date
 from tqdm.contrib import tzip
 from speechbrain.yaml import resolve_references
 from speechbrain.utils.logger import setup_logging
@@ -54,6 +55,9 @@ def create_experiment_directory(
         with open(params_to_save) as f:
             resolved_yaml = resolve_references(f, overrides)
         with open(params_filename, "w") as w:
+            print("# Generated %s from:" % date.today(), file=w)
+            print("# %s" % os.path.abspath(params_to_save), file=w)
+            print("# yamllint disable", file=w)
             shutil.copyfileobj(resolved_yaml, w)
 
     # Copy executing file to output directory
diff --git a/speechbrain/utils/checkpoints.py b/speechbrain/utils/checkpoints.py
--- a/speechbrain/utils/checkpoints.py
+++ b/speechbrain/utils/checkpoints.py
@@ -836,5 +836,6 @@ def _save_checkpoint_metafile(
         meta = {"unixtime": time.time(), "end-of-epoch": end_of_epoch}
         meta.update(meta_to_include)
         with open(fpath, "w") as fo:
+            fo.write("# yamllint disable\n")
             fo.write(yaml.dump(meta))
         return meta


Test patch:
Repository: speechbrain/speechbrain

Issue:
Load YAML overrides using `load_extended_yaml`
There are some things that are currently not possible to override due to the command-line overrides being loaded using `yaml.safe_load()` rather than `load_extended_yaml()`. For example:

```
activation: !torch.nn.LeakyReLU
```

may be nice to override with a different activation. This can be overridden in python just fine, but not from the command line, e.g.

```
python experiment.py params.yaml --yaml_overrides="{activation: !torch.nn.ReLU}"
```


Discussion:
One potential hangup I see with this is that adding the ability to make references (e.g. `!ref <abcd>`) to the original (non-overriding) yaml would be quite difficult. A solution could be to disallow references, or to just allow references without worrying about whether overriding the original yaml is possible.

Resolving patch:
diff --git a/speechbrain/core.py b/speechbrain/core.py
--- a/speechbrain/core.py
+++ b/speechbrain/core.py
@@ -5,7 +5,6 @@
 
 import os
 import sys
-import yaml
 import torch
 import shutil
 import logging
@@ -13,11 +12,11 @@
 import argparse
 import subprocess
 from tqdm.contrib import tzip
-from speechbrain.yaml import resolve_references
 from speechbrain.utils.logger import setup_logging
 from speechbrain.utils.epoch_loop import EpochCounter
 from speechbrain.utils.checkpoints import ckpt_recency
 from speechbrain.utils.data_utils import recursive_update
+from speechbrain.yaml import resolve_references, load_extended_yaml
 
 logger = logging.getLogger(__name__)
 DEFAULT_LOG_CONFIG = os.path.dirname(os.path.abspath(__file__))
@@ -168,10 +167,10 @@ def parse_overrides(override_string):
     """
     preview = {}
     if override_string:
-        preview = yaml.safe_load(override_string)
+        preview = load_extended_yaml(override_string)
 
     overrides = {}
-    for arg, val in preview.items():
+    for arg, val in preview.__dict__.items():
         if "." in arg:
             nest(overrides, arg.split("."), val)
         else:


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -23,8 +23,8 @@ def test_parse_arguments():
 def test_parse_overrides():
     from speechbrain.core import parse_overrides
 
-    overrides = parse_overrides("{model.arg1: 1, model.arg1: 2}")
-    assert overrides == {"model": {"arg1": 2}}
+    overrides = parse_overrides("{model.arg1: 1, model.arg2: 2}")
+    assert overrides == {"model": {"arg1": 1, "arg2": 2}}
 
 
 def test_brain():
Repository: speechbrain/speechbrain

Issue:
Learning rate printing
Now it will only print 0.00. Maybe we should print it with scientific notation.


Discussion:

Resolving patch:
diff --git a/speechbrain/utils/train_logger.py b/speechbrain/utils/train_logger.py
--- a/speechbrain/utils/train_logger.py
+++ b/speechbrain/utils/train_logger.py
@@ -54,8 +54,10 @@ def __init__(self, save_file, summary_fns):
 
     def _item_to_string(self, key, value, dataset=None):
         """Convert one item to string, handling floats"""
-        if isinstance(value, float):
+        if isinstance(value, float) and 0.01 < value < 100.0:
             value = f"{value:.2f}"
+        elif isinstance(value, float):
+            value = f"{value:.2e}"
         if dataset is not None:
             key = f"{dataset} {key}"
         return f"{key}: {value}"


Test patch:
Repository: speechbrain/speechbrain

Issue:
Replicability Issue
Every time I run the same experiment (e.,g minimal_examples/neural_networks/autoencoder) on the same machine I got slightly different results. Since we set up the seed, this shouldn't happen. 


Discussion:

Resolving patch:
diff --git a/recipes/TIMIT/ASR_CTC/experiment.py b/recipes/TIMIT/ASR_CTC/experiment.py
--- a/recipes/TIMIT/ASR_CTC/experiment.py
+++ b/recipes/TIMIT/ASR_CTC/experiment.py
@@ -1,7 +1,6 @@
 #!/usr/bin/env python3
 import os
 import sys
-import torch
 import speechbrain as sb
 import speechbrain.data_io.wer as wer_io
 import speechbrain.utils.edit_distance as edit_distance
@@ -18,8 +17,6 @@
 
 # Load hyperparameters file with command-line overrides
 params_file, overrides = sb.core.parse_arguments(sys.argv[1:])
-if "seed" in overrides:
-    torch.manual_seed(overrides["seed"])
 with open(params_file) as fin:
     params = sb.yaml.load_extended_yaml(fin, overrides)
 


Test patch:
Repository: speechbrain/speechbrain

Issue:
padding_mode not respected in Conv
The padding mode of "reflect" is used regardless of the value for argument `padding_mode` for `Conv` (which is especially surprising given the default is "zeros").


Discussion:
Yes, we definitely have to be consistent. As I posted in #64, apparently the current solution for padding gives the best performance...
Well the thing is that @mravanelli did a specific function for padding: _manage_padding. Any reason for not letting pytorch do it by itself so we can simply pass the correct argument? 
I believe that if we want to support having the same output size as input size ("same" option in TF etc.) we'd need to implement it ourselves, since PyTorch doesn't support it.
Yes, that's what we are doing when padding=True. In practice, the conv function has a parameter called "padding" that takes in input the number of elements to pad, but we have to compute the number of elements to pad by ourselves in manage_padding...
In practice, I implemented this functionality especially for HMM-DNN ASR where labels and predictions must have the same number of time steps..

Resolving patch:
diff --git a/speechbrain/nnet/CNN.py b/speechbrain/nnet/CNN.py
--- a/speechbrain/nnet/CNN.py
+++ b/speechbrain/nnet/CNN.py
@@ -95,7 +95,7 @@ def __init__(
         padding=True,
         groups=1,
         bias=True,
-        padding_mode="zeros",
+        padding_mode="reflect",
         sinc_conv=False,
         sample_rate=16000,
         min_low_hz=50,
@@ -210,7 +210,6 @@ def _init_conv1d(self, first_input):
             padding=0,
             groups=self.groups,
             bias=self.bias,
-            padding_mode=self.padding_mode,
         ).to(first_input.device)
 
     def _init_conv2d(self, first_input):
@@ -252,7 +251,6 @@ def _init_conv2d(self, first_input):
             dilation=self.dilation,
             groups=self.groups,
             bias=self.bias,
-            padding_mode=self.padding_mode,
         ).to(first_input.device)
 
     def _init_sinc_conv(self, first_input):
@@ -378,7 +376,7 @@ def _manage_padding(self, x, kernel_size, dilation, stride):
             padding = padding + padding_freq
 
         # Applying padding
-        x = nn.functional.pad(input=x, pad=tuple(padding), mode="reflect")
+        x = nn.functional.pad(x, tuple(padding), mode=self.padding_mode)
 
         return x
 


Test patch:
Repository: speechbrain/speechbrain

Issue:
Train Logger use average as the default summary function
Right now users have to specify a summary function for each statistic, however average is the function to use in the vast majority of cases (the exception is error rates). Why not make it default?


Discussion:
@Gastron what do you think?
Sounds good to me.

Resolving patch:
diff --git a/speechbrain/utils/train_logger.py b/speechbrain/utils/train_logger.py
--- a/speechbrain/utils/train_logger.py
+++ b/speechbrain/utils/train_logger.py
@@ -54,9 +54,9 @@ class FileTrainLogger(TrainLogger):
         from a training/validation pass and summarize it to a single scalar.
     """
 
-    def __init__(self, save_file, summary_fns):
+    def __init__(self, save_file, summary_fns=None):
         self.save_file = save_file
-        self.summary_fns = summary_fns
+        self.summary_fns = summary_fns or {}
 
     def _item_to_string(self, key, value, dataset=None):
         """Convert one item to string, handling floats"""
@@ -93,7 +93,10 @@ def log_stats(
                 continue
             summary = {}
             for stat, value_list in stats.items():
-                summary[stat] = self.summary_fns[stat](value_list)
+                if stat in self.summary_fns:
+                    summary[stat] = self.summary_fns[stat](value_list)
+                else:
+                    summary[stat] = summarize_average(value_list)
             string_summary += " - " + self._stats_to_string(summary, dataset)
 
         with open(self.save_file, "a") as fout:


Test patch: