internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: internetarchive/openlibrary

Issue:
Tab for declined merges
For librarians-in-training like me who commonly submit dozens to hundreds of merge suggestions at a time, it can be difficult to go back through checking to see which ones were rejected. If there was a tab added that specifically filtered the ones that are wrong, it would help me and other trainees correct mistakes more easily.

Is this a reasonable request?


Discussion:
I agree that rejected merges are useful feedback to be separated and thus emphasized

Resolving patch:
diff --git a/openlibrary/core/edits.py b/openlibrary/core/edits.py
--- a/openlibrary/core/edits.py
+++ b/openlibrary/core/edits.py
@@ -122,6 +122,9 @@ def where_clause(cls, mode, **kwargs):
                 if kwargs.get("submitter") is None
                 else "submitter=$submitter"
             )
+        # If status not specified, don't include it
+        if 'status' in kwargs and kwargs.get('status'):
+            wheres.append('status=$status')
         if "url" in kwargs:
             wheres.append("url=$url")
         if "id" in kwargs:
diff --git a/openlibrary/plugins/upstream/edits.py b/openlibrary/plugins/upstream/edits.py
--- a/openlibrary/plugins/upstream/edits.py
+++ b/openlibrary/plugins/upstream/edits.py
@@ -32,7 +32,13 @@ class community_edits_queue(delegate.page):
 
     def GET(self):
         i = web.input(
-            page=1, limit=25, mode="open", submitter=None, reviewer=None, order='desc'
+            page=1,
+            limit=25,
+            mode="open",
+            submitter=None,
+            reviewer=None,
+            order='desc',
+            status=None,
         )
         merge_requests = CommunityEditsQueue.get_requests(
             page=int(i.page),
@@ -41,6 +47,7 @@ def GET(self):
             submitter=i.submitter,
             reviewer=i.reviewer,
             order=f'updated {i.order}',
+            status=i.status,
         ).list()
 
         total_found = {


Test patch:
Repository: internetarchive/openlibrary

Issue:
Update cgi.FieldStorage to unblock Python 3.13
Python's `cgi` module has been [deprecated](https://docs.python.org/3/library/cgi.html) and will be removed in Python 3.13, `web.py` relies on `cgi.FieldStorage` for file upload, and Open Library uses `web.py` (and by proxy, `cgi.FieldStorage`, including, but not limited to, for cover upload). See [PEP-0594](https://peps.python.org/pep-0594/#cgi) for more.

@cclauss created an issue issue for this on the `web.py` GitHub: webpy/webpy#778.
### Proposal & Constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->
We need `web.py` updated to no longer use `cgi.FieldStorage`, we need to stick with Python <= 3.12, or we need to use something other than `web.py`, I think.

<!-- Which suggestions or requirements should be considered for how feature needs to appear or be implemented? -->
There's a PR to replace `cgi.FieldStorage` with [multipart](https://github.com/defnull/multipart/) and `urllib.parse.parse_qsl`: webpy/webpy#768.

### Additional context
<!-- Add any other context or screenshots about the feature request here. -->

### Stakeholders
<!-- @ tag stakeholders of this bug -->
@mekarpeles 
@cclauss 




Discussion:
Note Python 3.13 will be released october 2024 https://peps.python.org/pep-0719/

Resolving patch:
diff --git a/openlibrary/plugins/upstream/covers.py b/openlibrary/plugins/upstream/covers.py
--- a/openlibrary/plugins/upstream/covers.py
+++ b/openlibrary/plugins/upstream/covers.py
@@ -60,8 +60,8 @@ def upload(self, key, i):
         """Uploads a cover to coverstore and returns the response."""
         olid = key.split("/")[-1]
 
-        if i.file is not None and hasattr(i.file, 'value'):
-            data = i.file.value
+        if i.file is not None and hasattr(i.file, 'file'):
+            data = i.file.file
         else:
             data = None
 
@@ -82,7 +82,7 @@ def upload(self, key, i):
             upload_url = "http:" + upload_url
 
         try:
-            files = {'data': BytesIO(data)}
+            files = {'data': data}
             response = requests.post(upload_url, data=params, files=files)
             return web.storage(response.json())
         except requests.HTTPError as e:


Test patch:
Repository: internetarchive/openlibrary

Issue:
Rename merge queue files for consistency
### Short Summary:
Refactor merge request table such that there is more parity between the JS and HTML files.

### Background:
Names of files related to the librarian merge queue have become inconsistent over time:

#### Current file names
| Component | JS filename | HTML filename | LESS filename |
|--------|--------|--------|--------|
| Table header | merge-request-table/LibrarianQueue/TableHeader.js | `None` | components/merge-request-table.less |
| Table row | merge-request-table/LibrarianQueue/TableRow.js | `None`| components/merge-request-table.less |
| Base component (the whole table) | merge-request-table/LibrarianQueue.js | merge_queue/merge_queue.html | components/merge-request-table.less | 

I figure that the naming conventions for the JS and LESS files are in alignment, and no changes are required.  Our HTML template tile,,however, has an entirely different name, and would be difficult to find by a new developer (at least not without the help of somebody who is familiar with this code).  It's also kind of odd that there is a JS file for each component, but only one template file.

### Main Requirements:
1. Create two new template files: one for the table header, and one for a single table row.  Move existing header and table row HTML into their respective, newly created files.
2. Ensure that the following filepaths are used:

#### Updated file names
| Component | JS filename | HTML filename |
|--------|--------|--------|
| Table header | merge-request-table/MergeRequestTable/TableHeader.js | merge_request_table/table_header.html |
| Table row | merge-request-table/MergeRequestTable/TableRow.js | merge_request_table/table_row.html |
| Base component (the whole table) | merge-request-table/MergeRequestTable.js | merge_request_table/merge_request_table.html |

### Checklist:
- [ ] JS filepaths have been updated as per the above "Updated file names" table.
  - [ ] All references to these files have been updated.
- [ ] New templates have been created
  - [ ] table_header.html
  - [ ] table_row.html
- [ ] Existing merge_queue/merge_queue.html template has been updated:
  - [ ] Change filepath to merge_request_table/merge_request_table.html
  - [ ] Replace header and table row code with references to the new templates
- [ ] Update all references to the merge table template file


Discussion:
I would like to take this issue!

Resolving patch:
diff --git a/openlibrary/plugins/upstream/edits.py b/openlibrary/plugins/upstream/edits.py
--- a/openlibrary/plugins/upstream/edits.py
+++ b/openlibrary/plugins/upstream/edits.py
@@ -67,7 +67,7 @@ def GET(self):
         }
 
         return render_template(
-            'merge_queue/merge_queue',
+            'merge_request_table/merge_request_table',
             total_found,
             librarians,
             merge_requests=merge_requests,


Test patch:
Repository: internetarchive/openlibrary

Issue:
Subject tag autocomplete no longer sorts by frequency
When I developed autocomplete for subject tags, the results returned were automatically sorted by frequency — the most used subjects that matched were first on the list. This not only produced useful results, but helped concentrate the usage of particular subjects where multiple similar labels exist for a single topic, improving the quality of subject pages.

In subsequent refactoring of autocomplete support, this frequency sorting was lost.

### Steps to Reproduce
Edit a work and start typing in one of the subject fields to display the list of matching subjects.

<!-- What actually happened after these steps? What did you expect to happen? -->
* Actual: Subject suggestions are sorted in an apparently random order
* Expected: Subjects should be sorted with the "better" (more frequently used) choices at the top.

### Proposal & Constraints
I will be submitting a PR that restores the SOLR query that produces the frequency-sorted results.

### Stakeholders
@mheiman @cdrini 



Discussion:
There was a recent bug about author autocomplete ordering too: #8299, which suggests non-subject items may be similarly affected.



Resolving patch:
diff --git a/openlibrary/plugins/worksearch/autocomplete.py b/openlibrary/plugins/worksearch/autocomplete.py
--- a/openlibrary/plugins/worksearch/autocomplete.py
+++ b/openlibrary/plugins/worksearch/autocomplete.py
@@ -24,6 +24,7 @@ class autocomplete(delegate.page):
     fq = ['-type:edition']
     fl = 'key,type,name,title,score'
     olid_suffix: str | None = None
+    sort: str | None = None
     query = 'title:"{q}"^2 OR title:({q}*) OR name:"{q}"^2 OR name:({q}*)'
 
     def db_fetch(self, key: str) -> Thing | None:
@@ -68,6 +69,7 @@ def direct_get(self, fq: list[str] | None = None):
             **({'fq': fq} if fq else {}),
             # limit the fields returned for better performance
             'fl': self.fl,
+            **({'sort': self.sort} if self.sort else {}),
         }
 
         data = solr.select(solr_q, **params)
@@ -138,8 +140,9 @@ class subjects_autocomplete(autocomplete):
     # can't use /subjects/_autocomplete because the subjects endpoint = /subjects/[^/]+
     path = "/subjects_autocomplete"
     fq = ['type:subject']
-    fl = 'key,name'
+    fl = 'key,name,work_count'
     query = 'name:({q}*)'
+    sort = 'work_count desc'
 
     def GET(self):
         i = web.input(type="")


Test patch:
Repository: internetarchive/openlibrary

Issue:
Remove inline js: account/readinglog_stats.html
<!-- What problem are we solving? What does the experience look like today? What are the symptoms? -->
Remove the inline JS from this file following the recommended steps in #4474

### Proposal & Constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->
This one may be a little more difficult as it requires passing some data.
Suggested: use data-config on div.readinglog-charts element instead

### Related files
<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->
https://github.com/internetarchive/openlibrary/blob/master/openlibrary/templates/account/readinglog_stats.html

### Stakeholders
<!-- @ tag stakeholders of this bug -->



Discussion:

Resolving patch:
diff --git a/openlibrary/plugins/upstream/mybooks.py b/openlibrary/plugins/upstream/mybooks.py
--- a/openlibrary/plugins/upstream/mybooks.py
+++ b/openlibrary/plugins/upstream/mybooks.py
@@ -155,8 +155,8 @@ def GET(self, username, key='want-to-read'):
             for a in web.ctx.site.get_many(list(author_keys))
         ]
         return render['account/readinglog_stats'](
-            json.dumps(works_json),
-            json.dumps(authors_json),
+            works_json,
+            authors_json,
             len(works_json),
             user.key,
             user.displayname,


Test patch:
Repository: internetarchive/openlibrary

Issue:
"Share List" Previews broken
<!-- What problem are we solving? What does the experience look like today? What are the symptoms? -->

* re: #6608 

List previews seem to be broken across lists

### Evidence / Screenshot (if possible)

https://openlibrary.org/people/mekBot/lists/OL235922L/Library_Leader%27s_Forum_2024/preview.png?debug=true

![image](https://github.com/internetarchive/openlibrary/assets/978325/4c0d9e61-0e44-4593-a6fa-380dabc13349)

### Relevant url?
<!-- `https://openlibrary.org/...` -->

### Steps to Reproduce
<!-- What steps caused you to find the bug? -->
1. Go to ...
2. Do ...

<!-- What actually happened after these steps? What did you expect to happen? -->
* Actual:
* Expected:

### Details

- **Logged in (Y/N)?**
- **Browser type/version?**
- **Operating system?**
- **Environment (prod/dev/local)?** prod
<!-- If not sure, put prod -->

### Proposal & Constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->

### Related files
<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->

### Stakeholders
<!-- @ tag stakeholders of this bug -->



Discussion:

Resolving patch:
diff --git a/openlibrary/coverstore/code.py b/openlibrary/coverstore/code.py
--- a/openlibrary/coverstore/code.py
+++ b/openlibrary/coverstore/code.py
@@ -595,12 +595,15 @@ def render_list_preview_image(lst_key):
     author_text = "A list on Open Library"
     if owner := lst.get_owner():
         author_text = f"A list by {owner.displayname}"
-    w, h = draw.textsize(author_text, font=font_author)
+
+    left, top, right, bottom = font_author.getbbox(author_text)
+    w, h = right - left, bottom - top
     draw.text(((W - w) / 2, current_h), author_text, font=font_author, fill=(0, 0, 0))
     current_h += h + 5
 
     for line in para:
-        w, h = draw.textsize(line, font=font_title)
+        left, top, right, bottom = font_title.getbbox(line)
+        w, h = right - left, bottom - top
         draw.text(((W - w) / 2, current_h), line, font=font_title, fill=(0, 0, 0))
         current_h += h
 


Test patch:
Repository: internetarchive/openlibrary

Issue:
Prefill author name when adding work from author page
<!-- What problem are we solving? What does the experience look like today? What are the symptoms? -->

When adding a new work from an author's page, the author is not automically prefilled on the add page.

This use to work in the past.

### Evidence / Screenshot (if possible)

![image](https://github.com/internetarchive/openlibrary/assets/73437497/27c8bff8-3afb-4040-92d0-5ff49cb10533)

### Relevant url?

Example above from: https://openlibrary.org/books/add?author=/authors/OL1573400A

### Steps to Reproduce
<!-- What steps caused you to find the bug? -->
1. Go to an author page
2. Click the "Add another?" link near the work counter

<!-- What actually happened after these steps? What did you expect to happen? -->
* Actual:
* Expected:

![image](https://github.com/internetarchive/openlibrary/assets/73437497/ce001918-4dbb-4e34-80de-6f0f5d44bce1)

### Details

- **Logged in (Y/N)?**
- **Browser type/version?**
- **Operating system?**
- **Environment (prod/dev/local)?** prod
<!-- If not sure, put prod -->

### Proposal & Constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->

### Related files
<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->

### Stakeholders
<!-- @ tag stakeholders of this bug -->



Discussion:
Working on this, will have a PR shortly

Resolving patch:
diff --git a/openlibrary/plugins/upstream/addbook.py b/openlibrary/plugins/upstream/addbook.py
--- a/openlibrary/plugins/upstream/addbook.py
+++ b/openlibrary/plugins/upstream/addbook.py
@@ -193,11 +193,17 @@ def GET(self):
         if not self.has_permission():
             return safe_seeother(f"/account/login?redirect={self.path}")
 
-        i = web.input(work=None)
+        i = web.input(work=None, author=None)
         work = i.work and web.ctx.site.get(i.work)
+        author = i.author and web.ctx.site.get(i.author)
+
+        # pre-filling existing author(s) if adding new edition from existing work page
         authors = (work and work.authors) or []
         if work and authors:
             authors = [a.author for a in authors]
+        # pre-filling existing author if adding new work from author page
+        if author and author not in authors:
+            authors.append(author)
 
         return render_template(
             'books/add', work=work, authors=authors, recaptcha=get_recaptcha()


Test patch:
Repository: internetarchive/openlibrary

Issue:
Open Library Team Page
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->

### Describe the problem that you'd like solved
<!-- A clear and concise description of what you want to happen. -->

A basic team page design for https://openlibrary.org/about/people

Designs:
https://www.figma.com/proto/8MoiibMFcYHI3djoiiFmWP/Meet-the-Staff-2?node-id=206%3A244&scaling=min-zoom&page-id=206%3A213&starting-point-node-id=206%3A244

<img width="1065" alt="Screenshot 2023-03-14 at 7 43 39 PM" src="https://user-images.githubusercontent.com/978325/225191644-b40b07c3-60ae-4632-844e-58d508cc7106.png">

## Important files & next steps

Here is an example of how to register a new route with Open Library (i.e. how to define or override an endpoint like `/about/people`:
https://github.com/internetarchive/openlibrary/blob/master/openlibrary/plugins/openlibrary/authors.py

We'll also need to add a new file to our `templates/` directory -- `/about/people.html` in:
https://github.com/internetarchive/openlibrary/tree/master/openlibrary/templates

## Relevant resources
* https://archive.org/details/openlibrary-tour-2020/technical_overview.mp4



Discussion:
I'd like to work on this issue!
@Lasseignejk please do! Do you have any questions or need any help with next steps?

Resolving patch:
diff --git a/openlibrary/plugins/openlibrary/code.py b/openlibrary/plugins/openlibrary/code.py
--- a/openlibrary/plugins/openlibrary/code.py
+++ b/openlibrary/plugins/openlibrary/code.py
@@ -222,13 +222,7 @@ class team(delegate.page):
     path = '/about/team'
 
     def GET(self):
-        with Path('/openlibrary/openlibrary/templates/about/team.json').open(
-            mode='r'
-        ) as f:
-            team_members: list[dict[str, str]] = sorted(
-                json.load(f), key=lambda member: member['name'].split()[-1]
-            )
-            return render_template("about/index.html", team_members=team_members)
+        return render_template("about/index.html")
 
 
 class addbook(delegate.page):


Test patch:
Repository: internetarchive/openlibrary

Issue:
Handle Upstream Lending & API exceptions
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->

### Describe the problem that you'd like solved
<!-- A clear and concise description of what you want to happen. -->
Relates to #3429 and #8371, when upstream services decide to raise an error and return a non 200 response, this often results in exceptions being raised for Open Library patrons which appear as generic error screens that are not useful or descriptive.

e.g. https://sentry.archive.org/organizations/ia-ux/issues/46145/?project=7&query=lending&referrer=issue-stream&statsPeriod=14d

### Proposal
Proposing that both in petabox and Open Library the code be brought into alignment so that different classes of upstream errors are captured and handled independently so we can have better visibility into actual system errors (like outages) and decrease confusion for patrons.  

### Stakeholders
<!-- @ tag stakeholders of this bug -->
@bfalling @judec 




Discussion:

Resolving patch:
diff --git a/openlibrary/plugins/upstream/borrow.py b/openlibrary/plugins/upstream/borrow.py
--- a/openlibrary/plugins/upstream/borrow.py
+++ b/openlibrary/plugins/upstream/borrow.py
@@ -14,13 +14,14 @@
 
 from infogami import config
 from infogami.utils import delegate
-from infogami.utils.view import public, render_template
+from infogami.utils.view import public, render_template, add_flash_message
 from infogami.infobase.utils import parse_datetime
 
 from openlibrary.core import stats
 from openlibrary.core import lending
 from openlibrary.core import vendors
 from openlibrary.core import waitinglist
+from openlibrary.i18n import gettext as _
 from openlibrary.accounts.model import OpenLibraryAccount
 from openlibrary import accounts
 from openlibrary.utils import dateutil
@@ -189,6 +190,14 @@ def POST(self, key):
             except lending.PatronAccessException as e:
                 stats.increment('ol.loans.blocked')
 
+                add_flash_message(
+                    'error',
+                    _(
+                        'Your account has hit a lending limit. Please try again later or contact info@archive.org.'
+                    ),
+                )
+                raise web.seeother(key)
+
         if action in ('borrow', 'browse', 'read'):
             bookPath = '/stream/' + edition.ocaid
             if i._autoReadAloud is not None:


Test patch:
Repository: internetarchive/openlibrary

Issue:
Sidebar missing from settings page
<!-- What problem are we solving? What does the experience look like today? What are the symptoms? -->
Sidebar is broken on account settings page.  Suspect that this is due to `counts` being `None`.

This is happening on staging, but not production.

### Evidence / Screenshot (if possible)
![image](https://github.com/internetarchive/openlibrary/assets/28732543/7d18526a-e93b-4860-9d4b-4c3a7e0c8655)

### Relevant url?
<!-- `https://openlibrary.org/...` -->
https://staging.openlibrary.org/account
https://staging.openlibrary.org/account?debug=true

### Steps to Reproduce
<!-- What steps caused you to find the bug? -->
While on staging:
1. Log in.
2. Go to your account settings page.

<!-- What actually happened after these steps? What did you expect to happen? -->
* Actual: Error message is displayed, but no sidebar.
* Expected: The sidebar is there.

### Details

- **Logged in (Y/N)?** Y
- **Browser type/version?** Any modern browser
- **Operating system?** Any
- **Environment (prod/dev/local)?** prod
<!-- If not sure, put prod -->

### Proposal & Constraints
<!-- What is the proposed solution / implementation? Is there a precedent of this approach succeeding elsewhere? -->

### Related files
<!-- Files related to this issue; this is super useful for new contributors who might want to help! If you're not sure, leave this blank; a maintainer will add them. -->
Possibly related to #8597

### Stakeholders
<!-- @ tag stakeholders of this bug -->
@mekarpeles 



Discussion:

Resolving patch:
diff --git a/openlibrary/plugins/upstream/mybooks.py b/openlibrary/plugins/upstream/mybooks.py
--- a/openlibrary/plugins/upstream/mybooks.py
+++ b/openlibrary/plugins/upstream/mybooks.py
@@ -382,7 +382,7 @@ def __init__(self, username, key):
             else []
         )
 
-        if self.me and self.is_my_page and self.key in self.ALL_KEYS:
+        if self.me and self.is_my_page:
             self.counts.update(PatronBooknotes.get_counts(self.username))
             self.sponsorships = get_sponsored_editions(self.user)
             self.counts['sponsorships'] = len(self.sponsorships)


Test patch: