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

Issue:
extend convert_bool in gexf.py and graphml.py to all valid boolean 
Follow-up to pull request #971 - recommend extending `convert_bool` to include true/false support for literal 0/1 and the string variants.
1. [graphml.py:224](https://github.com/networkx/networkx/blob/7d9682a07dcae30acab3c4841e33d31f727a3fb2/networkx/readwrite/graphml.py#L224)
2. [gexf.py:215](https://github.com/networkx/networkx/blob/87764469941cfa52a5aefc1b1b381a614b484c8d/networkx/readwrite/gexf.py#L215)

E.g., in [graphml.py:224](https://github.com/networkx/networkx/blob/7d9682a07dcae30acab3c4841e33d31f727a3fb2/networkx/readwrite/graphml.py#L224):

Old:

``` python
convert_bool={'true':True,'false':False,
              'True': True, 'False': False}
```

New:

``` python
convert_bool={'true':True,'false':False,
              'True': True, 'False': False
              '0': False, 0: False,
              '1': True, 1: True}
```

For reference, the [XML Schema Datatypes](http://www.w3.org/TR/xmlschema-2/#boolean) section on booleans.



Discussion:

Resolving patch:
diff --git a/networkx/readwrite/gexf.py b/networkx/readwrite/gexf.py
--- a/networkx/readwrite/gexf.py
+++ b/networkx/readwrite/gexf.py
@@ -212,7 +212,13 @@ class GEXF(object):
 
     xml_type = dict(types)
     python_type = dict(reversed(a) for a in types)
-    convert_bool={'false': False, 'False': False, 'true': True, 'True': True}
+    # http://www.w3.org/TR/xmlschema-2/#boolean
+    convert_bool = {
+        'true': True, 'false': False,
+        'True': True, 'False': False,
+        '0': False, 0: False,
+        '1': False, 1: True
+    }
 
 #    try:
 #        register_namespace = ET.register_namespace
@@ -643,7 +649,7 @@ def make_graph(self, graph_xml):
             G.graph['mode']='dynamic'
         else:
             G.graph['mode']='static'
-            
+
         # timeformat
         self.timeformat=graph_xml.get('timeformat')
         if self.timeformat == 'date':
diff --git a/networkx/readwrite/graphml.py b/networkx/readwrite/graphml.py
--- a/networkx/readwrite/graphml.py
+++ b/networkx/readwrite/graphml.py
@@ -221,10 +221,13 @@ class GraphML(object):
 
     xml_type = dict(types)
     python_type = dict(reversed(a) for a in types)
-    convert_bool={'true':True,'false':False,
-                  'True': True, 'False': False}
-
-
+    # http://www.w3.org/TR/xmlschema-2/#boolean
+    convert_bool = {
+        'true': True, 'false': False,
+        'True': True, 'False': False,
+        '0': False, 0: False,
+        '1': False, 1: True
+    }
 
 class GraphMLWriter(GraphML):
     def __init__(self, graph=None, encoding="utf-8",prettyprint=True):


Test patch:
Repository: networkx/networkx

Issue:
average_clustering  count_zeros parameter True by default but stated as False in docstring 
Compare:

https://github.com/networkx/networkx/blob/a822b491c6b53a2819915a8c620e97a36ba6c060/networkx/algorithms/cluster.py#L117

with:

https://github.com/networkx/networkx/blob/a822b491c6b53a2819915a8c620e97a36ba6c060/networkx/algorithms/cluster.py#L139

The former gives the correct indication that `count_zeros` is `True` by default, while the latter which one might come across while browsing the documentation suggests incorrectly the opposite i.e. that `count_zeros` is `False` by default.

I'd suggest that documenting the default value manually in the docstring is redundant anyway and so should be omitted completely rather than corrected to read `True`.

I can fix this.



Discussion:

Resolving patch:
diff --git a/networkx/algorithms/cluster.py b/networkx/algorithms/cluster.py
--- a/networkx/algorithms/cluster.py
+++ b/networkx/algorithms/cluster.py
@@ -136,7 +136,7 @@ def average_clustering(G, nodes=None, weight=None, count_zeros=True):
        The edge attribute that holds the numerical value used as a weight.
        If None, then each edge has weight 1.
 
-    count_zeros : bool (default=False)       
+    count_zeros : bool
        If False include only the nodes with nonzero clustering in the average.
 
     Returns


Test patch:
Repository: networkx/networkx

Issue:
waxman_model's domain problem
I think `waxman_model` doesn't process the domain correctly.

networkx/geometric.py (version 1.9.1) ---

Original version:

``` python
def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0,0,1,1)):
  ...
    for n in G:
        G.node[n]['pos']=((xmin + (xmax-xmin))*random.random(),
                          (ymin + (ymax-ymin))*random.random())
```

Fixed version:

``` python
def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0,0,1,1)):
  ...
    for n in G:
        G.node[n]['pos']=(xmin + ((xmax-xmin)*random.random()),
                          ymin + ((ymax-ymin)*random.random()))
```



Discussion:

Resolving patch:
diff --git a/networkx/generators/geometric.py b/networkx/generators/geometric.py
--- a/networkx/generators/geometric.py
+++ b/networkx/generators/geometric.py
@@ -242,8 +242,8 @@ def waxman_graph(n, alpha=0.4, beta=0.1, L=None, domain=(0,0,1,1)):
     G.add_nodes_from(range(n))
     (xmin,ymin,xmax,ymax)=domain
     for n in G:
-        G.node[n]['pos']=((xmin + (xmax-xmin))*random.random(),
-                          (ymin + (ymax-ymin))*random.random())
+        G.node[n]['pos']=(xmin + ((xmax-xmin)*random.random()),
+                          ymin + ((ymax-ymin)*random.random()))
     if L is None:
         # find maximum distance L between two nodes
         l = 0


Test patch:
Repository: networkx/networkx

Issue:
Breath First Search: source parameter is not optional (but the docstrings say so)
The docstrings of the functions in `networkx/algorithms/traversal/breadth_first_search.py`
all claim that the `source` parameter is optional, while the code says otherwise.



Discussion:

Resolving patch:
diff --git a/networkx/algorithms/traversal/breadth_first_search.py b/networkx/algorithms/traversal/breadth_first_search.py
--- a/networkx/algorithms/traversal/breadth_first_search.py
+++ b/networkx/algorithms/traversal/breadth_first_search.py
@@ -17,7 +17,7 @@ def bfs_edges(G, source, reverse=False):
     ----------
     G : NetworkX graph
 
-    source : node, optional
+    source : node
        Specify starting node for breadth-first search and return edges in
        the component reachable from source.
 
@@ -40,9 +40,6 @@ def bfs_edges(G, source, reverse=False):
     -----
     Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
     by D. Eppstein, July 2004.
-
-    If a source is not specified then a source is chosen arbitrarily and
-    repeatedly until all components in the graph are searched.
     """
     if reverse and isinstance(G, nx.DiGraph):
         neighbors = G.predecessors_iter
@@ -69,7 +66,7 @@ def bfs_tree(G, source, reverse=False):
     ----------
     G : NetworkX graph
 
-    source : node, optional
+    source : node
        Specify starting node for breadth-first search and return edges in
        the component reachable from source.
 
@@ -92,9 +89,6 @@ def bfs_tree(G, source, reverse=False):
     -----
     Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
     by D. Eppstein, July 2004.
-
-    If a source is not specified then a source is chosen arbitrarily and
-    repeatedly until all components in the graph are searched.
     """
     T = nx.DiGraph()
     T.add_node(source)
@@ -108,7 +102,7 @@ def bfs_predecessors(G, source):
     ----------
     G : NetworkX graph
 
-    source : node, optional
+    source : node
        Specify starting node for breadth-first search and return edges in
        the component reachable from source.
 
@@ -128,9 +122,6 @@ def bfs_predecessors(G, source):
     -----
     Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
     by D. Eppstein, July 2004.
-
-    If a source is not specified then a source is chosen arbitrarily and
-    repeatedly until all components in the graph are searched.
     """
     return dict((t,s) for s,t in bfs_edges(G,source))
 
@@ -141,7 +132,7 @@ def bfs_successors(G, source):
     ----------
     G : NetworkX graph
 
-    source : node, optional
+    source : node
        Specify starting node for breadth-first search and return edges in
        the component reachable from source.
 
@@ -161,9 +152,6 @@ def bfs_successors(G, source):
     -----
     Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py
     by D. Eppstein, July 2004.
-
-    If a source is not specified then a source is chosen arbitrarily and
-    repeatedly until all components in the graph are searched.
     """
     d = defaultdict(list)
     for s,t in bfs_edges(G,source):


Test patch:
Repository: networkx/networkx

Issue:
Function add_nodes_from does not use adjlist_dict_factory properly
While I was reading through the code of the Graph class, I have found what I think must be a bug in the implementation.
Look at the code below:

```
python
for n in nodes:
  # keep all this inside try/except because
  # CPython throws TypeError on n not in self.succ,
  # while pre-2.7.5 ironpython throws on self.succ[n] 
  try:
    if n not in self.node:
      self.adj[n] = self.adjlist_dict_factory()
      self.node[n] = attr.copy()
    else:
      self.node[n].update(attr)
  except TypeError:
    nn,ndict = n
    if nn not in self.node:
      self.adj[nn] = {}
      newdict = attr.copy()
      newdict.update(ndict)
      self.node[nn] = newdict
    else:
      olddict = self.node[nn]
      olddict.update(attr)
      olddict.update(ndict)
```

So, the problem is with these two lines:
**self.adj[n] = self.adjlist_dict_factory()** in the try part of the code and
**self.adj[nn] = {}** after the except TypeError if the node is not present in the graph

Both assignments initialize in different ways the adjacency list for a node. I think this could lead to weird behavior when calling this function.



Discussion:

Resolving patch:
diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py
--- a/networkx/classes/graph.py
+++ b/networkx/classes/graph.py
@@ -519,7 +519,7 @@ def add_nodes_from(self, nodes, **attr):
             except TypeError:
                 nn,ndict = n
                 if nn not in self.node:
-                    self.adj[nn] = {}
+                    self.adj[nn] = self.adjlist_dict_factory()
                     newdict = attr.copy()
                     newdict.update(ndict)
                     self.node[nn] = newdict
@@ -860,7 +860,7 @@ def add_edges_from(self, ebunch, attr_dict=None, **attr):
                 u,v,dd = e
             elif ne==2:
                 u,v = e
-                dd = {}
+                dd = {} #doesnt need edge_attr_dict_factory
             else:
                 raise NetworkXError(\
                     "Edge tuple %s must be a 2-tuple or 3-tuple."%(e,))


Test patch:
Repository: networkx/networkx

Issue:
Added implementation of SimRank matrix of the graph.



Discussion:

Resolving patch:
diff --git a/networkx/relabel.py b/networkx/relabel.py
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -107,6 +107,8 @@ def _relabel_inplace(G, mapping):
             new = mapping[old]
         except KeyError:
             continue
+        if new == old:
+            continue
         try:
             G.add_node(new, attr_dict=G.node[old])
         except KeyError:


Test patch:
diff --git a/networkx/tests/test_relabel.py b/networkx/tests/test_relabel.py
--- a/networkx/tests/test_relabel.py
+++ b/networkx/tests/test_relabel.py
@@ -137,6 +137,13 @@ def test_relabel_nodes_multidigraph(self):
         assert_equal(sorted(G.edges()),
                      [('aardvark', 'bear'), ('aardvark', 'bear')])
 
+    def test_relabel_isolated_nodes_to_same(self):
+        G=Graph()
+        G.add_nodes_from(range(4))
+        mapping={1:1}
+        H=relabel_nodes(G, mapping, copy=False)
+        assert_equal(sorted(H.nodes()), list(range(4)))
+
     @raises(KeyError)
     def test_relabel_nodes_missing(self):
         G=Graph([('A','B'),('A','C'),('B','C'),('C','D')])
Repository: networkx/networkx

Issue:
Lose digraph ordering when creating a duplicate
I am seeing the following, which doesn't look right at all.

```
>>> import networkx as nx
>>> g = nx.OrderedDiGraph()
>>> g.add_node('a')
>>> g.add_node('b')
>>> g.add_node('c')
>>> list(g)
['a', 'b', 'c']
>>> g1 = nx.OrderedDiGraph(g)
>>> list(g1)
['a', 'c', 'b']
```

It seems the order is being lost when the graph is being copied (which is the recommended way to generate a new graph, if the prior one is frozen for example); this doesn't feel like what would be the expected result here.

```
$ pip freeze | grep networkx
networkx==1.10
$ python --version
Python 2.7.10
```



Discussion:
Trying to work around this using the convert routine directly, didn't seem to fix the issue.

```
>>> from networkx import convert
>>> g2 = convert.to_networkx_graph(g, create_using=nx.OrderedDiGraph())
>>> list(g2)
['a', 'c', 'b']
```

The following does seem to work, but likely isn't really a _good_ solution.

```
>>> g3 = nx.OrderedDiGraph()
>>> g3.add_nodes_from(g.nodes_iter())
>>> g3.add_edges_from(g.edges_iter())
>>> list(g3)
['a', 'b', 'c']
```

This looks like a bug.... Thanks for reporting it. I'll look into it.

Thanks!


Resolving patch:
diff --git a/networkx/convert.py b/networkx/convert.py
--- a/networkx/convert.py
+++ b/networkx/convert.py
@@ -89,10 +89,10 @@ def to_networkx_graph(data,create_using=None,multigraph_input=False):
             result= from_dict_of_dicts(data.adj,\
                     create_using=create_using,\
                     multigraph_input=data.is_multigraph())
-            if hasattr(data,'graph') and isinstance(data.graph,dict):
-                result.graph=data.graph.copy()
-            if hasattr(data,'node') and isinstance(data.node,dict):
-                result.node=dict( (n,dd.copy()) for n,dd in data.node.items() )
+            if hasattr(data,'graph'): # data.graph should be dict-like
+                result.graph.update(data.graph)
+            if hasattr(data,'node'): # data.node should be dict-like
+                result.node.update( (n,dd.copy()) for n,dd in data.node.items() )
             return result
         except:
             raise nx.NetworkXError("Input is not a correct NetworkX graph.")


Test patch:
diff --git a/networkx/tests/test_convert.py b/networkx/tests/test_convert.py
--- a/networkx/tests/test_convert.py
+++ b/networkx/tests/test_convert.py
@@ -215,3 +215,12 @@ def test_directed_to_undirected(self):
 
         assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges1)).edges(),edges1))
         assert_true(self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges2)).edges(),edges1))
+
+    def test_attribute_dict_integrity(self):
+        # we must not replace dict-like graph data structures with dicts 
+        G=OrderedGraph()
+        G.add_nodes_from("abc")
+        H=to_networkx_graph(G, create_using=OrderedGraph())
+        assert_equal(list(H.node),list(G.node))
+        H=OrderedDiGraph(G)
+        assert_equal(list(H.node),list(G.node))
Repository: networkx/networkx

Issue:
Minor inefficiency in dijkstra algorithms
The dijkstra algorithms seem to all have `c=count()` in them.  The variable `c` is used a few times, but never for anything that actually affects the calculation.  I suspect it was put in during some testing.  In my (limited) testing, it can be removed without altering any results.



Discussion:
It looks like c is used in the tuple that gets pushed onto the heap. So presumably the position in the heap will be different if we remove the `c` variable. Currently we push 3-tuples (uv-dist, next(c), u). If we push (uv-dist, u), and uv-dist is the same for two nodes, then the heap comparison will depend on comparison of nodes `u`.  We want to allow nodes that can't be compared.  I think this is the reason we include the value c here.  Maybe a comment in the code to that effect would be helpful. 


Resolving patch:
diff --git a/networkx/algorithms/shortest_paths/weighted.py b/networkx/algorithms/shortest_paths/weighted.py
--- a/networkx/algorithms/shortest_paths/weighted.py
+++ b/networkx/algorithms/shortest_paths/weighted.py
@@ -346,8 +346,10 @@ def _dijkstra(G, source, get_weight, pred=None, paths=None, cutoff=None,
     pop = heappop
     dist = {}  # dictionary of final distances
     seen = {source: 0}
+    # fringe is heapq with 3-tuples (distance,c,node)
+    # use the count c to avoid comparing nodes (may not be able to)
     c = count()
-    fringe = []  # use heapq with (distance,label) tuples
+    fringe = []
     push(fringe, (0, next(c), source))
     while fringe:
         (d, _, v) = pop(fringe)


Test patch:
Repository: networkx/networkx

Issue:
find_cycle() raises NetworkXNoCycle, contrary to doc
The [doc for find_cycle() says](https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.cycles.find_cycle.html#networkx.algorithms.cycles.find_cycle)

> edges – A list of directed edges indicating the path taken for the loop. If no cycle is found, then edges will be an empty list.

But the following snippet raises NetworkXNoCycle:

``` python
import networkx
from networkx.algorithms.cycles import find_cycle
G = networkx.DiGraph([(0,1), (1,2)])
find_cycle(G)
```

I'm using networkx 1.10.



Discussion:
Yup, looks like no changes were made to the docs in d053488b1331e6f0205fafe4db198f6a815816fe where `NetworkXNoCycle` was implemented.


Resolving patch:
diff --git a/networkx/algorithms/cycles.py b/networkx/algorithms/cycles.py
--- a/networkx/algorithms/cycles.py
+++ b/networkx/algorithms/cycles.py
@@ -351,7 +351,7 @@ def find_cycle(G, source=None, orientation='original'):
     -------
     edges : directed edges
         A list of directed edges indicating the path taken for the loop. If
-        no cycle is found, then ``edges`` will be an empty list. For graphs, an
+        no cycle is found, then an exception is raised. For graphs, an
         edge is of the form (u, v) where ``u`` and ``v`` are the tail and head
         of the edge as determined by the traversal. For multigraphs, an edge is
         of the form (u, v, key), where ``key`` is the key of the edge. When the
@@ -362,6 +362,11 @@ def find_cycle(G, source=None, orientation='original'):
         direction. When the direction is forward, the value of ``direction``
         is 'forward'. When the direction is reverse, the value of ``direction``
         is 'reverse'.
+        
+    Raises
+    ------
+    NetworkXNoCycle
+        If no cycle was found.
 
     Examples
     --------


Test patch:
Repository: networkx/networkx

Issue:
Current-flow betweenness for directed graphs Exception ? 
Hi guys

Did networkx provides algorithms for calculating the node (or edge) current-flow betweenness for _**directed graphs**_?

I have try to call the function `edge_current_flow_betweenness_centrality`, but it raises a Exception saying "not working for directed graphs", but the document

> edge_current_flow_betweenness_centrality(G, normalized=True, weight=’weight’, dtype=<type ‘float’>, solver=’full’)
> Compute current-flow betweenness centrality for edges.
> Current-flow betweenness centrality uses an electrical current model for information spreading in contrast to betweenness centrality which uses shortest paths.
> Current-flow betweenness centrality is also known as random-walk betweenness centrality 36.
> **Parameters**
> - **G** (graph) – A NetworkX graph
> - normalized (bool, optional (default=True)) – If True the betweenness values are normalized
>   by 2/[(n-1)(n-2)] where n is the number of nodes in G.
> - **weight** (string or None, optional (default=’weight’)) – Key for edge data used as the >edge
>   weight. If None, then use 1 as each edge weight.
> - **dtype** (data type (float)) – Default data type for internal matrices. Set to np.float32 for
>   lower memory consumption.
> - **solver** (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
>   Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least >memory).
> - **Returns nodes** – Dictionary of edge tuples with betweenness centrality as the value.
> - **Return** type dictionary

does not say anything about the Exception ?
Perhaps, this exception should be noted in the document ? something like _**Raise Exception: if graph is not undirected**_



Discussion:

Resolving patch:
diff --git a/networkx/algorithms/centrality/current_flow_betweenness.py b/networkx/algorithms/centrality/current_flow_betweenness.py
--- a/networkx/algorithms/centrality/current_flow_betweenness.py
+++ b/networkx/algorithms/centrality/current_flow_betweenness.py
@@ -283,6 +283,13 @@ def edge_current_flow_betweenness_centrality(G, normalized=True,
     nodes : dictionary
        Dictionary of edge tuples with betweenness centrality as the value.
 
+    Raises
+    ------
+    NetworkXError
+        The algorithm does not support DiGraphs.
+        If the input graph is an instance of DiGraph class, NetworkXError
+        is raised.
+
     See Also
     --------
     betweenness_centrality


Test patch:
Repository: networkx/networkx

Issue:
maximal_matching and self loops
`maximal_matching` does allow self-loops

``` py
>>> G = nx.Graph([[1,1]])
>>> nx.matching.maximal_matching(G)
{(1, 1)}
```

whereas `max_weight_matching` does not

``` py
>>> nx.matching.max_weight_matching(G)
{}
```

Is this expected behaviour? If not, a simple `u != v` check should fix it.



Discussion:
Interesting.  I don't know what the correct definition is.  But we should be consistent.
Maybe don't allow self loops?  If we document that and give an example of how to remove self loops then both cases should be covered.

Anyone have comments on how to resolve this?  

I suggest not allowing self-loops in maximal matchings. Consider the path graph on two nodes with self-loops on both nodes. If self-loops are allowed, the maximum matching would be the set of two self-loops, which is a little surprising. This may be desirable in certain situations, but I think we should leave that as an example in the documentation if necessary.


Resolving patch:
diff --git a/networkx/algorithms/matching.py b/networkx/algorithms/matching.py
--- a/networkx/algorithms/matching.py
+++ b/networkx/algorithms/matching.py
@@ -46,7 +46,7 @@ def maximal_matching(G):
     for u,v in G.edges():
         # If the edge isn't covered, add it to the matching
         # then remove neighborhood of u and v from consideration.
-        if u not in nodes and v not in nodes:
+        if u not in nodes and v not in nodes and u!=v:
             matching.add((u,v))
             nodes.add(u)
             nodes.add(v)


Test patch:
diff --git a/networkx/algorithms/tests/test_matching.py b/networkx/algorithms/tests/test_matching.py
--- a/networkx/algorithms/tests/test_matching.py
+++ b/networkx/algorithms/tests/test_matching.py
@@ -247,6 +247,20 @@ def test_maximal_matching():
     vset = set(u for u, v in matching)
     vset = vset | set(v for u, v in matching)
 
+    for edge in graph.edges():
+        u, v = edge
+        ok_(len(set([v]) & vset) > 0 or len(set([u]) & vset) > 0, \
+                "not a proper matching!")
+    graph = nx.Graph()
+    graph.add_edge(1, 1)
+    graph.add_edge(1, 2)
+    graph.add_edge(2, 2)
+    graph.add_edge(2, 3)
+    matching = nx.maximal_matching(graph)
+    assert(len(matching)==1)
+    vset = set(u for u, v in matching)
+    vset = vset | set(v for u, v in matching)
+
     for edge in graph.edges():
         u, v = edge
         ok_(len(set([v]) & vset) > 0 or len(set([u]) & vset) > 0, \