internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: jazzband/django-oauth-toolkit

Issue:
AttributeError in OAuth2ExtraTokenMiddleware middleware when a swapped AccessToken is used.
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
When a custom `AccessToken` is used, the `OAuth2ExtraTokenMiddleware` raises an `AttributeError: Manager isn't available; 'oauth2_provider.AccessToken' has been swapped for ...`

**To Reproduce**
<!-- Steps to reproduce the behavior -->
Use a custom `OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL` and enable the `oauth2_provider.middleware.OAuth2ExtraTokenMiddleware`
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
No error to be raised.
**Version**
<!-- Version of django-oauth-toolkit -->

<!-- Have you tested with the latest version and/or master branch? -->
<!-- Replace '[ ]' with '[x]' to indicate that. -->
- [NA] I have tested with the latest published release and it's still a problem.
- [x] I have tested with the master branch and it's still a problem.

**Additional context**
<!-- Add any other context about the problem here. -->
A simple change is proposed in #1380



Discussion:

Resolving patch:
diff --git a/oauth2_provider/middleware.py b/oauth2_provider/middleware.py
--- a/oauth2_provider/middleware.py
+++ b/oauth2_provider/middleware.py
@@ -3,7 +3,7 @@
 from django.contrib.auth import authenticate
 from django.utils.cache import patch_vary_headers
 
-from oauth2_provider.models import AccessToken
+from oauth2_provider.models import get_access_token_model
 
 
 log = logging.getLogger(__name__)
@@ -53,6 +53,7 @@ def __call__(self, request):
         authheader = request.META.get("HTTP_AUTHORIZATION", "")
         if authheader.startswith("Bearer"):
             tokenstring = authheader.split()[1]
+            AccessToken = get_access_token_model()
             try:
                 token = AccessToken.objects.get(token=tokenstring)
                 request.access_token = token


Test patch:
Repository: OCA/server-tools

Issue:
[Bug] mass_editing - Search in ir.model.fields not working
I setup the mass_editing for res.partner then i go to:
Settings -> Technical -> Database Structure -> Fields
and go to the Filter with ('model_id','=',61) where 61 is the id of res.partner in res.model. By typ "res.partner" and select "Partner" from the suggestion.

Then i get the following error:
File "[..]/mass_editing/mass_editing.py", line 34, in search
    model_domain += [('model_id', 'in', map(int, domain[2][1:-1].split(',')))]
TypeError: 'int' object has no attribute '**getitem**'



Discussion:
His @OSguard, could you post more of the traceback?
I would like to know what code calls `search()` in this instance.

It sounds like search was called with an int in place of the `domain` parameter.

More info at https://bugs.launchpad.net/server-env-tools/+bug/1207671

thanks is the same bug. i should check with google next time first.

``` python
            if domain[0] == 'model_id' and domain[2]\
                    and type(domain[2]) != list:
                model_domain += [(
                    'model_id', 'in', map(int, domain[2][1:-1].split(',')))]
            else:
                model_domain.append(domain)
```

`type(domain[2]) != list` followed by `domain[2][1:-1]`
I guess it makes an assumption that `domain[2]` is a `str`, but in some cases, it's an `int`.

Is it possible that `domain[:3] == ('model_id', '=', some_int)`?
**EDIT**: just read the example and yes it is.

A saner way of checking would be to replace `and type(domain[2]) != list` by `and type(domain[2]) is str`

Damnit, sorry. I commited directly instead of a PR because I have write access...

There. Two PRs which should solve the issue, though I didn't test.


Resolving patch:
diff --git a/mass_editing/models/ir_model_fields.py b/mass_editing/models/ir_model_fields.py
--- a/mass_editing/models/ir_model_fields.py
+++ b/mass_editing/models/ir_model_fields.py
@@ -31,12 +31,14 @@ def search(
             count=False):
         model_domain = []
         for domain in args:
-            if domain[0] == 'model_id' and domain[2]\
-                    and type(domain[2]) != list:
-                model_domain += [(
-                    'model_id', 'in', map(int, domain[2][1:-1].split(',')))]
+            if (len(domain) > 2 and domain[0] == 'model_id'
+                    and isinstance(domain[2], basestring)):
+                model_domain += [
+                    ('model_id', 'in', map(int, domain[2][1:-1].split(',')))
+                ]
             else:
                 model_domain.append(domain)
         return super(IrModelFields, self).search(
             cr, uid, model_domain, offset=offset, limit=limit, order=order,
-            context=context, count=count)
+            context=context, count=count
+        )


Test patch:
Repository: OCA/server-tools

Issue:
[Bug] mass_editing - Search in ir.model.fields not working
I setup the mass_editing for res.partner then i go to:
Settings -> Technical -> Database Structure -> Fields
and go to the Filter with ('model_id','=',61) where 61 is the id of res.partner in res.model. By typ "res.partner" and select "Partner" from the suggestion.

Then i get the following error:
File "[..]/mass_editing/mass_editing.py", line 34, in search
    model_domain += [('model_id', 'in', map(int, domain[2][1:-1].split(',')))]
TypeError: 'int' object has no attribute '**getitem**'



Discussion:
His @OSguard, could you post more of the traceback?
I would like to know what code calls `search()` in this instance.

It sounds like search was called with an int in place of the `domain` parameter.

More info at https://bugs.launchpad.net/server-env-tools/+bug/1207671

thanks is the same bug. i should check with google next time first.

``` python
            if domain[0] == 'model_id' and domain[2]\
                    and type(domain[2]) != list:
                model_domain += [(
                    'model_id', 'in', map(int, domain[2][1:-1].split(',')))]
            else:
                model_domain.append(domain)
```

`type(domain[2]) != list` followed by `domain[2][1:-1]`
I guess it makes an assumption that `domain[2]` is a `str`, but in some cases, it's an `int`.

Is it possible that `domain[:3] == ('model_id', '=', some_int)`?
**EDIT**: just read the example and yes it is.

A saner way of checking would be to replace `and type(domain[2]) != list` by `and type(domain[2]) is str`

Damnit, sorry. I commited directly instead of a PR because I have write access...

There. Two PRs which should solve the issue, though I didn't test.


Resolving patch:
diff --git a/mass_editing/mass_editing.py b/mass_editing/mass_editing.py
--- a/mass_editing/mass_editing.py
+++ b/mass_editing/mass_editing.py
@@ -32,10 +32,11 @@ def search(
             count=False):
         model_domain = []
         for domain in args:
-            if domain[0] == 'model_id' and domain[2]\
-                    and type(domain[2]) != list:
-                model_domain += [(
-                    'model_id', 'in', map(int, domain[2][1:-1].split(',')))]
+            if (len(domain) > 2 and domain[0] == 'model_id'
+                    and isinstance(domain[2], basestring)):
+                model_domain += [
+                    ('model_id', 'in', map(int, domain[2][1:-1].split(',')))
+                ]
             else:
                 model_domain.append(domain)
         return super(ir_model_fields, self).search(


Test patch:
Repository: OCA/server-tools

Issue:
[7.0] [base_optional_quick_create] AttributeError: 'NoneType' object has no attribute 'name_create'
Error at starting before a migration if a model has been removed



Discussion:

Resolving patch:
diff --git a/base_optional_quick_create/model.py b/base_optional_quick_create/model.py
--- a/base_optional_quick_create/model.py
+++ b/base_optional_quick_create/model.py
@@ -45,7 +45,7 @@ def _register_hook(self, cr, ids=None):
             if model.avoid_quick_create:
                 model_name = model.model
                 model_obj = self.pool.get(model_name)
-                if not hasattr(model_obj, 'check_quick_create'):
+                if model_obj and not hasattr(model_obj, 'check_quick_create'):
                     model_obj.name_create = self._wrap_name_create(
                         model_obj.name_create,
                         model_name)


Test patch:
Repository: OCA/server-tools

Issue:
[7.0] [base_optional_quick_create] AttributeError: 'NoneType' object has no attribute 'name_create'
Error at starting before a migration if a model has been removed



Discussion:

Resolving patch:
diff --git a/base_optional_quick_create/model.py b/base_optional_quick_create/model.py
--- a/base_optional_quick_create/model.py
+++ b/base_optional_quick_create/model.py
@@ -44,7 +44,7 @@ def _register_hook(self, cr, ids=None):
             if model.avoid_quick_create:
                 model_name = model.model
                 model_obj = self.pool.get(model_name)
-                if not hasattr(model_obj, 'check_quick_create'):
+                if model_obj and not hasattr(model_obj, 'check_quick_create'):
                     model_obj.name_create = self._wrap_name_create(
                         model_obj.name_create, model_name)
                     model_obj.check_quick_create = True


Test patch:
Repository: OCA/server-tools

Issue:
Annoying logs while using the shell
I get interrupted while writing in the shell by the following logs:
openerp.addons.hw_escpos.controllers.main: ESC/POS Device Disconnected: Printer Not Found
openerp.addons.hw_escpos.controllers.main: disconnected : Printer Not Found



Discussion:

Resolving patch:
diff --git a/shell/cli/shell.py b/shell/cli/shell.py
--- a/shell/cli/shell.py
+++ b/shell/cli/shell.py
@@ -18,6 +18,7 @@
 
 from __future__ import print_function
 import code
+import logging
 import os
 import signal
 import sys
@@ -62,6 +63,7 @@ def console(self, local_vars):
                       ' to get one.')
             for i in sorted(local_vars):
                 print('%s: %s' % (i, local_vars[i]))
+            logging.disable(logging.CRITICAL)
             Console(locals=local_vars).interact()
 
     def shell(self, dbname):


Test patch:
Repository: OCA/server-tools

Issue:
tree_view_record_id: causes a warning in the logs
in the runbot logs I get:

2015-07-17 13:09:05,793 27838 WARNING 3110977-7-0-458127-all openerp.modules.loading: The model module.tree.view.record.id.installed has no access rules, consider adding one. E.g. access_module_tree_view_record_id_installed,access_module_tree_view_record_id_installed,model_module_tree_view_record_id_installed,,1,1,1,1

I tracked down module.tree.view.record.id.installed to tree_view_record_id

I totally don't understand why the pseudo dynamic a weird name generated that way, but an ACL is missing



Discussion:

Resolving patch:
diff --git a/sentry_logger/__init__.py b/sentry_logger/__init__.py
--- a/sentry_logger/__init__.py
+++ b/sentry_logger/__init__.py
@@ -20,6 +20,7 @@
 #
 ###############################################################################
 
+import os
 import logging
 import cgitb
 
@@ -54,7 +55,12 @@
         handler = OdooSentryHandler(client, level=level)
         root_logger.addHandler(handler)
     else:
-        root_logger.warn(u"Sentry DSN not defined in config file")
+        msg = u"Sentry DSN not defined in config file"
+        if os.environ.get('OCA_CI'):
+            # don't fail the build on runbot for this
+            root_logger.info(msg)
+        else:
+            root_logger.warn(msg)
         client = None
 
     # Inject sentry_activated to session to display error message or not
diff --git a/tree_view_record_id/__openerp__.py b/tree_view_record_id/__openerp__.py
--- a/tree_view_record_id/__openerp__.py
+++ b/tree_view_record_id/__openerp__.py
@@ -41,6 +41,7 @@
         'base',
     ],
     'data': [
+        'security/ir.model.access.csv',
     ],
     'demo': [
     ],


Test patch:
Repository: OCA/server-tools

Issue:
[8.0][dead_mans_switch_client] Module crashes runbots
I'm seeing more and more runbots with :x: because of this module. [This seems the offending line](https://github.com/OCA/server-tools/blob/8.0/dead_mans_switch_client/models/dead_mans_switch_client.py#L54). Any clue on how to fix it?

Example runbot: https://runbot.odoo-community.org/runbot/build/3137787

CC @hbrunn.



Discussion:
make a PR to log a warning instead of an error. Or better (but not simple to do) make a PR for runbot to ignore some error logs

I can see this fails because no `dead_mans_switch_client.url` parameter is present. What about creating demo data for it pointing to `localhost`, where dead_mans_switch_server will be installed too in runbots?

Could you tell me what value should it have? Thanks.

you can try that too, but I'm not sure that's guaranteed to work because there's no dependency between the two modules. Another issue is that tests don't use multithreading, so there's a chance the test justs deadlocks there.
But to try it anyways, use `http://localhost:$port/dead_mans_switch/alive`


Resolving patch:
diff --git a/dead_mans_switch_client/__openerp__.py b/dead_mans_switch_client/__openerp__.py
--- a/dead_mans_switch_client/__openerp__.py
+++ b/dead_mans_switch_client/__openerp__.py
@@ -3,7 +3,7 @@
 # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
 {
     "name": "Dead man's switch (client)",
-    "version": "8.0.1.0.0",
+    "version": "8.0.1.0.1",
     "author": "Therp BV,Odoo Community Association (OCA)",
     "license": "AGPL-3",
     "category": "Monitoring",
@@ -15,4 +15,7 @@
         "data/ir_actions.xml",
         "data/ir_cron.xml",
     ],
+    "demo": [
+        "demo/dead_mans_switch_client_demo.yml",
+    ],
 }
diff --git a/dead_mans_switch_client/models/dead_mans_switch_client.py b/dead_mans_switch_client/models/dead_mans_switch_client.py
--- a/dead_mans_switch_client/models/dead_mans_switch_client.py
+++ b/dead_mans_switch_client/models/dead_mans_switch_client.py
@@ -1,5 +1,6 @@
 # -*- coding: utf-8 -*-
 # © 2015 Therp BV <http://therp.nl>
+# © 2015 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
 # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
 import json
 import logging
@@ -66,3 +67,19 @@ def alive(self):
                 {
                     'Content-Type': 'application/json',
                 }))
+
+    @api.model
+    def _install_default_url(self):
+        """Set up a default URL."""
+        conf = self.env["ir.config_parameter"]
+        name = "dead_mans_switch_client.url"
+        param = conf.get_param(name)
+
+        if not param:
+            url = "{}/dead_mans_switch/alive".format(
+                conf.get_param(
+                    "report.url",
+                    conf.get_param(
+                        "web.base.url",
+                        "http://localhost")))
+            conf.set_param(name, url)


Test patch:
Repository: OCA/server-tools

Issue:
runbot 9.0 red due to letsencrypt?
Hi,

It seems the 9.0 branch is red on runbot due to the letsencrypt module?

```
Call of self.pool.get('letsencrypt').cron(cr, uid, *()) failed in Job 2
Traceback (most recent call last):
  File "/srv/openerp/instances/openerp-oca-runbot/parts/odoo-extra/runbot/static/build/3148182-9-0-209efa/openerp/addons/base/ir/ir_cron.py", line 129, in _callback
    getattr(model, method_name)(cr, uid, *args)
  File "/srv/openerp/instances/openerp-oca-runbot/parts/odoo-extra/runbot/static/build/3148182-9-0-209efa/openerp/api.py", line 250, in wrapper
    return old_api(self, *args, **kwargs)
  File "/srv/openerp/instances/openerp-oca-runbot/parts/odoo-extra/runbot/static/build/3148182-9-0-209efa/openerp/api.py", line 354, in old_api
    result = method(recs, *args, **kwargs)
  File "/srv/openerp/instances/openerp-oca-runbot/parts/odoo-extra/runbot/static/build/3148182-9-0-209efa/openerp/addons/letsencrypt/models/letsencrypt.py", line 151, in cron
    account_key, csr, acme_challenge, log=_logger, CA=DEFAULT_CA)
  File "/srv/openerp/instances/openerp-oca-runbot/sandbox/local/lib/python2.7/site-packages/acme_tiny.py", line 104, in get_crt
    raise ValueError("Error requesting challenges: {0} {1}".format(code, result))
ValueError: Error requesting challenges: 400 {
  "type": "urn:acme:error:malformed",
  "detail": "Error creating new authz :: Invalid character in DNS name",
  "status": 400
}
```

@hbrunn 



Discussion:
with https://github.com/OCA/server-tools/pull/459, I get a quite different error. Can you restart your build?


Resolving patch:
diff --git a/letsencrypt/__openerp__.py b/letsencrypt/__openerp__.py
--- a/letsencrypt/__openerp__.py
+++ b/letsencrypt/__openerp__.py
@@ -16,6 +16,7 @@
     "data": [
         "data/ir_config_parameter.xml",
         "data/ir_cron.xml",
+        "demo/ir_cron.xml",
     ],
     "post_init_hook": 'post_init_hook',
     "installable": True,


Test patch:
Repository: OCA/server-tools

Issue:
Fix travis build on 9.0 branch
the 9.0 branch of the project is red, with really strange errors about computed fields. There have been such errors since the merge of #469 but for some reason they were neither fatal nor breaking the build. 

Splitting `database_cleanup` tests in .travis.yml seems to let the other modules go green, but the tests for database_cleanup are red. 



Discussion:
It's still red...

The exact same error is showing up in my builds as well.

@pedrobaeza @bmw95 I updated the description of the PR. 

@hbrunn @StefanRijnhart your help on this would be very welcome. 

There is a security check to see if the user actually has access to the purge wizard menus to prevent unauthorized access (because no access rules apply to transient models). Because the server is not in debug mode, access to technical menus is not available. This raises the security error.


Resolving patch:
diff --git a/database_cleanup/models/purge_wizard.py b/database_cleanup/models/purge_wizard.py
--- a/database_cleanup/models/purge_wizard.py
+++ b/database_cleanup/models/purge_wizard.py
@@ -24,8 +24,8 @@ def purge(self):
     @api.model
     def create(self, values):
         # make sure the user trying this is actually supposed to do it
-        if not self.env.ref('database_cleanup.menu_database_cleanup')\
-           .parent_id._filter_visible_menus():
+        if self.env.ref(
+                'base.group_erp_manager') not in self.env.user.groups_id:
             raise AccessDenied
         return super(CleanupPurgeLine, self).create(values)
 
@@ -86,8 +86,8 @@ def name_get(self):
     @api.model
     def create(self, values):
         # make sure the user trying this is actually supposed to do it
-        if not self.env.ref('database_cleanup.menu_database_cleanup')\
-           .parent_id._filter_visible_menus():
+        if self.env.ref(
+                'base.group_erp_manager') not in self.env.user.groups_id:
             raise AccessDenied
         return super(PurgeWizard, self).create(values)
 


Test patch:
Repository: davanstrien/flyswot

Issue:
check csv output doesn't have blank lines 



Discussion:

Resolving patch:
diff --git a/src/flyswot/inference.py b/src/flyswot/inference.py
--- a/src/flyswot/inference.py
+++ b/src/flyswot/inference.py
@@ -112,15 +112,14 @@ def predict_directory(
     typer.echo(f"Found {len(files)} files matching {pattern} in {directory}")
     csv_fname = create_csv_fname(csv_save_dir)
     create_csv_header(csv_fname)
-    with Progress() as progress:
-        prediction_progress = progress.add_task("Predicting images", total=len(files))
+    with typer.progressbar(length=len(files)) as progress:
         all_preds = []
         predictions = []
         for batch in itertoolz.partition_all(bs, files):
             batch_predictions = OnnxInference.predict_batch(batch, bs)
             all_preds.append(batch_predictions.batch_labels)
             predictions.append(batch_predictions)
-            progress.update(prediction_progress, advance=bs)
+            progress.update(len(batch))
             write_batch_preds_to_csv(csv_fname, batch_predictions)
         all_preds = list(itertoolz.concat(all_preds))
     print_table(all_preds)
@@ -155,14 +154,14 @@ def create_csv_fname(csv_directory: Path) -> Path:
 
 
 def create_csv_header(csv_path: Path) -> None:
-    with open(csv_path, mode="w") as csv_file:
+    with open(csv_path, mode="w", newline="") as csv_file:
         field_names = ["path", "directory", "predicted_label", "confidence"]
         writer = csv.DictWriter(csv_file, fieldnames=field_names)
         writer.writeheader()
 
 
 def write_batch_preds_to_csv(csv_fpath: Path, predictions: PredictionBatch) -> None:
-    with open(csv_fpath, mode="a") as csv_file:
+    with open(csv_fpath, mode="a", newline="") as csv_file:
         field_names = ["path", "directory", "predicted_label", "confidence"]
         writer = csv.DictWriter(csv_file, fieldnames=field_names)
         for pred in predictions.batch:


Test patch:
Repository: davanstrien/flyswot

Issue:
tidy logging for predict directory 
There is some superfluous and unclear logging information when running `flyswot predict directory`. 


Discussion:

Resolving patch:
diff --git a/src/flyswot/inference.py b/src/flyswot/inference.py
--- a/src/flyswot/inference.py
+++ b/src/flyswot/inference.py
@@ -93,9 +93,7 @@ def predict_directory(
     Creates a CSV report saved to `csv_save_dir` containing the predictions
     """
     start_time = time.perf_counter()
-    typer.echo(csv_save_dir)
     model_dir = models.ensure_model_dir()
-    typer.echo(model_dir)
     # TODO add load learner function that can be passed a model name
     model_parts = models.ensure_model(model_dir)
     model = model_parts.model
@@ -117,8 +115,9 @@ def predict_directory(
             progress.update(len(batch))
             write_batch_preds_to_csv(csv_fname, batch_predictions)
         all_preds = list(itertoolz.concat(all_preds))
+    typer.echo(f"CSV report stored in {csv_fname}")
     delta = timedelta(seconds=time.perf_counter() - start_time)
-    typer.echo(f"Time taken to run command {str(delta)}")
+    typer.echo(f"Time taken to run:  {str(delta)}")
     print_table(all_preds)
 
 
diff --git a/src/flyswot/models.py b/src/flyswot/models.py
--- a/src/flyswot/models.py
+++ b/src/flyswot/models.py
@@ -195,7 +195,6 @@ def ensure_model(
 ) -> Optional[LocalModel]:  # pragma: no cover
     """Checks for a local model and if not found downloads the latest available remote model"""
     local_model = _get_latest_model(model_dir)
-    typer.echo(f"model path {local_model}")
     if local_model and not check_latest:
         model_parts = _get_model_parts(local_model)
         return model_parts


Test patch:
Repository: davanstrien/flyswot

Issue:
update default for ensure_model to get latest model 



Discussion:

Resolving patch:
diff --git a/src/flyswot/inference.py b/src/flyswot/inference.py
--- a/src/flyswot/inference.py
+++ b/src/flyswot/inference.py
@@ -19,7 +19,7 @@
 import typer
 from PIL import Image  # type: ignore
 from rich.table import Table
-from toolz import itertoolz  # type: ignore
+from toolz import itertoolz
 
 from flyswot import core
 from flyswot import models
@@ -89,9 +89,9 @@ def predict_directory(
     pattern: str = typer.Option("fse", help="Pattern used to filter image filenames"),
     bs: int = typer.Option(16, help="Batch Size"),
     image_format: str = typer.Option(
-        ".tif",
-        help="Image format for flyswot to use for predictions",
+        ".tif", help="Image format for flyswot to use for predictions"
     ),
+    check_latest: bool = typer.Option(True, help="Use latest available model"),
 ):
     """Predicts against all images stored under DIRECTORY which match PATTERN in the filename.
 
@@ -102,7 +102,7 @@ def predict_directory(
     start_time = time.perf_counter()
     model_dir = models.ensure_model_dir()
     # TODO add load learner function that can be passed a model name
-    model_parts = models.ensure_model(model_dir)
+    model_parts = models.ensure_model(model_dir, check_latest)
     model = model_parts.model
     vocab = models.load_vocab(model_parts.vocab)
     onnxinference = OnnxInferenceSession(model, vocab)


Test patch: