anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: zalando/patroni
Issue: failover fails if master is down and slave is not 'healthiest'

I've had a sittuation where I deliberately shut down the only slave and then the master. I then 'lost' the master and restarted the slave, but it refused to become master because it was:
'Following a different leader because i am not the healthiest node'. 
Except that there was no other node (the former master was lost, no other slave exists.) I am not entirely sure why it considered itself unhealthy, but manually promoting with pg_ctl promote worked and got the cluster back up and running. 
I'm afraid I don't have enough details to reproduce the scenario. If I try to replicate what I did again it just works fine. 


Changed files:
patroni/postgresql.py

diff --git a/patroni/postgresql.py b/patroni/postgresql.py
index a5b1e16..909a120 100644
--- a/patroni/postgresql.py
+++ b/patroni/postgresql.py
@@ -469,17 +469,15 @@ class Postgresql(object):
                     return pattern and (pattern in line)
         return not pattern
 
-    def write_recovery_conf(self, leader, bootstrap=False):
+    def write_recovery_conf(self, leader):
         with open(self.recovery_conf, 'w') as f:
-            f.write("""standby_mode = 'on'
-recovery_target_timeline = 'latest'
-""")
+            f.write("standby_mode = 'on'\\nrecovery_target_timeline = 'latest'\\n")
             if leader and leader.conn_url:
-                f.write("""primary_conninfo = '{0}'\\n""".format(self.primary_conninfo(leader.conn_url)))
+                f.write("primary_conninfo = '{0}'\\n".format(self.primary_conninfo(leader.conn_url)))
                 if self.use_slots:
-                    f.write("""primary_slot_name = '{0}'\\n""".format(self.name))
-            if (leader and leader.conn_url) or bootstrap:
-                for name, value in self.config.get('recovery_conf', {}).items():
+                    f.write("primary_slot_name = '{0}'\\n".format(self.name))
+            for name, value in self.config.get('recovery_conf', {}).items():
+                if name not in ('standby_mode', 'recovery_target_timeline', 'primary_conninfo', 'primary_slot_name'):
                     f.write("{0} = '{1}'\\n".format(name, value))
 
     def rewind(self, leader):
@@ -729,7 +727,7 @@ $$""".format(name, options), name, password, password)
         else:
             if self.sync_replica(clone_member):
                 self.restore_configuration_files()
-                self.write_recovery_conf(clone_member, True)
+                self.write_recovery_conf(clone_member)
                 ret = self.start()
         return ret
Repository: wireservice/csvkit
Issue: local variable 'j' referenced before assignment

In table.py on line 237, I had to add j = 0 to define the variable J in order to get csvkit to work in my environment. 
Is this a bug, or did I do something else wrong? 
The subject line was the error I receieved for all of the utilities like csvstat, and csvsql. 
My change: 
        for i, row in enumerate(rows):
-->       j = 0
            for j, d in enumerate(row):

Thank you, 

Doug


Changed files:
csvkit/table.py, tests/test_table.py

diff --git a/csvkit/table.py b/csvkit/table.py
index c2824f1..fcb0feb 100644
--- a/csvkit/table.py
+++ b/csvkit/table.py
@@ -234,6 +234,8 @@ class Table(list):
         width = len(data_columns)
 
         for i, row in enumerate(rows):
+            j = 0
+
             for j, d in enumerate(row):
                 try:
                     data_columns[j].append(row[column_ids[j]].strip())
diff --git a/tests/test_table.py b/tests/test_table.py
index f559e70..39f952d 100644
--- a/tests/test_table.py
+++ b/tests/test_table.py
@@ -86,6 +86,9 @@ class TestTable(unittest.TestCase):
         self.assertEqual(t[3][0], 'True')
         self.assertEqual(type(t[3][0]), six.text_type)
 
+    def test_from_csv_empty_file(self):
+        table.Table.from_csv(six.StringIO('\\n\\n'))
+
     def test_to_csv(self):
         with open('examples/testfixed_converted.csv', 'r') as f:
             contents = f.read()
Repository: wireservice/csvkit
Issue: csvstat chokes on "inf" numbers

For the following input CSV (yes, 1 row, 1 column, 1 header):

    headerA
    inf

`csvstat` (no other argument besides input.csv) outputs:

```
  1. "columnA"

	Type of data:          Number
	Contains null values:  False
	Unique values:         1
	Most common values:    [<class 'decimal.InvalidOperation'>]
```

This happens because `python-babel` (in Debian system 2.4.0) number formatting function chokes on Infinity, e.g.:
```
from decimal import Decimal
from babel.numbers import format_decimal
format_decimal(Decimal("Infinity"))
```

`format_decimal` is called from `csvstat.py:269` (in Debian system 1.0.2-1).

Interestingly `csvstat --freq` outputs:
```
{ "Infinity": 1 }
```


Changed files:
csvkit/utilities/csvstat.py

diff --git a/csvkit/utilities/csvstat.py b/csvkit/utilities/csvstat.py
index 9aecdc9..fb1ecb2 100644
--- a/csvkit/utilities/csvstat.py
+++ b/csvkit/utilities/csvstat.py
@@ -190,7 +190,7 @@ class CSVStat(CSVKitUtility):
                     op = OPERATIONS[op_name]['aggregation']
                     stat = table.aggregate(op(column_id))
 
-                    if isinstance(stat, Decimal):
+                    if isinstance(stat, Decimal) and stat.is_finite():
                         stat = format_decimal(stat, locale=agate.config.get_option('default_locale'))
             except:
                 stat = None
@@ -224,7 +224,7 @@ class CSVStat(CSVKitUtility):
                         op = op_data['aggregation']
                         v = table.aggregate(op(column_id))
 
-                        if isinstance(v, Decimal):
+                        if isinstance(v, Decimal) and v.is_finite():
                             v = format_decimal(v, locale=agate.config.get_option('default_locale'))
 
                         stats[op_name] = v
@@ -268,7 +268,7 @@ class CSVStat(CSVKitUtility):
                         if isinstance(column.data_type, agate.Number):
                             v = row[column_name]
 
-                            if isinstance(v, Decimal):
+                            if isinstance(v, Decimal) and v.is_finite():
                                 v = format_decimal(v, locale=agate.config.get_option('default_locale'))
                         else:
                             v = six.text_type(row[column_name])
Repository: frappe/frappe
Issue: Create block in workspace

### Information about bug

### App Versions
```
{
	"erpnext": "14.27.2",
	"frappe": "14.39.0",
	"hrms": "14.4.3",
	"india_compliance": "14.10.1",
	"payments": "0.0.1"
}
```
### Route
```
Workspaces/Home
```
### Traceback
```
Traceback (most recent call last):
  File "apps/frappe/frappe/app.py", line 66, in application
    response = frappe.api.handle()
  File "apps/frappe/frappe/api.py", line 54, in handle
    return frappe.handler.handle()
  File "apps/frappe/frappe/handler.py", line 47, in handle
    data = execute_cmd(cmd)
  File "apps/frappe/frappe/handler.py", line 85, in execute_cmd
    return frappe.call(method, **frappe.form_dict)
  File "apps/frappe/frappe/__init__.py", line 1608, in call
    return fn(*args, **newargs)
  File "apps/frappe/frappe/desk/search.py", line 35, in search_link
    search_widget(
  File "apps/frappe/frappe/desk/search.py", line 106, in search_widget
    raise e
  File "apps/frappe/frappe/desk/search.py", line 83, in search_widget
    frappe.response["values"] = frappe.call(
  File "apps/frappe/frappe/__init__.py", line 1608, in call
    return fn(*args, **newargs)
  File "apps/frappe/frappe/desk/doctype/custom_html_block/custom_html_block.py", line 18, in get_custom_blocks_for_user
    condition_query = frappe.qb.get_query(customHTMLBlock)
AttributeError: type object 'MariaDB' has no attribute 'get_query'

```
### Request Data
```
{
	"type": "POST",
	"args": {
		"txt": "",
		"doctype": "Custom HTML Block",
		"reference_doctype": "",
		"query": "frappe.desk.doctype.custom_html_block.custom_html_block.get_custom_blocks_for_user"
	},
	"headers": {},
	"error_handlers": {},
	"url": "/api/method/frappe.desk.search.search_link"
}
```
### Response Data
```
{
	"exception": "AttributeError: type object 'MariaDB' has no attribute 'get_query'"
}
```

### Module

accounts, other

### Version

{
	"erpnext": "14.27.2",
	"frappe": "14.39.0",
	"hrms": "14.4.3",
	"india_compliance": "14.10.1",
	"payments": "0.0.1"
}

### Installation method

FrappeCloud

### Relevant log output / Stack trace / Full Error Message.

_No response_

Changed files:
frappe/desk/doctype/custom_html_block/custom_html_block.py

diff --git a/frappe/desk/doctype/custom_html_block/custom_html_block.py b/frappe/desk/doctype/custom_html_block/custom_html_block.py
index 3ce7966f6a..493b7ee4e4 100644
--- a/frappe/desk/doctype/custom_html_block/custom_html_block.py
+++ b/frappe/desk/doctype/custom_html_block/custom_html_block.py
@@ -30,7 +30,7 @@ def get_custom_blocks_for_user(doctype, txt, searchfield, start, page_len, filte
 	# return logged in users private blocks and all public blocks
 	customHTMLBlock = DocType("Custom HTML Block")
 
-	condition_query = frappe.qb.get_query(customHTMLBlock)
+	condition_query = frappe.qb.from_(customHTMLBlock)
 
 	return (
 		condition_query.select(customHTMLBlock.name).where(
Repository: kevinmusgrave/pytorch-metric-learning
Issue: VICReg requires torch >= 1.10

Hi,

The torch.cov in the covariance_loss function requires torch >= 1.10.
Replacing:
>      _, D = emb.size()
>      cov_emb = torch.cov(emb.T)
>      cov_ref_emb = torch.cov(ref_emb.T)
to:
>      batch_size, D = emb.size()
>      cov_emb = (emb.T @ emb) / (batch_size - 1)
>      cov_ref_emb = (ref_emb.T @ ref_emb) / (batch_size - 1)
would make it compatible with older versions as well.

Another remark is that in the reference implementation, the variance loss is divided by 2: https://github.com/facebookresearch/vicreg/blob/5e7b38f4586384bbb0d9a035352fab1d8f03b3b4/main_vicreg.py#L207
Was it intentionally left out, or am I missing something here?

Changed files:
src/pytorch_metric_learning/losses/vicreg_loss.py, tests/losses/test_vicreg_loss.py

diff --git a/src/pytorch_metric_learning/losses/vicreg_loss.py b/src/pytorch_metric_learning/losses/vicreg_loss.py
index 0be29b2..e539ae9 100644
--- a/src/pytorch_metric_learning/losses/vicreg_loss.py
+++ b/src/pytorch_metric_learning/losses/vicreg_loss.py
@@ -70,12 +70,14 @@ class VICRegLoss(BaseMetricLossFunction):
     def variance_loss(self, emb, ref_emb):
         std_emb = torch.sqrt(emb.var(dim=0) + self.eps)
         std_ref_emb = torch.sqrt(ref_emb.var(dim=0) + self.eps)
-        return F.relu(1 - std_emb), F.relu(1 - std_ref_emb)
+        return F.relu(1 - std_emb) / 2, F.relu(1 - std_ref_emb) / 2 # / 2 for averaging
 
     def covariance_loss(self, emb, ref_emb):
-        _, D = emb.size()
-        cov_emb = torch.cov(emb.T)
-        cov_ref_emb = torch.cov(ref_emb.T)
+        N, D = emb.size()
+        emb = emb - emb.mean(dim=0)
+        ref_emb = ref_emb - ref_emb.mean(dim=0)
+        cov_emb = (emb.T @ emb) / (N - 1)
+        cov_ref_emb = (ref_emb.T @ ref_emb) / (N - 1)
 
         diag = torch.eye(D, device=cov_emb.device)
         cov_loss = (
diff --git a/tests/losses/test_vicreg_loss.py b/tests/losses/test_vicreg_loss.py
index 102ae7a..7395c2d 100644
--- a/tests/losses/test_vicreg_loss.py
+++ b/tests/losses/test_vicreg_loss.py
@@ -42,6 +42,7 @@ class TestVICRegLoss(unittest.TestCase):
                     variance_loss = torch.mean(F.relu(1 - std_emb)) + torch.mean(
                         F.relu(1 - std_ref_emb)
                     )
+                    variance_loss = variance_loss / 2 # for averaging
 
                     # covariance loss, a more manual version
                     N, D = emb.size()
Repository: kevinmusgrave/pytorch-metric-learning
Issue: Gradient in distributed training

Here is the current implementation of the distributed wrapper.

https://github.com/KevinMusgrave/pytorch-metric-learning/blob/6bfa880b8d2acafb7c6d52041d2bb14ed41aee76/src/pytorch_metric_learning/utils/distributed.py#L35-L59

But according to this [blog](https://amsword.medium.com/gradient-backpropagation-with-torch-distributed-all-gather-9f3941a381f8), the loss function should be multiplied by `world_size`. 

What do you think about it? Maybe I can create a PR to fix it.

Changed files:
tests/utils/test_distributed.py, src/pytorch_metric_learning/utils/distributed.py, src/pytorch_metric_learning/__init__.py

diff --git a/src/pytorch_metric_learning/__init__.py b/src/pytorch_metric_learning/__init__.py
index a7be658..f2bdfbe 100644
--- a/src/pytorch_metric_learning/__init__.py
+++ b/src/pytorch_metric_learning/__init__.py
@@ -1 +1 @@
-__version__ = "1.0.0.dev2"
+__version__ = "1.0.0.dev3"
diff --git a/src/pytorch_metric_learning/utils/distributed.py b/src/pytorch_metric_learning/utils/distributed.py
index e6108c3..9e11955 100644
--- a/src/pytorch_metric_learning/utils/distributed.py
+++ b/src/pytorch_metric_learning/utils/distributed.py
@@ -56,7 +56,8 @@ class DistributedLossWrapper(torch.nn.Module):
 
     def forward(self, embeddings, labels, *args, **kwargs):
         embeddings, labels = all_gather_embeddings_labels(embeddings, labels)
-        return self.loss(embeddings, labels, *args, **kwargs)
+        world_size = torch.distributed.get_world_size()
+        return world_size * self.loss(embeddings, labels, *args, **kwargs)
 
 
 class DistributedMinerWrapper(torch.nn.Module):
diff --git a/tests/utils/test_distributed.py b/tests/utils/test_distributed.py
index 8905bcd..9878704 100644
--- a/tests/utils/test_distributed.py
+++ b/tests/utils/test_distributed.py
@@ -132,7 +132,7 @@ def single_process_function(
             correct_loss_size = original_loss_fn.reducer.losses_size
             assert loss_size == correct_loss_size
 
-    assert torch.isclose(loss, torch.from_numpy(correct_loss).to(device))
+    assert torch.isclose(loss, torch.from_numpy(correct_loss).to(device) * world_size)
     assert miner_fn.miner.num_pos_pairs == original_miner_fn.num_pos_pairs
     assert miner_fn.miner.num_neg_pairs == original_miner_fn.num_neg_pairs
     for i in range(len(correct_indices_tuple)):
@@ -245,10 +245,7 @@ class TestDistributedLossWrapper(unittest.TestCase):
                     all_outputs, all_labels, correct_indices_tuple
                 )
 
-                if TEST_DEVICE == torch.device("cpu"):
-                    correct_loss.backward(retain_graph=True)
-                else:
-                    (correct_loss / world_size).backward(retain_graph=True)
+                correct_loss.backward(retain_graph=True)
                 optimizer.step()
                 if not is_tuple_loss:
                     for p in original_loss_fn.parameters():