nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: frictionlessdata/tabulator-py
Pull request #215 (2017-10-30 11:17:15)

Fixed csv dialect bug with sniffing
- fixes https://github.com/frictionlessdata/goodtables-py/issues/228

roll: @amercader 
Please take a look.

Patch:
diff --git a/tabulator/parsers/csv.py b/tabulator/parsers/csv.py
index 3774492..70dc859 100644
--- a/tabulator/parsers/csv.py
+++ b/tabulator/parsers/csv.py
@@ -119,7 +119,8 @@ class CSVParser(Parser):
             if not dialect.escapechar:
                 dialect.doublequote = True
         except csv.Error:
-            dialect = csv.excel
+            class dialect(csv.excel):
+                pass
         for key, value in self.__options.items():
             setattr(dialect, key, value)
 


Test patch:
diff --git a/tests/formats/test_csv.py b/tests/formats/test_csv.py
index 7f9ce58..e7430b7 100644
--- a/tests/formats/test_csv.py
+++ b/tests/formats/test_csv.py
@@ -5,6 +5,7 @@ from __future__ import absolute_import
 from __future__ import unicode_literals
 
 import io
+import pytest
 from mock import Mock
 from tabulator import Stream
 from tabulator.parsers.csv import CSVParser
@@ -137,6 +138,15 @@ def test_stream_csv_detect_delimiter_pipe():
         assert stream.read() == [['a1', 'b1'], ['a2', 'b2']]
 
 
+def test_stream_csv_dialect_should_not_persist_if_sniffing_fails_issue_goodtables_228():
+    source1 = 'a;b;c\n#comment'
+    source2 = 'a,b,c\n#comment'
+    with Stream(source1, scheme='text', format='csv', headers=1, delimiter=';') as stream:
+        assert stream.headers == ['a', 'b', 'c']
+    with Stream(source2, scheme='text', format='csv', headers=1) as stream:
+        assert stream.headers == ['a', 'b', 'c']
+
+
 # Parser
 
 def test_parser_csv():
Repository: frictionlessdata/tabulator-py
Pull request #251 (2018-10-03 14:49:01)

Extract format from URL query string
I'm often dealing with URLs like https://domain.tls/path/to/resource?format=csv

Currently, `tabulator.helpers.detect_scheme_and_format` only extracts format from URLs ending with `.csv` (or other formats), using `splitext`.

I'm proposing a way to extract format from `format=xxx` in URL query string. It seems to me that it's a sufficiently common use case to be included in Tabulator.

Example: a commonly used OpenData platform formats its URLs like this:
- Dataset page: https://data.opendatasoft.com/explore/dataset/prenoms@hauts-de-seine/export/
- CSV file URL: https://data.opendatasoft.com/explore/dataset/prenoms@hauts-de-seine/download/?format=csv&timezone=Europe/Berlin&use_labels_for_header=true


Patch:
diff --git a/tabulator/helpers.py b/tabulator/helpers.py
index 97226b4..8070c4c 100644
--- a/tabulator/helpers.py
+++ b/tabulator/helpers.py
@@ -10,7 +10,7 @@ import six
 import codecs
 from copy import copy
 from importlib import import_module
-from six.moves.urllib.parse import urlparse, urlunparse
+from six.moves.urllib.parse import parse_qs, urlparse, urlunparse
 from . import exceptions
 from . import config
 
@@ -51,6 +51,12 @@ def detect_scheme_and_format(source):
     if len(scheme) < 2:
         scheme = config.DEFAULT_SCHEME
     format = os.path.splitext(parsed.path or parsed.netloc)[1][1:].lower() or None
+    if format is None:
+        # Test if query string contains a "format=" parameter.
+        query_string = parse_qs(parsed.query)
+        query_string_format = query_string.get("format")
+        if query_string_format is not None and len(query_string_format) == 1:
+            format = query_string_format[0]
 
     # Format: datapackage
     if parsed.path.endswith('datapackage.json'):


Test patch:
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index 3382395..47f94ab 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -30,6 +30,7 @@ from tabulator import helpers, config
     ('path', 'file', None),
     ('path.CsV', 'file', 'csv'),
     ('http://someplace.com/foo/path.csv?foo=bar#baz', 'http', 'csv'),
+    ('http://someplace.com/foo/path?foo=bar&format=csv#baz', 'http', 'csv'),
     ('https://docs.google.com/spreadsheets/d/X/edit?usp=sharing', None, 'gsheet'),
     ('https://docs.google.com/spreadsheets/d/X/export?format=csv&gid=0&single=true', 'https', 'csv'),
     ('https://docs.google.com/spreadsheets/d/X/pub?gid=0&single=true&output=csv', 'https', 'csv'),
Repository: frictionlessdata/tabulator-py
Pull request #256 (2018-10-18 18:16:31)

Stringify None values as empty strings
When using the 'force_strings' parameter on Excel files, you might get 'None' as a value for some cells.
This is obviously a bad outcome as it exposes some internal implementation and requires special handling for this special case.
An empty string is more apt in these cases.


Patch:
diff --git a/README.md b/README.md
index c7f0e53..bbe358a 100644
--- a/README.md
+++ b/README.md
@@ -344,7 +344,7 @@ with Stream(source, format='csv', headers=1, ignore_blank_headers=True) as strea
 ##### Force strings
 
 When `True`, all rows' values will be converted to strings (defaults to
-`False`).
+`False`). `None` values will be converted to empty strings.
 
 ```python
 # Default behaviour
diff --git a/tabulator/helpers.py b/tabulator/helpers.py
index 8070c4c..d5eb0ce 100644
--- a/tabulator/helpers.py
+++ b/tabulator/helpers.py
@@ -176,6 +176,8 @@ def extract_options(options, names):
 def stringify_value(value):
     """Convert any value to string.
     """
+    if value is None:
+        return u''
     isoformat = getattr(value, 'isoformat', None)
     if isoformat is not None:
         value = isoformat()


Test patch:
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index 47f94ab..c9c7070 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -118,3 +118,7 @@ def test_stringify_value():
     sample = '\u4e9c'.encode('utf-8-sig').decode("utf-8")
     assert helpers.stringify_value(sample) == sample
 
+
+def test_stringify_value_none():
+    assert helpers.stringify_value(None) == ''
+
Repository: nephila/python-taiga
Pull request #8 (2015-06-09 01:35:02)

Membership endpoints


Patch:
diff --git a/taiga/models/__init__.py b/taiga/models/__init__.py
index 23ec176..73229e4 100644
--- a/taiga/models/__init__.py
+++ b/taiga/models/__init__.py
@@ -1,5 +1,7 @@
 from .models import User
 from .models import Users
+from .models import Membership
+from .models import Memberships
 from .models import Project
 from .models import Projects
 from .models import UserStory
@@ -42,5 +44,5 @@ __all__ = [
     'IssueStatuses', 'TaskStatus', 'TaskStatuses', 'WikiPage', 'WikiPages',
     'WikiLink', 'WikiLinks', 'IssueAttribute', 'IssueAttributes',
     'TaskAttribute', 'TaskAttributes', 'UserStoryAttribute',
-    'UserStoryAttributes'
+    'UserStoryAttributes', 'Membership', 'Memberships'
 ]
diff --git a/taiga/models/models.py b/taiga/models/models.py
index d50842d..f428959 100644
--- a/taiga/models/models.py
+++ b/taiga/models/models.py
@@ -71,6 +71,24 @@ class Users(ListResource):
     instance = User
 
 
+class Membership(InstanceResource):
+
+    endpoint = 'memberships'
+
+    allowed_params = ['email', 'role', 'project']
+
+    repr_attribute = 'email'
+
+
+class Memberships(ListResource):
+
+    instance = Membership
+
+    def create(self, project, email, role, **attrs):
+        attrs.update({'project': project, 'email': email, 'role': role})
+        return self._new_resource(payload=attrs)
+
+
 class Priority(InstanceResource):
 
     endpoint = 'priorities'
@@ -477,6 +495,14 @@ class Project(InstanceResource):
         )
         return self
 
+    def add_membership(self, email, role, **attrs):
+        return Memberships(self.requester).create(
+            self.id, email, role, **attrs
+        )
+
+    def list_memberships(self):
+        return Memberships(self.requester).list(project=self.id)
+
     def add_user_story(self, subject, **attrs):
         return UserStories(self.requester).create(
             self.id, subject, **attrs


Test patch:
diff --git a/tests/test_projects.py b/tests/test_projects.py
index 2e9d642..71c143b 100644
--- a/tests/test_projects.py
+++ b/tests/test_projects.py
@@ -283,3 +283,18 @@ class TestProjects(unittest.TestCase):
         project = Project(rm, id=1)
         project.list_user_story_attributes()
         mock_list_us_attr.assert_called_with(project=1)
+
+    @patch('taiga.models.Memberships.create')
+    def test_add_membership(self, mock_new_membership):
+        rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
+        project = Project(rm, id=1)
+        project.add_membership('test@example.com', 1)
+        mock_new_membership.assert_called_with(1, 'test@example.com', 1)
+
+    @patch('taiga.models.Memberships.list')
+    def test_list_membership(self, mock_list_memberships):
+        rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
+        project = Project(rm, id=1)
+        project.list_memberships()
+        mock_list_memberships.assert_called_with(project=1)
+
Repository: nephila/python-taiga
Pull request #80 (2019-04-11 19:05:34)

Merge #72
Merge #72 with suggested change

Closes #72


Patch:
diff --git a/taiga/models/models.py b/taiga/models/models.py
index ae296ae..c3fe687 100644
--- a/taiga/models/models.py
+++ b/taiga/models/models.py
@@ -1247,11 +1247,11 @@ class Project(InstanceResource):
             estimated_finish, **attrs
         )
 
-    def list_milestones(self):
+    def list_milestones(self, **queryparams):
         """
         Get the list of :class:`Milestone` resources for the project.
         """
-        return Milestones(self.requester).list(project=self.id)
+        return Milestones(self.requester).list(project=self.id, **queryparams)
 
     def add_point(self, name, value, **attrs):
         """


Test patch:
diff --git a/tests/test_projects.py b/tests/test_projects.py
index 29dbbdb..d667e17 100644
--- a/tests/test_projects.py
+++ b/tests/test_projects.py
@@ -333,8 +333,8 @@ class TestProjects(unittest.TestCase):
     def test_list_milestones(self, mock_list_milestones):
         rm = RequestMaker('/api/v1', 'fakehost', 'faketoken')
         project = Project(rm, id=1)
-        project.list_milestones()
-        mock_list_milestones.assert_called_with(project=1)
+        project.list_milestones(subject='foo')
+        mock_list_milestones.assert_called_with(project=1, subject='foo')
 
     @patch('taiga.models.Issues.create')
     def test_add_issue(self, mock_new_issue):
Repository: nephila/python-taiga
Pull request #81 (2019-04-11 19:29:48)

Merge #76
Fix #76 


Patch:
diff --git a/taiga/models/models.py b/taiga/models/models.py
index ae296ae..6ad6de6 100644
--- a/taiga/models/models.py
+++ b/taiga/models/models.py
@@ -1700,7 +1700,8 @@ class HistoryEntity(object):
         """
         response = self.requester.get(
             '/{endpoint}/{entity}/{id}',
-            endpoint=self.endpoint, entity=self.entity, id=resource_id
+            endpoint=self.endpoint, entity=self.entity, id=resource_id,
+            paginate=False
         )
         return response.json()
 


Test patch:
diff --git a/tests/test_history.py b/tests/test_history.py
index 4166a6c..175000b 100644
--- a/tests/test_history.py
+++ b/tests/test_history.py
@@ -20,7 +20,7 @@ class TestHistory(unittest.TestCase):
         api.history.issue.get(res_id)
         mock_requestmaker_get.assert_called_with(
             '/{endpoint}/{entity}/{id}',
-            endpoint='history', entity='issue', id=res_id
+            endpoint='history', entity='issue', id=res_id, paginate=False
         )
 
     @patch('taiga.requestmaker.RequestMaker.get')
@@ -34,7 +34,7 @@ class TestHistory(unittest.TestCase):
         api.history.task.get(res_id)
         mock_requestmaker_get.assert_called_with(
             '/{endpoint}/{entity}/{id}',
-            endpoint='history', entity='task', id=res_id
+            endpoint='history', entity='task', id=res_id, paginate=False
         )
 
     @patch('taiga.requestmaker.RequestMaker.get')
@@ -48,7 +48,7 @@ class TestHistory(unittest.TestCase):
         api.history.user_story.get(res_id)
         mock_requestmaker_get.assert_called_with(
             '/{endpoint}/{entity}/{id}',
-            endpoint='history', entity='userstory', id=res_id
+            endpoint='history', entity='userstory', id=res_id, paginate=False
         )
 
     @patch('taiga.requestmaker.RequestMaker.get')
@@ -62,7 +62,7 @@ class TestHistory(unittest.TestCase):
         api.history.wiki.get(res_id)
         mock_requestmaker_get.assert_called_with(
             '/{endpoint}/{entity}/{id}',
-            endpoint='history', entity='wiki', id=res_id
+            endpoint='history', entity='wiki', id=res_id, paginate=False
         )
 
     @patch('taiga.requestmaker.RequestMaker.post')
Repository: materialsproject/custodian
Pull request #162 (2020-11-30 15:22:39)

tweak LargeSigmaHandler correction
Tweak the correction made by `LargeSigmaHandler` so that it traverses the feasible range of SIGMA values in fewer steps, and ensure that SIGMA always remains at least 0.02. 

After running many calculations with `LargeSigmaHandler`, I found that this handler was often triggering multiple times on the same calculation, and in many cases causing `MaxCorrectionsPerJob` failures. This PR changes the handler so that a maximum of 3 corrections will be made (with larger adjustments at each step), leaving some cushion for other handlers to make corrections without hitting the default limit of 5.


Patch:
diff --git a/custodian/vasp/handlers.py b/custodian/vasp/handlers.py
index 44088afb..55a03700 100644
--- a/custodian/vasp/handlers.py
+++ b/custodian/vasp/handlers.py
@@ -1119,16 +1119,20 @@ class LargeSigmaHandler(ErrorHandler):
         backup(VASP_BACKUP_FILES)
         actions = []
         vi = VaspInput.from_directory(".")
+        sigma = vi["INCAR"].get("SIGMA", 0.2)
 
-        # Reduce SIGMA
-        actions.append(
-                {
-                    "dict": "INCAR",
-                    "action": {
-                        "_set": {"SIGMA": vi["INCAR"].get("SIGMA", 0.2) - 0.04}
-                    },
-                }
-            )
+        # Reduce SIGMA by 0.06 if larger than 0.08
+        # this will reduce SIGMA from the default of 0.2 to the practical
+        # minimum value of 0.02 in 3 steps
+        if sigma > 0.08:
+            actions.append(
+                    {
+                        "dict": "INCAR",
+                        "action": {
+                            "_set": {"SIGMA": sigma - 0.06}
+                        },
+                    }
+                )
 
         VaspModder(vi=vi).apply_actions(actions)
         return {"errors": ["LargeSigma"], "actions": actions}


Test patch:
diff --git a/custodian/vasp/tests/test_handlers.py b/custodian/vasp/tests/test_handlers.py
index c6d3d3b0..870fe567 100644
--- a/custodian/vasp/tests/test_handlers.py
+++ b/custodian/vasp/tests/test_handlers.py
@@ -547,7 +547,7 @@ class LargeSigmaHandlerTest(unittest.TestCase):
         self.assertTrue(h.check())
         d = h.correct()
         self.assertEqual(d["errors"], ["LargeSigma"])
-        self.assertEqual(Incar.from_file("INCAR")["SIGMA"], 1.46)
+        self.assertEqual(Incar.from_file("INCAR")["SIGMA"], 1.44)
         os.remove("vasprun.xml")
 
     @classmethod
Repository: JuliaCollections/DataStructures.jl
Pull request #449 (2018-09-21 19:40:00)

Define empty! for PriorityQueue
In addition to defining `empty!`, this makes `PriorityQueue` immutable. I don't see a reason it should be mutable, and indeed modifying its, e.g., ordering after filling it with items seems like a bad idea.


Patch:
diff --git a/src/priorityqueue.jl b/src/priorityqueue.jl
index a063464..b739247 100644
--- a/src/priorityqueue.jl
+++ b/src/priorityqueue.jl
@@ -23,7 +23,7 @@ PriorityQueue{String,Int64,Base.Order.ForwardOrdering} with 3 entries:
   "a" => 2
 ```
 """
-mutable struct PriorityQueue{K,V,O<:Ordering} <: AbstractDict{K,V}
+struct PriorityQueue{K,V,O<:Ordering} <: AbstractDict{K,V}
     # Binary heap of (element, priority) pairs.
     xs::Array{Pair{K,V}, 1}
     o::O
@@ -334,6 +334,12 @@ function delete!(pq::PriorityQueue, key)
     pq
 end
 
+function empty!(pq::PriorityQueue)
+    empty!(pq.xs)
+    empty!(pq.index)
+    pq
+end
+
 # Unordered iteration through key value pairs in a PriorityQueue
 function _iterate(pq::PriorityQueue, state)
     state == nothing && return nothing


Test patch:
diff --git a/test/test_priority_queue.jl b/test/test_priority_queue.jl
index 3c20b44..8eed6c9 100644
--- a/test/test_priority_queue.jl
+++ b/test/test_priority_queue.jl
@@ -209,8 +209,17 @@ import Base.Order.Reverse
             @test pq === pq_out
             @test Set(collect(pq)) == Set(["a"=>2, "c"=>1])
         end
+
+        @testset "empty!" begin
+            pq = PriorityQueue(Base.Order.Forward, "a"=>2, "b"=>3, "c"=>1)
+            @test !isempty(pq)
+            empty!(pq)
+            @test isempty(pq)
+            enqueue!(pq, "a"=>2)
+            @test length(pq) == 1
+        end
     end
-    
+
     @testset "Iteration" begin
         pq = PriorityQueue('a'=>'A')
         @test collect(pq) == ['a' => 'A']
Repository: JuliaCollections/DataStructures.jl
Pull request #505 (2019-05-22 13:17:30)

Same behaviour for get and getkey as with julias base Dict.
SortedDict get and getkey methods behave differently then the similar methods in base julias Dict implementation in trying to convert the default to the dicts datatype. julias base dict simply returns the default. 

One could argue against this decision in julias base dict, but I tripped over this when trying to use SortedDict as a drop-in replacement for dict.


Patch:
diff --git a/src/sorted_dict.jl b/src/sorted_dict.jl
index 1f34584..09cb26a 100644
--- a/src/sorted_dict.jl
+++ b/src/sorted_dict.jl
@@ -399,7 +399,7 @@ log *n*)
 """
 function get(default_::Union{Function,Type}, m::SortedDict{K,D}, k_) where {K,D}
     i, exactfound = findkey(m.bt, convert(K, k_))
-    return exactfound ? m.bt.data[i].d : convert(D, default_())
+    return exactfound ? m.bt.data[i].d : default_()
 end
 
 get(m::SortedDict, k_, default_) = get(()->default_, m, k_)
@@ -440,7 +440,7 @@ than `k`. Time: O(*c* log *n*)
 """
 function getkey(m::SortedDict{K,D,Ord}, k_, default_) where {K,D,Ord <: Ordering}
     i, exactfound = findkey(m.bt, convert(K, k_))
-    exactfound ? m.bt.data[i].k : convert(K, default_)
+    exactfound ? m.bt.data[i].k : default_
 end
 
 ## Function delete! deletes an item at a given


Test patch:
diff --git a/test/test_sorted_containers.jl b/test/test_sorted_containers.jl
index 3db88ad..6981218 100644
--- a/test/test_sorted_containers.jl
+++ b/test/test_sorted_containers.jl
@@ -473,6 +473,7 @@ function testSortedDictMethods()
     my_assert(co == Forward)
     my_assert(haskey(m1, 71))
     my_assert(!haskey(m1, 77))
+    my_assert(get(m1, 70, nothing) == nothing)
     my_assert(get(m1, 70, -45.2) == -45.2)
     my_assert(get(m1, 83, -45.2) == convert(Float64,83)^2)
     h = get!(m1, 5, 27.0)
@@ -485,6 +486,7 @@ function testSortedDictMethods()
     my_assert(getkey(m1,7, 9) == 7)
     my_assert(getkey(m1,7.0, 9) == 7)
     my_assert(getkey(m1,12, 9) == 9)
+    my_assert(getkey(m1,12, nothing) == nothing)
     delete!(m1, 17)
     my_assert(length(m1) == length(ww) - 1)
     my_assert(deref_key((m1,advance((m1,findkey(m1,13))))) == 19)
Repository: JuliaCollections/DataStructures.jl
Pull request #519 (2019-07-26 15:05:35)

Trie now converts val to the correct type
Making `setindex!` work similarly to the standard library `Dict` and other containers. Now this works:
```julia
julia> T = Trie{Int64}()
Trie{Int64}(140018024147216, Dict{Char,Trie{Int64}}(), false)

julia> T["abc"] = 3
3

julia> T["def"] = Int8(5)
5
```

where before it failed.


Patch:
diff --git a/src/trie.jl b/src/trie.jl
index 1e6cb05..1b5d036 100644
--- a/src/trie.jl
+++ b/src/trie.jl
@@ -33,7 +33,8 @@ Trie(kv::AbstractVector{Tuple{K,V}}) where {K<:AbstractString,V} = Trie{V}(kv)
 Trie(kv::AbstractDict{K,V}) where {K<:AbstractString,V} = Trie{V}(kv)
 Trie(ks::AbstractVector{K}) where {K<:AbstractString} = Trie{Nothing}(ks, similar(ks, Nothing))
 
-function setindex!(t::Trie{T}, val::T, key::AbstractString) where T
+function setindex!(t::Trie{T}, val, key::AbstractString) where T
+    value = convert(T, val) # we don't want to iterate before finding out it fails
     node = t
     for char in key
         if !haskey(node.children, char)
@@ -42,7 +43,7 @@ function setindex!(t::Trie{T}, val::T, key::AbstractString) where T
         node = node.children[char]
     end
     node.is_key = true
-    node.value = val
+    node.value = value
 end
 
 function getindex(t::Trie, key::AbstractString)


Test patch:
diff --git a/test/test_trie.jl b/test/test_trie.jl
index eb15156..9cb5f65 100644
--- a/test/test_trie.jl
+++ b/test/test_trie.jl
@@ -8,10 +8,11 @@
         t["emma"] = 30
         t["rob"] = 27
         t["roger"] = 52
+        t["kevin"] = Int8(11)
 
         @test haskey(t, "roger")
         @test get(t,"rob",nothing) == 27
-        @test sort(keys(t)) == ["amy", "ann", "emma", "rob", "roger"]
+        @test sort(keys(t)) == ["amy", "ann", "emma", "kevin", "rob", "roger"]
         @test t["rob"] == 27
         @test sort(keys_with_prefix(t,"ro")) == ["rob", "roger"]
     end
Repository: JuliaCollections/DataStructures.jl
Pull request #535 (2019-10-01 07:03:21)

Add == for stack
Currently this fails unless the stacks are the same object in memory. All that was needed is a fallback to the deque storage `==` test.


Patch:
diff --git a/src/stack.jl b/src/stack.jl
index 0be6e02..cd8d1ef 100644
--- a/src/stack.jl
+++ b/src/stack.jl
@@ -25,3 +25,5 @@ empty!(s::Stack) = (empty!(s.store); s)
 iterate(st::Stack, s...) = iterate(reverse_iter(st.store), s...)
 
 reverse_iter(s::Stack{T}) where {T} = DequeIterator{T}(s.store)
+
+==(x::Stack, y::Stack) = x.store == y.store


Test patch:
diff --git a/test/test_stack.jl b/test/test_stack.jl
index 60460e4..b038508 100644
--- a/test/test_stack.jl
+++ b/test/test_stack.jl
@@ -39,6 +39,25 @@
             @test length(s) == n - i
         end
     end
+    
+    @testset "==" begin
+        s = Stack{Int}()
+        t = Stack{Int}()
+        
+        @test s == t
+        push!(s, 10)
+        @test s != t
+        push!(t, 10)
+        @test s == t
+        push!(t, 20)
+        @test s != t
+        
+        @testset "different types" begin
+            r = Stack{Float32}()
+            push!(r, 10)
+            @test s == r
+        end
+    end
 
     @testset "empty!" begin
         s = Stack{Int}(1)
Repository: JuliaCollections/DataStructures.jl
Pull request #536 (2019-10-01 07:20:19)

Adding == and empty! for queue
These were missing from `Queue` but present in `Stack` and `Deque`.


Patch:
diff --git a/src/queue.jl b/src/queue.jl
index feb5d55..5fe6606 100644
--- a/src/queue.jl
+++ b/src/queue.jl
@@ -36,8 +36,12 @@ Removes an element from the front of the queue `s` and returns it.
 """
 dequeue!(s::Queue) = popfirst!(s.store)
 
+empty!(s::Queue) = (empty!(s.store); s)
+
 # Iterators
 
 iterate(q::Queue, s...) = iterate(q.store, s...)
 
 reverse_iter(q::Queue) = reverse_iter(q.store)
+
+==(x::Queue, y::Queue) = x.store == y.store


Test patch:
diff --git a/test/test_queue.jl b/test/test_queue.jl
index d689a44..c7c9a76 100644
--- a/test/test_queue.jl
+++ b/test/test_queue.jl
@@ -43,6 +43,34 @@
         end
     end
 
+    @testset "==" begin
+        t = Queue{Int}()
+        s = Queue{Int}()
+        
+        @test s == t
+        enqueue!(s, 10)
+        @test s != t
+        enqueue!(t, 10)
+        @test s == t
+        enqueue!(t, 20)
+        @test s != t
+
+        @testset "different types" begin
+            r = Queue{Float32}()
+            enqueue!(r, 10)
+            @test s == r
+        end
+    end
+    
+    @testset "emptyness" begin
+        s = Queue{Int}()
+        enqueue!(s, 1)
+        enqueue!(s, 3)
+        @test !isempty(s)
+        empty!(s)
+        @test isempty(s)
+    end
+    
     @testset "iter should return a FIFO collection" begin
         q = Queue{Int}(10)
         n = 100