internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: akvo/akvo-rsr

Issue:
Program PDF report returns an XLS report
# What were you doing?

Follow the steps in test "Download PDF Program overview".

# What should've happened?

A PDF report should've been received in the email, but an XLS report was delivered.


Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/py_reports/email_report.py b/akvo/rsr/views/py_reports/email_report.py
--- a/akvo/rsr/views/py_reports/email_report.py
+++ b/akvo/rsr/views/py_reports/email_report.py
@@ -16,7 +16,7 @@
 TIMEOUT = timedelta(minutes=30)
 MAX_ATTEMPTS = 3
 HANDLER = {
-    program_overview_pdf_report.REPORT_NAME: program_overview_excel_report.handle_email_report,
+    program_overview_pdf_report.REPORT_NAME: program_overview_pdf_report.handle_email_report,
     program_overview_excel_report.REPORT_NAME: program_overview_excel_report.handle_email_report,
     program_period_labels_overview_pdf_report.REPORT_NAME: program_period_labels_overview_pdf_report.handle_email_report,
     results_indicators_with_map_pdf_reports.ORG_PROJECTS_REPORT_NAME: results_indicators_with_map_pdf_reports.handle_org_projects_email_report,
@@ -35,6 +35,7 @@ def run_job():
     try:
         handler = HANDLER.get(job.report, None)
         if handler:
+            logger.info("Handling job %s for report %s with %s", job.id, job.report)
             handler(job.payload, job.recipient)
         job.mark_finished()
     except Exception:


Test patch:
Repository: akvo/akvo-rsr

Issue:
Fallback to value in "Report Admin > Pending Approval" list view
# Current situation

Some updates look like they have no value and others do.

![Image](https://user-images.githubusercontent.com/91939214/211502642-df01abac-d774-4fad-a167-a0940796a42f.png)

The reason is that some have descriptions and others don't.

**Examples:**

With description
![Image](https://user-images.githubusercontent.com/91939214/211502702-3a0a1f62-4de4-4dc0-9212-f4d061bad2f2.png)

Without description
![Image](https://user-images.githubusercontent.com/91939214/211502718-d95d8e2a-60f0-4ff2-b348-909fc9411559.png)

# Improvement

Fallback to the actual value when no description has been provided.


Discussion:

Resolving patch:
diff --git a/akvo/rest/serializers/indicator_period_data.py b/akvo/rest/serializers/indicator_period_data.py
--- a/akvo/rest/serializers/indicator_period_data.py
+++ b/akvo/rest/serializers/indicator_period_data.py
@@ -84,7 +84,7 @@ class Meta:
         model = IndicatorPeriodData
         fields = (
             'id', 'user_details', 'status', 'status_display', 'update_method', 'value', 'numerator', 'denominator', 'text',
-            'disaggregations', 'narrative', 'photo_url', 'file_url', 'created_at', 'last_modified_at',
+            'disaggregations', 'narrative', 'score_indices', 'photo_url', 'file_url', 'created_at', 'last_modified_at',
             'file_set', 'photo_set', 'review_note', 'comments',
         )
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Feature Request: Generate reference documentation from docstrings
### What are you trying to do?

Easily view reference documentation.

### Describe the solution you'd like

A reference documentation generated from the docstrings.

### Have you consider alternatives?

_No response_

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/akvo/rsr/management/commands/reverse_geocode_city_names.py b/akvo/rsr/management/commands/reverse_geocode_city_names.py
--- a/akvo/rsr/management/commands/reverse_geocode_city_names.py
+++ b/akvo/rsr/management/commands/reverse_geocode_city_names.py
@@ -17,7 +17,6 @@
 import json
 import os
 import tempfile
-import sys
 
 from django.core.management.base import BaseCommand, CommandError
 from django.db.models import Q
@@ -29,7 +28,8 @@
 RAPIDAPI_KEY = os.environ.get('RAPIDAPI_KEY', None)
 if not RAPIDAPI_KEY:
     print('Please set the RAPIDAPI_KEY environment variable')
-    sys.exit(1)
+    # Raise an error instead of exiting the entire process so that other tools can import the file
+    raise ValueError()
 
 session = requests.Session()
 
diff --git a/doc/conf.py b/doc/conf.py
new file mode 100644
--- /dev/null
+++ b/doc/conf.py
@@ -0,0 +1,39 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# For the full list of built-in configuration values, see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Project information -----------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
+
+import os
+import sys
+import django
+sys.path.insert(0, os.path.abspath('..'))
+os.environ['DJANGO_SETTINGS_MODULE'] = 'akvo.settings'
+django.setup()
+
+project = 'Akvo RSR'
+copyright = '2023, Akvo Foundation'
+author = 'Akvo Foundation'
+
+# -- General configuration ---------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
+
+extensions = [
+    'sphinx.ext.autodoc',
+    'sphinx.ext.autosummary',
+    'sphinx.ext.viewcode',
+    'myst_parser',
+]
+
+templates_path = ['_templates']
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+
+
+# -- Options for HTML output -------------------------------------------------
+# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
+
+html_theme = 'cloud'
+html_static_path = ['_static']
diff --git a/gen_doc.py b/gen_doc.py
new file mode 100755
--- /dev/null
+++ b/gen_doc.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+
+import os
+
+from pdoc.cli import *
+
+OUTPUT_DIR = "./public"
+
+# Programmatically provide settings module
+SETTINGS_MODULE = "akvo.settings"
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', SETTINGS_MODULE)
+
+# Setup Django
+import django
+django.setup()
+
+cmdline_args = [
+    "--html",
+    "-o" , OUTPUT_DIR,
+    "--skip-errors",
+    "--force",
+    "akvo",
+]
+
+if __name__ == "__main__":
+    main(parser.parse_args(cmdline_args))


Test patch:
Repository: akvo/akvo-rsr

Issue:
Feature Request: Document the results framework
### What are you trying to do?

Understand how the results framework functions

### Describe the solution you'd like

A technical documentation of how it works.

### Have you consider alternatives?

_No response_

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/project_hierarchy.py b/akvo/rsr/models/project_hierarchy.py
--- a/akvo/rsr/models/project_hierarchy.py
+++ b/akvo/rsr/models/project_hierarchy.py
@@ -9,10 +9,22 @@
 
 
 class ProjectHierarchy(models.Model):
+    """
+    The actual "Program" with a project hierarchy.
+    """
     project_relation = 'projecthierarchy__in'
+
     root_project = models.OneToOneField('Project', on_delete=models.CASCADE, db_index=True)
+    """
+    The root of the program
+    It can be used to create subprograms / a program tree
+    """
+
     max_depth = models.PositiveSmallIntegerField()
+    """TODO: It is unclear why this field currently exists"""
+
     is_master = models.BooleanField(_('is master program'), default=False)
+    """Used when an organisation has one program under which they would like to create subprograms"""
 
     class Meta:
         app_label = 'rsr'
@@ -22,10 +34,15 @@ class Meta:
 
     @property
     def descendants(self):
+        """
+        The entire tree in a list.
+        No order is guaranteed
+        """
         return self.root_project.descendants(max_depth=self.max_depth)
 
     @property
     def project_count(self):
+        """The number of children without counting the root project"""
         return self.descendants.count() - 1  # remove root_project from count
 
     @property
@@ -34,6 +51,7 @@ def project_ids(self):
 
     @property
     def organisation(self):
+        """The reporting organisation of the tree"""
         return self.root_project.reporting_org
 
     def __str__(self):
diff --git a/doc/conf.py b/doc/conf.py
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -21,6 +21,7 @@
 # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
 
 extensions = [
+    'sphinxcontrib.plantuml',
     'sphinx.ext.autodoc',
     'sphinx.ext.autosummary',
     'sphinx.ext.viewcode',
@@ -30,7 +31,9 @@
 templates_path = ['_templates']
 exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
 
-
+myst_enable_extensions = [
+    "colon_fence",  # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#syntax-colon-fence
+]
 
 # -- Options for HTML output -------------------------------------------------
 # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output


Test patch:
Repository: akvo/akvo-rsr

Issue:
Bug: IATI organisation and activity file URL should have .xml suffix
### What were you doing?

The IATI registry updated its website to look at the ending of the organisation and activity file URL and expect it to have a `.xml` suffix.

### What should've happened?

The IATI organisation and activity file URL should have a `.xml` suffix

### My environment

_No response_

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/akvo/urls.py b/akvo/urls.py
--- a/akvo/urls.py
+++ b/akvo/urls.py
@@ -226,11 +226,11 @@
     url(r'^project/(?P<project_id>\d+)/iati/$',
         project.iati, name='project-iati'),
 
-    url(r'^organisation/(?P<organisation_id>\d+)/iati/$',
+    url(r'^organisation/(?P<organisation_id>\d+)/iati(/|(/?\.xml)?)$',
         organisation.iati, name='projects-iati'),
 
     # IATI organisation file
-    url(r'^organisation/(?P<organisation_id>\d+)/iati-org/$',
+    url(r'^organisation/(?P<organisation_id>\d+)/iati-org(/|(/?\.xml)?)$',
         organisation.iati_org, name='org-iati'),
 
     # Legacy TastyPie API emulation


Test patch:
Repository: akvo/akvo-rsr

Issue:
Feature Request: Document the task management
### What are you trying to do?

Understand how the task management functions

### Describe the solution you'd like

A technical documentation of how it works.

### Have you consider alternatives?

_No response_

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/akvo/cache/heartbeat.py b/akvo/cache/heartbeat.py
--- a/akvo/cache/heartbeat.py
+++ b/akvo/cache/heartbeat.py
@@ -8,7 +8,7 @@
 
 class CacheHeartbeat(Thread):
     """
-    Thread to update set a cache key with a max life and refresh it as long as the thread is alive
+    Thread to set a cache key with a max life and refresh it as long as the thread is alive
 
     The thread can be ended by setting the `event_end` flag
     """
@@ -38,7 +38,13 @@ def run(self) -> None:
         logger.info("Ended cache heartbeat for '%s'", self.cache_key)
 
     def set_cache_value(self):
-        cache.set(self.cache_key, self.get_calc_value(), self.key_timeout)
+        """
+        Set the cache key and its value
+        """
+        cache.set(self.cache_key, self.calc_cache_value(), self.key_timeout)
 
-    def get_calc_value(self) -> Union[str, int, float]:
+    def calc_cache_value(self) -> Union[str, int, float]:
+        """
+        Calculate a value to be used when setting the cache key
+        """
         return datetime.datetime.utcnow().timestamp()
diff --git a/akvo/rsr/management/commands/django_q_probettp.py b/akvo/rsr/management/commands/django_q_probettp.py
--- a/akvo/rsr/management/commands/django_q_probettp.py
+++ b/akvo/rsr/management/commands/django_q_probettp.py
@@ -38,8 +38,14 @@ def handle_end(*_):
 
 
 class DjangoQRequestHandler(BaseHTTPRequestHandler):
+    """
+    A handler to be used with HTTPServer to get the status of the local django-q cluster
+    """
 
     def do_GET(self):
+        """
+        Handle GET requests to return a simple string indicating the status of the django-q cluster
+        """
         hostname = socket.gethostname()
 
         # Find local cluster


Test patch:
Repository: akvo/akvo-rsr

Issue:
Bug: Setting the "Contributes to" field on project editor does not set the project parent
### What were you doing?

Given a standalone project. Setting the "Contributes to" field with another project in RSR retains the field's value but does not set the associated project as the parent.

Given a contributing project with all imported results framework removed. Setting a "Contributes to" field with another project in RSR retains the field's value but doesn't change its parent.

### What should've happened?

Setting the "Contributes to" field with another project in RSR should set the associated project as the parent.

### My environment

_No response_

### Additional context

Problematic projects example
- https://rsr.akvo.org/my-rsr/projects/10634/info
- https://rsr.akvo.org/my-rsr/projects/10617/info


Discussion:

Resolving patch:
diff --git a/akvo/rest/serializers/project.py b/akvo/rest/serializers/project.py
--- a/akvo/rest/serializers/project.py
+++ b/akvo/rest/serializers/project.py
@@ -138,11 +138,17 @@ def get_path(self, project: Project):
         return str(project.path)
 
     def update(self, project: Project, validated_data: dict):
-        # mutual exclusion: contributes_to_project and external_parent_iati_activity_id
         if "contributes_to_project" in validated_data:
+            parent = validated_data['contributes_to_project']
+            if parent:
+                project.set_parent(validated_data['contributes_to_project'])
+            else:
+                project.delete_parent()
             validated_data["external_parent_iati_activity_id"] = None
-        elif "external_parent_iati_activity_id" in validated_data:
-            validated_data["contributes_to_project"] = None
+        elif "external_parent_iati_activity_id" in validated_data and validated_data['external_parent_iati_activity_id']:
+            project.delete_parent()
+
+        validated_data["contributes_to_project"] = None
 
         return super().update(project, validated_data)
 


Test patch:
diff --git a/akvo/rsr/tests/rest/test_project.py b/akvo/rsr/tests/rest/test_project.py
--- a/akvo/rsr/tests/rest/test_project.py
+++ b/akvo/rsr/tests/rest/test_project.py
@@ -619,7 +619,7 @@ def test_set_parent_contributing_project(self):
         # external parent should have been removed
         self.assertIsNone(self.project.external_parent_iati_activity_id)
         # internal parent should have been set
-        self.assertEqual(self.project.contributes_to_project_id, self.parent_project.id)
+        self.assertEqual(self.project.parent().id, self.parent_project.id)
 
     def test_set_external_parent_contributing_project(self):
         # Set a pre-existing internal parent
Repository: akvo/akvo-rsr

Issue:
Bug: IATI inconsistency emails are spammy
### What were you doing?

Getting many emails from the IATI inconsistency checks.

Some projects are being checked that haven't been published yet (unpublished projects can't be exported).


### What should've happened?

Only published projects should be checked and the email should state how to compare the internal vs the external check results.

### My environment

_No response_

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/akvo/rsr/usecases/iati_validation/schedule_validation.py b/akvo/rsr/usecases/iati_validation/schedule_validation.py
--- a/akvo/rsr/usecases/iati_validation/schedule_validation.py
+++ b/akvo/rsr/usecases/iati_validation/schedule_validation.py
@@ -13,15 +13,16 @@
 
 
 def schedule_iati_activity_validation(project: Project, schedule_at: Optional[datetime] = None):
-    logger.info("Scheduling IATI validation for project %s", project.id)
-    scheduled_at = schedule_at if schedule_at else now() + DEFAULT_SCHEDULE_DELAY_TIME
-    pending_jobs = IatiActivityValidationJob.objects.filter(project=project, started_at=None)
-    if pending_jobs.exists():
-        job = pending_jobs.first()
-        job.scheduled_at = scheduled_at
-        job.save(update_fields=['scheduled_at'])
-    else:
-        IatiActivityValidationJob.objects.create(project=project, scheduled_at=scheduled_at)
+    if project.is_published():
+        logger.info("Scheduling IATI validation for project %s", project.id)
+        scheduled_at = schedule_at if schedule_at else now() + DEFAULT_SCHEDULE_DELAY_TIME
+        pending_jobs = IatiActivityValidationJob.objects.filter(project=project, started_at=None)
+        if pending_jobs.exists():
+            job = pending_jobs.first()
+            job.scheduled_at = scheduled_at
+            job.save(update_fields=['scheduled_at'])
+        else:
+            IatiActivityValidationJob.objects.create(project=project, scheduled_at=scheduled_at)
 
     # Ensure that even if the job for the external check doesn't run, that the internal one will
     project.run_iati_checks = True


Test patch:
diff --git a/akvo/rsr/tests/usecases/test_schedule_iati_validation.py b/akvo/rsr/tests/usecases/test_schedule_iati_validation.py
--- a/akvo/rsr/tests/usecases/test_schedule_iati_validation.py
+++ b/akvo/rsr/tests/usecases/test_schedule_iati_validation.py
@@ -15,6 +15,12 @@ class ScheduleIatiActivityValidationTestCase(BaseTestCase):
     def setUp(self):
         self.project = self.create_project('Test project')
 
+    def test_no_job_for_unpublished_project(self):
+        schedule_at = now() + timedelta(minutes=1)
+        self.project.unpublish()
+        schedule_iati_activity_validation(self.project, schedule_at)
+        self.assertEqual(0, IatiActivityValidationJob.objects.filter(project=self.project).count())
+
     def test_add_new_job(self):
         schedule_at = now() + timedelta(minutes=1)
         schedule_iati_activity_validation(self.project, schedule_at)
Repository: sublimelsp/LSP

Issue:
Implement the `initialized` notification
Some servers such as [Julia language server](https://github.com/JuliaEditorSupport/LanguageServer.jl) requires an `Initialized` notification to order to work.

https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#new-initialized-notification


Discussion:

Resolving patch:
diff --git a/main.py b/main.py
--- a/main.py
+++ b/main.py
@@ -163,6 +163,10 @@ def __init__(self, method, params):
         self.params = params
         self.jsonrpc = "2.0"
 
+    @classmethod
+    def initialized(cls):
+        return Notification("initialized", None)
+
     @classmethod
     def didOpen(cls, params):
         return Notification("textDocument/didOpen", params)
@@ -803,6 +807,8 @@ def handle_initialize_result(result, client, window, config):
         window.status_message("{} initialized".format(config.name))
     didopen_after_initialize = list()
 
+    client.send_notification(Notification.initialized())
+
 
 stylesheet = '''
             <style>


Test patch:
Repository: sublimelsp/LSP

Issue:
Send correct client capabilities to server
applyEdit on workspace, synchronization on textDocument are incomplete.


Discussion:

Resolving patch:
diff --git a/main.py b/main.py
--- a/main.py
+++ b/main.py
@@ -1479,7 +1479,13 @@ def start_client(window: sublime.Window, config: ClientConfig):
                         "completionItem": {
                             "snippetSupport": True
                         }
+                    },
+                    "synchronization": {
+                        "didSave": True
                     }
+                },
+                "workspace": {
+                    "applyEdit": True
                 }
             }
         }


Test patch:
Repository: sublimelsp/LSP

Issue:
Expand variables in language server command setting
As described in #27, PHP's language server can be installed globally in the user's home, or local to the project.

It is a minor effort for the user to fill in the absolute path, but if we support `~` we can provide default or copy-paste-able configuration for more language servers.
Language servers installed per-project cannot be achieved unless we expand `$project_path` etc.


Discussion:
SublimeLinter's behaviour might be useful to copy here: https://github.com/SublimeLinter/SublimeLinter3/blob/a5f6c28ac7d88bfe28d524f6c2a6c2ed6b563cbc/lint/linter.py#L522

Resolving patch:
diff --git a/main.py b/main.py
--- a/main.py
+++ b/main.py
@@ -1463,7 +1463,11 @@ def start_client(window: sublime.Window, config: ClientConfig):
         if show_status_messages:
             window.status_message("Starting " + config.name + "...")
         debug("starting in", project_path)
-        client = start_server(config.binary_args, project_path)
+
+        variables = window.extract_variables()
+        expanded_args = list(sublime.expand_variables(os.path.expanduser(arg), variables) for arg in config.binary_args)
+
+        client = start_server(expanded_args, project_path)
         if not client:
             window.status_message("Could not start" + config.name + ", disabling")
             debug("Could not start", config.binary_args, ", disabling")
@@ -1515,15 +1519,14 @@ def get_window_client(view: sublime.View, config: ClientConfig) -> Client:
 
 
 def start_server(server_binary_args, working_dir):
-    args = server_binary_args
-    debug("starting " + str(args))
+    debug("starting " + str(server_binary_args))
     si = None
     if os.name == "nt":
         si = subprocess.STARTUPINFO()  # type: ignore
         si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW  # type: ignore
     try:
         process = subprocess.Popen(
-            args,
+            server_binary_args,
             stdin=subprocess.PIPE,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,


Test patch:
Repository: sublimelsp/LSP

Issue:
Diagnostic hover blocks normal hover on entire line
Only the region where a diagnostic exist should show diagnostic details, rest of the line should function as normal


Discussion:

Resolving patch:
diff --git a/main.py b/main.py
--- a/main.py
+++ b/main.py
@@ -1638,9 +1638,9 @@ def is_applicable(cls, settings):
     def on_hover(self, point, hover_zone):
         if hover_zone != sublime.HOVER_TEXT or self.view.is_popup_visible():
             return
-        line_diagnostics = get_line_diagnostics(self.view, point)
-        if line_diagnostics:
-            self.show_diagnostics_hover(point, line_diagnostics)
+        point_diagnostics = get_point_diagnostics(self.view, point)
+        if point_diagnostics:
+            self.show_diagnostics_hover(point, point_diagnostics)
         else:
             self.request_symbol_hover(point)
 
@@ -2009,6 +2009,14 @@ def get_line_diagnostics(view, point):
     )
 
 
+def get_point_diagnostics(view, point):
+    diagnostics = get_diagnostics_for_view(view)
+    return tuple(
+        diagnostic for diagnostic in diagnostics
+        if diagnostic.range.to_region(view).contains(point)
+    )
+
+
 def get_diagnostics_for_view(view: sublime.View) -> 'List[Diagnostic]':
     window = view.window()
     file_path = view.file_name()


Test patch: