prompt
stringlengths
5.33k
21.1k
metadata
dict
context_start_lineno
int64
1
913
line_no
int64
16
984
repo
stringclasses
5 values
id
int64
0
416
target_function_prompt
stringlengths
201
13.6k
function_signature
stringlengths
7
453
solution_position
listlengths
2
2
raw_solution
stringlengths
201
13.6k
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 Base.copy(s1::IntSet) = copy!(IntSet(), s1) function Base.copy!(to::IntSet, from::IntSet) resize!(to.bits, length(from.bits)) copyto!(to.bits, from.bits) to.inverse = from.inverse return to end Base.eltype(::Type{IntSet}) = Int Base.sizehint!(s::IntSet, n::Integer) = (_resize0!(s.bits, n+1); s) # An internal function for setting the inclusion bit for a given integer n >= 0 @inline function _setint!(s::IntSet, n::Integer, b::Bool) idx = n+1 if idx > length(s.bits) !b && return s # setting a bit to zero outside the set's bits is a no-op newlen = idx + idx>>1 # This operation may overflow; we want saturation _resize0!(s.bits, ifelse(newlen<0, typemax(Int), newlen)) end unsafe_setindex!(s.bits, b, idx) # Use @inbounds once available return s ##CHUNK 2 # An internal function for setting the inclusion bit for a given integer n >= 0 @inline function _setint!(s::IntSet, n::Integer, b::Bool) idx = n+1 if idx > length(s.bits) !b && return s # setting a bit to zero outside the set's bits is a no-op newlen = idx + idx>>1 # This operation may overflow; we want saturation _resize0!(s.bits, ifelse(newlen<0, typemax(Int), newlen)) end unsafe_setindex!(s.bits, b, idx) # Use @inbounds once available return s end # An internal function to resize a bitarray and ensure the newly allocated # elements are zeroed (will become unnecessary if this behavior changes) @inline function _resize0!(b::BitVector, newlen::Integer) len = length(b) resize!(b, newlen) len < newlen && @inbounds(b[len+1:newlen] .= false) # resize! gives dirty memory return b end #FILE: DataStructures.jl/src/heaps/arrays_as_heaps.jl ##CHUNK 1 # Binary min-heap percolate up. function percolate_up!(xs::AbstractArray, i::Integer, x=xs[i], o::Ordering=Forward) @inbounds while (j = heapparent(i)) >= 1 lt(o, x, xs[j]) || break xs[i] = xs[j] i = j end xs[i] = x end @inline percolate_up!(xs::AbstractArray, i::Integer, o::Ordering) = percolate_up!(xs, i, xs[i], o) """ heappop!(v, [ord]) Given a binary heap-ordered array, remove and return the lowest ordered element. For efficiency, this function does not check that the array is indeed heap-ordered. """ function heappop!(xs::AbstractArray, o::Ordering=Forward) ##CHUNK 2 j = r > len || lt(o, xs[l], xs[r]) ? l : r lt(o, xs[j], x) || break xs[i] = xs[j] i = j end xs[i] = x end percolate_down!(xs::AbstractArray, i::Integer, o::Ordering, len::Integer=length(xs)) = percolate_down!(xs, i, xs[i], o, len) # Binary min-heap percolate up. function percolate_up!(xs::AbstractArray, i::Integer, x=xs[i], o::Ordering=Forward) @inbounds while (j = heapparent(i)) >= 1 lt(o, x, xs[j]) || break xs[i] = xs[j] i = j end xs[i] = x end #FILE: DataStructures.jl/src/dict_support.jl ##CHUNK 1 # support functions function not_iterator_of_pairs(kv::T) where T # if the object is not iterable, return true, else check the eltype of the iteration Base.isiterable(T) || return true # else, check if we can check `eltype`: if Base.IteratorEltype(kv) isa Base.HasEltype typ = eltype(kv) if !(typ == Any) return !(typ <: Union{<: Tuple, <: Pair}) end end # we can't check eltype, or eltype is not useful, # so brute force it. return any(x->!isa(x, Union{Tuple,Pair}), kv) end #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 ``` """ function Base.getkey(h::RobinDict{K,V}, key, default) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? default : h.keys[index]::K end # backward shift deletion by not keeping any tombstones function rh_delete!(h::RobinDict{K, V}, index) where {K, V} @assert index > 0 # this assumes that there is a key/value present in the dictionary at index index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #CURRENT FILE: DataStructures.jl/src/accumulator.jl ##CHUNK 1 end Base.issubset(a::Accumulator, b::Accumulator) = all(b[k] >= v for (k, v) in a) Base.union(a::Accumulator, b::Accumulator, c::Accumulator...) = union(union(a,b), c...) Base.union(a::Accumulator, b::Accumulator) = union!(copy(a), b) function Base.union!(a::Accumulator, b::Accumulator) for (kb, vb) in b va = a[kb] vb >= 0 || throw(MultiplicityException(kb, vb)) va >= 0 || throw(MultiplicityException(kb, va)) a[kb] = max(va, vb) end return a end Base.intersect(a::Accumulator, b::Accumulator, c::Accumulator...) = intersect(intersect(a,b), c...) Base.intersect(a::Accumulator, b::Accumulator) = intersect!(copy(a), b) function Base.show(io::IO, acc::Accumulator{T,V}) where {T,V} ##CHUNK 2 function Base.setdiff(a::Accumulator, b::Accumulator) ret = copy(a) for (k, v) in b v > 0 || throw(MultiplicityException(k, v)) dec!(ret, k, v) drop_nonpositive!(ret, k) end return ret end Base.issubset(a::Accumulator, b::Accumulator) = all(b[k] >= v for (k, v) in a) Base.union(a::Accumulator, b::Accumulator, c::Accumulator...) = union(union(a,b), c...) Base.union(a::Accumulator, b::Accumulator) = union!(copy(a), b) function Base.union!(a::Accumulator, b::Accumulator) for (kb, vb) in b va = a[kb] vb >= 0 || throw(MultiplicityException(kb, vb)) ##CHUNK 3 va >= 0 || throw(MultiplicityException(kb, va)) a[kb] = max(va, vb) end return a end Base.intersect(a::Accumulator, b::Accumulator, c::Accumulator...) = intersect(intersect(a,b), c...) Base.intersect(a::Accumulator, b::Accumulator) = intersect!(copy(a), b) function Base.show(io::IO, acc::Accumulator{T,V}) where {T,V} l = length(acc) if l>0 print(io, "Accumulator(") else print(io,"Accumulator{$T,$V}(") end for (count, (k, v)) in enumerate(acc) print(io, k, " => ", v) if count < l print(io, ", ") ##CHUNK 4 k::K v::V end function Base.showerror(io::IO, err::MultiplicityException) print(io, "When using an `Accumulator` as a multiset, all elements must have positive multiplicity") print(io, " element `$(err.k)` has multiplicity $(err.v)") end drop_nonpositive!(a::Accumulator, k) = (a[k] > 0 || delete!(a.map, k)) function Base.setdiff(a::Accumulator, b::Accumulator) ret = copy(a) for (k, v) in b v > 0 || throw(MultiplicityException(k, v)) dec!(ret, k, v) drop_nonpositive!(ret, k) end return ret Based on the information above, please generate test code for the following function: function Base.intersect!(a::Accumulator, b::Accumulator) for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities va = a[k] vb = b[k] va >= 0 || throw(MultiplicityException(k, va)) vb >= 0 || throw(MultiplicityException(k, vb)) a[k] = min(va, vb) drop_nonpositive!(a, k) # Drop any that ended up zero end return a end
{ "fpath_tuple": [ "DataStructures.jl", "src", "accumulator.jl" ], "ground_truth": "function Base.intersect!(a::Accumulator, b::Accumulator)\n for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities\n va = a[k]\n vb = b[k]\n va >= 0 || throw(MultiplicityException(k, va))\n vb >= 0 || throw(MultiplicityException(k, vb))\n\n a[k] = min(va, vb)\n drop_nonpositive!(a, k) # Drop any that ended up zero\n end\n return a\nend", "task_id": "DataStructures/0" }
230
241
DataStructures.jl
0
function Base.intersect!(a::Accumulator, b::Accumulator) for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities va = a[k] vb = b[k] va >= 0 || throw(MultiplicityException(k, va)) vb >= 0 || throw(MultiplicityException(k, vb)) a[k] = min(va, vb) drop_nonpositive!(a, k) # Drop any that ended up zero end return a end
Base.intersect!(a::Accumulator, b::Accumulator)
[ 230, 241 ]
function Base.intersect!(a::Accumulator, b::Accumulator) for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities va = a[k] vb = b[k] va >= 0 || throw(MultiplicityException(k, va)) vb >= 0 || throw(MultiplicityException(k, vb)) a[k] = min(va, vb) drop_nonpositive!(a, k) # Drop any that ended up zero end return a end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end ##CHUNK 2 x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end ##CHUNK 3 node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color ##CHUNK 4 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 5 rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end Base.in(key, tree::RBTree) = haskey(tree, key) """ getindex(tree, ind) Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key. """ function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 2 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) #FILE: DataStructures.jl/benchmark/bench_sparse_int_set.jl ##CHUNK 1 end function iterate_two_exclude_one_bench(x,y,z) t = 0 for (ix, iy) in zip(x, y, exclude=(z,)) t += ix + iy end return t end x_y_z_setup = ( Random.seed!(1234); x = SparseIntSet(rand(1:30000, 1000)); y = SparseIntSet(rand(1:30000, 1000)); z = SparseIntSet(rand(1:30000, 1000)); ) suite["iterate one"] = @benchmarkable iterate_one_bench(x) setup=x_y_z_setup suite["iterate two"] = #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node ##CHUNK 2 Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ """ right_rotate(node_x::AVLTreeNode) Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ function right_rotate(z::AVLTreeNode) y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end Based on the information above, please generate test code for the following function: function left_rotate(z::AVLTreeNode) y = z.rightChild α = y.leftChild y.leftChild = z z.rightChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function left_rotate(z::AVLTreeNode)\n y = z.rightChild\n α = y.leftChild\n y.leftChild = z\n z.rightChild = α\n z.height = compute_height(z)\n y.height = compute_height(y)\n z.subsize = compute_subtree_size(z)\n y.subsize = compute_subtree_size(y)\n return y\nend", "task_id": "DataStructures/1" }
83
93
DataStructures.jl
1
function left_rotate(z::AVLTreeNode) y = z.rightChild α = y.leftChild y.leftChild = z z.rightChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
left_rotate(z::AVLTreeNode)
[ 83, 93 ]
function left_rotate(z::AVLTreeNode) y = z.rightChild α = y.leftChild y.leftChild = z z.rightChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end ##CHUNK 2 x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end ##CHUNK 3 node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color ##CHUNK 4 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 2 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) #FILE: DataStructures.jl/benchmark/bench_sparse_int_set.jl ##CHUNK 1 end function iterate_two_exclude_one_bench(x,y,z) t = 0 for (ix, iy) in zip(x, y, exclude=(z,)) t += ix + iy end return t end x_y_z_setup = ( Random.seed!(1234); x = SparseIntSet(rand(1:30000, 1000)); y = SparseIntSet(rand(1:30000, 1000)); z = SparseIntSet(rand(1:30000, 1000)); ) suite["iterate one"] = @benchmarkable iterate_one_bench(x) setup=x_y_z_setup suite["iterate two"] = #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ function left_rotate(z::AVLTreeNode) y = z.rightChild α = y.leftChild y.leftChild = z z.rightChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end """ right_rotate(node_x::AVLTreeNode) Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ ##CHUNK 2 else L = get_subsize(node.leftChild) R = get_subsize(node.rightChild) return (L + R + Int32(1)) end end """ left_rotate(node_x::AVLTreeNode) Performs a left-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ function left_rotate(z::AVLTreeNode) y = z.rightChild α = y.leftChild y.leftChild = z z.rightChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) ##CHUNK 3 y.subsize = compute_subtree_size(y) return y end """ right_rotate(node_x::AVLTreeNode) Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node Based on the information above, please generate test code for the following function: function right_rotate(z::AVLTreeNode) y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function right_rotate(z::AVLTreeNode)\n y = z.leftChild\n α = y.rightChild\n y.rightChild = z\n z.leftChild = α\n z.height = compute_height(z)\n y.height = compute_height(y)\n z.subsize = compute_subtree_size(z)\n y.subsize = compute_subtree_size(y)\n return y\nend", "task_id": "DataStructures/2" }
100
110
DataStructures.jl
2
function right_rotate(z::AVLTreeNode) y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
right_rotate(z::AVLTreeNode)
[ 100, 110 ]
function right_rotate(z::AVLTreeNode) y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 2 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 3 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 4 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 3 end RBTree() = RBTree{Any}() Base.length(tree::RBTree) = tree.count """ search_node(tree, key) Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`. """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild ##CHUNK 4 node = node.leftChild end return node end """ delete!(tree::RBTree, key) Deletes `key` from `tree`, if present, else returns the unmodified tree. """ function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data ##CHUNK 5 function insert_node!(tree::RBTree, node::RBTreeNode) node_y = nothing node_x = tree.root while node_x !== tree.nil node_y = node_x if node.data < node_x.data node_x = node_x.leftChild else node_x = node_x.rightChild end end node.parent = node_y if node_y == nothing tree.root = node elseif node.data < node_y.data node_y.leftChild = node else node_y.rightChild = node #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 julia> sorted_rank(tree, 17) 9 ``` """ function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end Based on the information above, please generate test code for the following function: function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function search_node(tree::AVLTree{K}, d::K) where K\n prev = nothing\n node = tree.root\n while node != nothing && node.data != nothing && node.data != d\n\n prev = node\n if d < node.data\n node = node.leftChild\n else\n node = node.rightChild\n end\n end\n\n return (node == nothing) ? prev : node\nend", "task_id": "DataStructures/3" }
124
138
DataStructures.jl
3
function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end
search_node(tree::AVLTree{K}, d::K) where K
[ 124, 138 ]
function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 node.height = compute_height(node) balance = get_balance(node) if balance > 1 if get_balance(node.leftChild) >= 0 return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if get_balance(node.rightChild) <= 0 return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end ##CHUNK 2 result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if get_balance(node.leftChild) >= 0 return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end ##CHUNK 3 function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end node.subsize = compute_subtree_size(node) ##CHUNK 4 end if balance < -1 if get_balance(node.rightChild) <= 0 return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end """ delete!(tree::AVLTree{K}, k::K) where K Delete key `k` from `tree` AVL tree. """ function Base.delete!(tree::AVLTree{K}, k::K) where K ##CHUNK 5 """ push!(tree::AVLTree{K}, key) where K Insert `key` in AVL tree `tree`. """ function Base.push!(tree::AVLTree{K}, key) where K key0 = convert(K, key) insert!(tree, key0) end function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing ##CHUNK 6 julia> for k in 1:2:20 push!(tree, k) end julia> sorted_rank(tree, 17) 9 ``` """ function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end ##CHUNK 7 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 8 node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end """ getindex(tree::AVLTree{K}, ind::Integer) where K Considering the elements of `tree` sorted, returns the `ind`-th element in `tree`. Search operation is performed in \$O(\\log n)\$ time complexity. Based on the information above, please generate test code for the following function: function insert_node(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = insert_node(node.leftChild, key) else node.rightChild = insert_node(node.rightChild, key) end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if key < node.leftChild.data return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function insert_node(node::AVLTreeNode{K}, key::K) where K\n if key < node.data\n node.leftChild = insert_node(node.leftChild, key)\n else\n node.rightChild = insert_node(node.rightChild, key)\n end\n\n node.subsize = compute_subtree_size(node)\n node.height = compute_height(node)\n balance = get_balance(node)\n\n if balance > 1\n if key < node.leftChild.data\n return right_rotate(node)\n else\n node.leftChild = left_rotate(node.leftChild)\n return right_rotate(node)\n end\n end\n\n if balance < -1\n if key > node.rightChild.data\n return left_rotate(node)\n else\n node.rightChild = right_rotate(node.rightChild)\n return left_rotate(node)\n end\n end\n\n return node\nend", "task_id": "DataStructures/4" }
162
192
DataStructures.jl
4
function insert_node(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = insert_node(node.leftChild, key) else node.rightChild = insert_node(node.rightChild, key) end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if key < node.leftChild.data return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
insert_node(node::AVLTreeNode{K}, key::K) where K
[ 162, 192 ]
function insert_node(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = insert_node(node.leftChild, key) else node.rightChild = insert_node(node.rightChild, key) end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if key < node.leftChild.data return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 2 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 function insert_node(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = insert_node(node.leftChild, key) else node.rightChild = insert_node(node.rightChild, key) end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if key < node.leftChild.data return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end ##CHUNK 2 balance = get_balance(node) if balance > 1 if key < node.leftChild.data return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end ##CHUNK 3 """ in(key, tree::AVLTree) `In` infix operator for `key` and `tree` types. Analogous to [`haskey(tree::AVLTree{K}, k::K) where K`](@ref). """ Base.in(key, tree::AVLTree) = haskey(tree, key) function insert_node(node::Nothing, key::K) where K return AVLTreeNode{K}(key) end function insert_node(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = insert_node(node.leftChild, key) else node.rightChild = insert_node(node.rightChild, key) end node.subsize = compute_subtree_size(node) node.height = compute_height(node) ##CHUNK 4 if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end function Base.insert!(tree::AVLTree{K}, d::K) where K haskey(tree, d) && return tree tree.root = insert_node(tree.root, d) tree.count += 1 return tree end ##CHUNK 5 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 6 end julia> sorted_rank(tree, 17) 9 ``` """ function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank Based on the information above, please generate test code for the following function: function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if get_balance(node.leftChild) >= 0 return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if get_balance(node.rightChild) <= 0 return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function delete_node!(node::AVLTreeNode{K}, key::K) where K\n if key < node.data\n node.leftChild = delete_node!(node.leftChild, key)\n elseif key > node.data\n node.rightChild = delete_node!(node.rightChild, key)\n else\n if node.leftChild == nothing\n result = node.rightChild\n return result\n elseif node.rightChild == nothing\n result = node.leftChild\n return result\n else\n result = minimum_node(node.rightChild)\n node.data = result.data\n node.rightChild = delete_node!(node.rightChild, result.data)\n end\n end\n\n node.subsize = compute_subtree_size(node)\n node.height = compute_height(node)\n balance = get_balance(node)\n\n if balance > 1\n if get_balance(node.leftChild) >= 0\n return right_rotate(node)\n else\n node.leftChild = left_rotate(node.leftChild)\n return right_rotate(node)\n end\n end\n\n if balance < -1\n if get_balance(node.rightChild) <= 0\n return left_rotate(node)\n else\n node.rightChild = right_rotate(node.rightChild)\n return left_rotate(node)\n end\n end\n\n return node\nend", "task_id": "DataStructures/5" }
212
254
DataStructures.jl
5
function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if get_balance(node.leftChild) >= 0 return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if get_balance(node.rightChild) <= 0 return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
delete_node!(node::AVLTreeNode{K}, key::K) where K
[ 212, 254 ]
function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end node.subsize = compute_subtree_size(node) node.height = compute_height(node) balance = get_balance(node) if balance > 1 if get_balance(node.leftChild) >= 0 return right_rotate(node) else node.leftChild = left_rotate(node.leftChild) return right_rotate(node) end end if balance < -1 if get_balance(node.rightChild) <= 0 return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 end RBTree() = RBTree{Any}() Base.length(tree::RBTree) = tree.count """ search_node(tree, key) Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`. """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild ##CHUNK 3 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 4 node = node.leftChild end return node end """ delete!(tree::RBTree, key) Deletes `key` from `tree`, if present, else returns the unmodified tree. """ function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 2 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 3 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 2 function delete_node!(node::AVLTreeNode{K}, key::K) where K if key < node.data node.leftChild = delete_node!(node.leftChild, key) elseif key > node.data node.rightChild = delete_node!(node.rightChild, key) else if node.leftChild == nothing result = node.rightChild return result elseif node.rightChild == nothing result = node.leftChild return result else result = minimum_node(node.rightChild) node.data = result.data node.rightChild = delete_node!(node.rightChild, result.data) end end ##CHUNK 3 """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data Based on the information above, please generate test code for the following function: function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function sorted_rank(tree::AVLTree{K}, key::K) where K\n !haskey(tree, key) && throw(KeyError(key))\n node = tree.root\n rank = 0\n while node.data != key\n if (node.data < key)\n rank += (1 + get_subsize(node.leftChild))\n node = node.rightChild\n else\n node = node.leftChild\n end\n end\n rank += (1 + get_subsize(node.leftChild))\n return rank\nend", "task_id": "DataStructures/6" }
290
304
DataStructures.jl
6
function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end
sorted_rank(tree::AVLTree{K}, key::K) where K
[ 290, 304 ]
function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) ##CHUNK 2 end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 Base.in(key, tree::RBTree) = haskey(tree, key) """ getindex(tree, ind) Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key. """ function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) ##CHUNK 2 rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end Base.in(key, tree::RBTree) = haskey(tree, key) """ getindex(tree, ind) Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key. """ function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 sum += ft.bi_tree[i] i -= i&(-i) end sum end Base.getindex(ft::FenwickTree{T}, ind::Integer) where T = prefixsum(ft, ind) #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.delete!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) if index > 0 rh_delete!(h, index) end return h end function get_next_filled(h::RobinDict, i) L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end ##CHUNK 2 L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end Base.@propagate_inbounds _iterate(t::RobinDict{K,V}, i) where {K,V} = i == 0 ? nothing : (Pair{K,V}(t.keys[i],t.vals[i]), i == typemax(Int) ? 0 : get_next_filled(t, i+1)) Base.@propagate_inbounds function Base.iterate(t::RobinDict) _iterate(t, t.idxfloor) end Base.@propagate_inbounds Base.iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i)) function _merge_kvtypes(d, others...) K, V = keytype(d), valtype(d) for other in others K = promote_type(K, keytype(other)) #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end @inline function _buffer_index(cb::CircularBuffer, i::Int) n = cb.capacity idx = cb.first + i - 1 return ifelse(idx > n, idx - n, idx) end """ cb[i] #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 end function Base.symdiff!(s1::IntSet, s2::IntSet) e = _matchlength!(s1.bits, length(s2.bits)) map!(⊻, s1.bits, s1.bits, s2.bits) s2.inverse && (s1.inverse = !s1.inverse) append!(s1.bits, e) return s1 end function Base.in(n::Integer, s::IntSet) idx = n+1 if 1 <= idx <= length(s.bits) unsafe_getindex(s.bits, idx) != s.inverse else ifelse((idx <= 0) | (idx > typemax(Int)), false, s.inverse) end end function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert #CURRENT FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 # computes the height of the subtree, which basically is # one added the maximum of the height of the left subtree and right subtree compute_height(node::AVLTreeNode) = Int8(1) + max(get_height(node.leftChild), get_height(node.rightChild)) get_subsize(node::AVLTreeNode_or_null) = (node == nothing) ? Int32(0) : node.subsize # compute the subtree size function compute_subtree_size(node::AVLTreeNode_or_null) if node == nothing return Int32(0) else L = get_subsize(node.leftChild) R = get_subsize(node.rightChild) return (L + R + Int32(1)) end end """ left_rotate(node_x::AVLTreeNode) Based on the information above, please generate test code for the following function: function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end end end value = traverse_tree(tree.root, ind) return value end
{ "fpath_tuple": [ "DataStructures.jl", "src", "avl_tree.jl" ], "ground_truth": "function Base.getindex(tree::AVLTree{K}, ind::Integer) where K\n @boundscheck (1 <= ind <= tree.count) || throw(BoundsError(\"$ind should be in between 1 and $(tree.count)\"))\n function traverse_tree(node::AVLTreeNode_or_null, idx)\n if (node != nothing)\n L = get_subsize(node.leftChild)\n if idx <= L\n return traverse_tree(node.leftChild, idx)\n elseif idx == L + 1\n return node.data\n else\n return traverse_tree(node.rightChild, idx - L - 1)\n end\n end\n end\n value = traverse_tree(tree.root, ind)\n return value\nend", "task_id": "DataStructures/7" }
329
345
DataStructures.jl
7
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end end end value = traverse_tree(tree.root, ind) return value end
Base.getindex(tree::AVLTree{K}, ind::Integer) where K
[ 329, 345 ]
function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end end end value = traverse_tree(tree.root, ind) return value end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_sorted_containers.jl ##CHUNK 1 end remove_spaces(s::String) = replace(s, r"\s+"=>"") ## Function checkcorrectness checks a balanced tree for correctness. function checkcorrectness(t::DataStructures.BalancedTree23{K,D,Ord}, allowdups=false) where {K,D,Ord <: Ordering} dsz = size(t.data, 1) tsz = size(t.tree, 1) r = t.rootloc bfstreenodes = Vector{Int}() tdpth = t.depth intree = BitSet() levstart = Vector{Int}(undef, tdpth) push!(bfstreenodes, r) levstart[1] = 1 ##CHUNK 2 allowdups=false) where {K,D,Ord <: Ordering} dsz = size(t.data, 1) tsz = size(t.tree, 1) r = t.rootloc bfstreenodes = Vector{Int}() tdpth = t.depth intree = BitSet() levstart = Vector{Int}(undef, tdpth) push!(bfstreenodes, r) levstart[1] = 1 push!(intree, r) for curdepth = 2 : tdpth levstart[curdepth] = size(bfstreenodes, 1) + 1 for l = levstart[curdepth - 1] : levstart[curdepth] - 1 anc = bfstreenodes[l] c1 = t.tree[anc].child1 if in(c1, intree) println("anc = $anc c1 = $c1") throw(ErrorException("Tree contains loops 1")) end #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 #CURRENT FILE: DataStructures.jl/src/balanced_tree.jl ##CHUNK 1 t.deletionchild[2] = leftsib t.deletionchild[3] = p t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionleftkey[3] = sk2 end p = pparent deletionleftkey1_valid = false end curdepth -= 1 end if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ##CHUNK 2 # If the root has been split, then we need to add a level # to the tree that is the parent of the old root and the new node. if splitroot @invariant existingchild == t.rootloc newroot = TreeNode{K}(existingchild, newchild, 0, 0, minkeynewchild, minkeynewchild) newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot) replaceparent!(t.tree, existingchild, newrootloc) replaceparent!(t.tree, newchild, newrootloc) t.rootloc = newrootloc t.depth += 1 end return true, newind end ## nextloc0: returns the next item in the tree according to the ##CHUNK 3 ## by inserting a dummy tree node with two children, the before-start ## marker whose index is 1 and the after-end marker whose index is 2. ## These two markers live in dummy data nodes. function initializeTree!(tree::Vector{TreeNode{K}}) where K resize!(tree,1) tree[1] = TreeNode{K}(K, 1, 2, 0, 0) return nothing end function initializeData!(data::Vector{KDRec{K,D}}) where {K,D} resize!(data, 2) data[1] = KDRec{K,D}(1) data[2] = KDRec{K,D}(1) return nothing end ## Type BalancedTree23{K,D,Ord} is 'base class' for ## SortedDict, SortedMultiDict and SortedSet. ##CHUNK 4 depthp = t.depth @inbounds while true if depthp < t.depth p = t.tree[ii].parent end if t.tree[p].child1 == ii nextchild = t.tree[p].child2 break end if t.tree[p].child2 == ii && t.tree[p].child3 > 0 nextchild = t.tree[p].child3 break end ii = p depthp -= 1 end @inbounds while true if depthp == t.depth return nextchild end ##CHUNK 5 @inbounds while true if depthp < t.depth p = t.tree[ii].parent end if t.tree[p].child3 == ii prevchild = t.tree[p].child2 break end if t.tree[p].child2 == ii prevchild = t.tree[p].child1 break end ii = p depthp -= 1 end @inbounds while true if depthp == t.depth return prevchild end p = prevchild ##CHUNK 6 @inbounds return curnode, (curnode > 2 && eq(t.ord, t.data[curnode].k, k)) end ## The findkeyless function finds the index of a (key,data) pair in the tree that ## with the greatest key that is less than the given key. If there is no ## key less than the given key, then it returns 1 (the before-start node). function findkeyless(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_nonleaf(t.ord, thisnode, k) : cmp3le_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? ##CHUNK 7 if exactfound && !allowdups t.data[leafind] = KDRec{K,D}(parent, k,d) return false, leafind end # We get here if k was not already found in the tree or # if duplicates are allowed. # In this case we insert a new node. depth = t.depth ord = t.ord ## Store the new data item in the tree's data array. Later ## go back and fix the parent. newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d)) push!(t.useddatacells, newind) p1 = parent newchild = newind minkeynewchild = k splitroot = false Based on the information above, please generate test code for the following function: function Base.empty!(t::BalancedTree23) resize!(t.data,2) initializeData!(t.data) resize!(t.tree,1) initializeTree!(t.tree) t.depth = 1 t.rootloc = 1 empty!(t.freetreeinds) empty!(t.freedatainds) empty!(t.useddatacells) push!(t.useddatacells, 1, 2) return nothing end
{ "fpath_tuple": [ "DataStructures.jl", "src", "balanced_tree.jl" ], "ground_truth": "function Base.empty!(t::BalancedTree23)\n resize!(t.data,2)\n initializeData!(t.data)\n resize!(t.tree,1)\n initializeTree!(t.tree)\n t.depth = 1\n t.rootloc = 1\n empty!(t.freetreeinds)\n empty!(t.freedatainds)\n empty!(t.useddatacells)\n push!(t.useddatacells, 1, 2)\n return nothing\nend", "task_id": "DataStructures/8" }
238
250
DataStructures.jl
8
function Base.empty!(t::BalancedTree23) resize!(t.data,2) initializeData!(t.data) resize!(t.tree,1) initializeTree!(t.tree) t.depth = 1 t.rootloc = 1 empty!(t.freetreeinds) empty!(t.freedatainds) empty!(t.useddatacells) push!(t.useddatacells, 1, 2) return nothing end
Base.empty!(t::BalancedTree23)
[ 238, 250 ]
function Base.empty!(t::BalancedTree23) resize!(t.data,2) initializeData!(t.data) resize!(t.tree,1) initializeTree!(t.tree) t.depth = 1 t.rootloc = 1 empty!(t.freetreeinds) empty!(t.freedatainds) empty!(t.useddatacells) push!(t.useddatacells, 1, 2) return nothing end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 pos_diff = i - des_ind else pos_diff = sz - des_ind + i end dist = calculate_distance(h, i) @assert dist == pos_diff max_disp = max(max_disp, dist) distlast = (i != 1) ? isslotfilled(h, i-1) ? calculate_distance(h, i-1) : 0 : isslotfilled(h, sz) ? calculate_distance(h, sz) : 0 @assert dist <= distlast + 1 end @assert h.idxfloor == min_idx @assert cnt == length(h) end h = RobinDict() for i = 1:10000 h[i] = i+1 end check_invariants(h) #FILE: DataStructures.jl/test/test_sorted_containers.jl ##CHUNK 1 lt(o::ForBack, a, b) = o.flag ? isless(a,b) : isless(b,a) @noinline my_assert(stmt) = stmt ? nothing : throw(AssertionError("assertion failed")) function my_primes(N) w = Vector{Bool}(undef, N) fill!(w,true) for k = 2 : N if w[k] w[2 * k : k : N] .= false end end p = Int[] for k = 2 : N if w[k] push!(p,k) end end p ##CHUNK 2 merge!(m1, m2) my_assert(isequal(m1, m3)) m7 = SortedMultiDict{Int,Int}() n1 = 10000 for k = 1 : n1 push_return_semitoken!(m7, k=>k+1) end for k = 1 : n1 push_return_semitoken!(m7, k=>k+2) end for k = 1 : n1 i1, i2 = searchequalrange(m7, k) count = 0 for (key,v) in inclusive(m7, i1, i2) count += 1 my_assert(key == k) my_assert(v == k + count) end my_assert(count == 2) count = 0 #FILE: DataStructures.jl/src/sorted_container_iteration.jl ##CHUNK 1 """ status(token::Token) status((m, st)) Determine the status of a token. Return values are: - 0 = invalid token - 1 = valid and points to live data - 2 = before-start token - 3 = past-end token The second form creates the token in-place as a tuple of a sorted container `m` and a semitoken `st`. Time: O(1) """ status(ii::Token) = !(ii[2].address in ii[1].bt.useddatacells) ? 0 : ii[2].address == 1 ? 2 : ii[2].address == 2 ? 3 : 1 """ compare(m::SortedContainer, s::IntSemiToken, t::IntSemiToken) #CURRENT FILE: DataStructures.jl/src/balanced_tree.jl ##CHUNK 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_nonleaf(t.ord, thisnode, k) : cmp3_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_leaf(t.ord, thisnode, k) : cmp3_leaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 @inbounds return curnode, (curnode > 2 && eq(t.ord, t.data[curnode].k, k)) end ## The findkeyless function finds the index of a (key,data) pair in the tree that ## with the greatest key that is less than the given key. If there is no ## key less than the given key, then it returns 1 (the before-start node). ##CHUNK 2 ## where the given key lives (if it is present), or ## if the key is not present, to the lower bound for the key, ## i.e., the data item that comes immediately before it. ## If there are multiple equal keys, then it finds the last one. ## It returns the index of the key found and a boolean indicating ## whether the exact key was found or not. function findkey(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_nonleaf(t.ord, thisnode, k) : cmp3_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_leaf(t.ord, thisnode, k) : ##CHUNK 3 cmp3_leaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 @inbounds return curnode, (curnode > 2 && eq(t.ord, t.data[curnode].k, k)) end ## The findkeyless function finds the index of a (key,data) pair in the tree that ## with the greatest key that is less than the given key. If there is no ## key less than the given key, then it returns 1 (the before-start node). ## The following are helper routines for the insert! and delete! functions. ## They replace the 'parent' field of either an internal tree node or ## a data node at the bottom tree level. function replaceparent!(data::Vector{KDRec{K,D}}, whichind::Int, newparent::Int) where {K,D} data[whichind] = KDRec{K,D}(newparent, data[whichind].k, data[whichind].d) return nothing ##CHUNK 4 treenode::TreeNode, k) !lt(o,treenode.splitkey1, k) ? 1 : !lt(o,treenode.splitkey2, k) ? 2 : 3 end @inline function cmp3le_leaf(o::Ordering, treenode::TreeNode, k) !lt(o,treenode.splitkey1,k) ? 1 : (treenode.child3 == 2 || !lt(o,treenode.splitkey2, k)) ? 2 : 3 end ## The empty! function deletes all data in the balanced tree. ## Therefore, it invalidates all indices. function Base.empty!(t::BalancedTree23) resize!(t.data,2) initializeData!(t.data) ##CHUNK 5 if height == 0 child_belowaddress[whichc] = (i1 == 1) ? 1 : ((i1 == length(m.data)) ? 2 : i1 + 1) child_keyaddress[whichc] = child_belowaddress[whichc] else child_belowaddress[whichc] = levbelowbaseind + i1 child_keyaddress[whichc] = keysbelow[i1] end end if numchildren == 2 child_belowaddress[3] = 0 child_keyaddress[3] = child_keyaddress[2] end push!(newkeysbelow, child_keyaddress[1]) push!(m.tree, TreeNode{K}(child_belowaddress[1], child_belowaddress[2], child_belowaddress[3], 0, m.data[child_keyaddress[2]].k, m.data[child_keyaddress[3]].k)) myaddress = length(m.tree) ##CHUNK 6 resize!(newkeysbelow, 0) # Loop over the nodes of the level below, stepping by 2's # to form the tree nodes on the new level. One tree node (the # last one) may need to have three children if the # number of nodes on the level below is odd. for i = 1 : div(belowlevlength, 2) cbase = i * 2 - 2 numchildren = (cbase == belowlevlength - 3) ? 3 : 2 for whichc = 1 : numchildren i1 = cbase + whichc if height == 0 child_belowaddress[whichc] = (i1 == 1) ? 1 : ((i1 == length(m.data)) ? 2 : i1 + 1) child_keyaddress[whichc] = child_belowaddress[whichc] else child_belowaddress[whichc] = levbelowbaseind + i1 child_keyaddress[whichc] = keysbelow[i1] end end if numchildren == 2 Based on the information above, please generate test code for the following function: function findkeyless(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_nonleaf(t.ord, thisnode, k) : cmp3le_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_leaf(t.ord, thisnode, k) : cmp3le_leaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 return curnode end
{ "fpath_tuple": [ "DataStructures.jl", "src", "balanced_tree.jl" ], "ground_truth": "function findkeyless(t::BalancedTree23, k)\n curnode = t.rootloc\n for depthcount = 1 : t.depth - 1\n @inbounds thisnode = t.tree[curnode]\n cmp = thisnode.child3 == 0 ?\n cmp2le_nonleaf(t.ord, thisnode, k) :\n cmp3le_nonleaf(t.ord, thisnode, k)\n curnode = cmp == 1 ? thisnode.child1 :\n cmp == 2 ? thisnode.child2 : thisnode.child3\n end\n @inbounds thisnode = t.tree[curnode]\n cmp = thisnode.child3 == 0 ?\n cmp2le_leaf(t.ord, thisnode, k) :\n cmp3le_leaf(t.ord, thisnode, k)\n curnode = cmp == 1 ? thisnode.child1 :\n cmp == 2 ? thisnode.child2 : thisnode.child3\n return curnode\nend", "task_id": "DataStructures/9" }
292
309
DataStructures.jl
9
function findkeyless(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_nonleaf(t.ord, thisnode, k) : cmp3le_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_leaf(t.ord, thisnode, k) : cmp3le_leaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 return curnode end
findkeyless(t::BalancedTree23, k)
[ 292, 309 ]
function findkeyless(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_nonleaf(t.ord, thisnode, k) : cmp3le_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2le_leaf(t.ord, thisnode, k) : cmp3le_leaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 return curnode end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/balanced_tree.jl ##CHUNK 1 if newchildcount == 3 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], t.deletionchild[3], pparent, t.deletionleftkey[2], t.deletionleftkey[3]) break end @invariant newchildcount == 1 ## For the rest of this loop, we cover the case ## that p has one child. ## If newchildcount == 1 and curdepth==1, this means that ## the root of the tree has only one child. In this case, we can ## delete the root and make its one child the new root (see below). if curdepth == 1 mustdeleteroot = true break end ## We now branch on three cases depending on whether p is child1, ##CHUNK 2 ## If newchildcount == 1 and curdepth==1, this means that ## the root of the tree has only one child. In this case, we can ## delete the root and make its one child the new root (see below). if curdepth == 1 mustdeleteroot = true break end ## We now branch on three cases depending on whether p is child1, ## child2 or child3 of its parent. if t.tree[pparent].child1 == p rightsib = t.tree[pparent].child2 ## Here p is child1 and rightsib is child2. ## If rightsib has 2 children, then p and ## rightsib are merged into a single node ## that has three children. ## If rightsib has 3 children, then p and ##CHUNK 3 if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ## has never been stored in the tree. It must be stored ## as splitkey1 or splitkey2 of some ancestor of the ## deleted node, so we continue ascending the tree ## until we find a node which has p (and therefore the ## deleted node) as its descendent through its second ## or third child. ## It cannot be the case that the deleted node is ## is a descendent of the root always through ## first children, since this would mean the deleted ## node is the leftmost placeholder, which ##CHUNK 4 mustdeleteroot = false pparent = -1 ## The following loop ascends the tree and contracts nodes (reduces their ## number of children) as ## needed. If newchildcount == 2 or 3, then the ascent is terminated ## and a node is created with 2 or 3 children. ## If newchildcount == 1, then the ascent must continue since a tree ## node cannot have one child. while true pparent = t.tree[p].parent ## Simple cases when the new child count is 2 or 3 if newchildcount == 2 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], 0, pparent, t.deletionleftkey[2], defaultKey) break end ##CHUNK 5 0, pparent, t.tree[rightsib].splitkey2, defaultKey) if curdepth == t.depth replaceparent!(t.data, rc1, p) else replaceparent!(t.tree, rc1, p) end newchildcount = 2 t.deletionchild[1] = p t.deletionchild[2] = rightsib t.deletionleftkey[2] = sk1 end ## If pparent had a third child (besides p and rightsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 ##CHUNK 6 if c3 != it && c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.data[c3].k end @invariant newchildcount == 1 || newchildcount == 2 push!(t.freedatainds, it) pop!(t.useddatacells,it) defaultKey = t.tree[1].splitkey1 curdepth = t.depth mustdeleteroot = false pparent = -1 ## The following loop ascends the tree and contracts nodes (reduces their ## number of children) as ## needed. If newchildcount == 2 or 3, then the ascent is terminated ## and a node is created with 2 or 3 children. ## If newchildcount == 1, then the ascent must continue since a tree ## node cannot have one child. ##CHUNK 7 pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 2 t.deletionchild[1] = leftsib t.deletionchild[2] = p t.deletionleftkey[2] = sk2 end ## If pparent had a third child (besides p and leftsib) ## then we add this to t.deletionchild ##CHUNK 8 t.deletionchild[2] = leftsib t.deletionchild[3] = p t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionleftkey[3] = sk2 end p = pparent deletionleftkey1_valid = false end curdepth -= 1 end if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ##CHUNK 9 ## has never been stored in the tree. It must be stored ## as splitkey1 or splitkey2 of some ancestor of the ## deleted node, so we continue ascending the tree ## until we find a node which has p (and therefore the ## deleted node) as its descendent through its second ## or third child. ## It cannot be the case that the deleted node is ## is a descendent of the root always through ## first children, since this would mean the deleted ## node is the leftmost placeholder, which ## cannot be deleted. if deletionleftkey1_valid while true pparentnode = t.tree[pparent] if pparentnode.child2 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, ##CHUNK 10 macro invariant_support_statement(expr) end struct KDRec{K,D} parent::Int k::K d::D KDRec{K,D}(p::Int, k1::K, d1::D) where {K,D} = new{K,D}(p,k1,d1) KDRec{K,D}(p::Int) where {K,D} = new{K,D}(p) end ## TreeNode is an internal node of the tree. ## child1,child2,child3: ## These are the three children node numbers. ## If the node is a 2-node (rather than 3), then child3 == 0. ## If this is a leaf then child1,child2,child3 are subscripts ## of data nodes, else they are subscripts of other tree nodes. ## splitkey1: ## the minimum key of the subtree at child2. If this is a leaf Based on the information above, please generate test code for the following function: function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering} ## First we find the greatest data node that is <= k. leafind, exactfound = findkey(t, k) parent = t.data[leafind].parent ## The following code is necessary because in the case of a ## brand new tree, the initial tree and data entries were incompletely ## initialized by the constructor. In this case, the call to insert! ## underway carries ## valid K and D values, so these valid values may now be ## stored in the dummy placeholder nodes so that they no ## longer hold undefined references. if size(t.data,1) == 2 @invariant t.rootloc == 1 && t.depth == 1 t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2, t.tree[1].child3, t.tree[1].parent, k, k) t.data[1] = KDRec{K,D}(t.data[1].parent, k, d) t.data[2] = KDRec{K,D}(t.data[2].parent, k, d) end ## If we have found exactly k in the tree, then we ## replace the data associated with k and return. if exactfound && !allowdups t.data[leafind] = KDRec{K,D}(parent, k,d) return false, leafind end # We get here if k was not already found in the tree or # if duplicates are allowed. # In this case we insert a new node. depth = t.depth ord = t.ord ## Store the new data item in the tree's data array. Later ## go back and fix the parent. newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d)) push!(t.useddatacells, newind) p1 = parent newchild = newind minkeynewchild = k splitroot = false curdepth = depth existingchild = leafind ## This loop ascends the tree (i.e., follows the path from a leaf to the root) ## starting from the parent p1 of ## where the new key k will go. ## Variables updated by the loop: ## p1: parent of where the new node goes ## newchild: index of the child to be inserted ## minkeynewchild: the minimum key in the subtree rooted at newchild ## existingchild: a child of p1; the newchild must ## be inserted in the slot to the right of existingchild ## curdepth: depth of newchild ## For each 3-node we encounter ## during the ascent, we add a new child, which requires splitting ## the 3-node into two 2-nodes. Then we keep going until we hit the root. ## If we encounter a 2-node, then the ascent can stop; we can ## change the 2-node to a 3-node with the new child. while true # Let newchild1,...newchild4 be the new children of # the parent node # Initially, take the three children of the existing parent # node and set newchild4 to 0. newchild1 = t.tree[p1].child1 newchild2 = t.tree[p1].child2 minkeychild2 = t.tree[p1].splitkey1 newchild3 = t.tree[p1].child3 minkeychild3 = t.tree[p1].splitkey2 p1parent = t.tree[p1].parent newchild4 = 0 # Now figure out which of the 4 children is the new node # and insert it into newchild1 ... newchild4 if newchild1 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild2 minkeychild3 = minkeychild2 newchild2 = newchild minkeychild2 = minkeynewchild elseif newchild2 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild minkeychild3 = minkeynewchild elseif newchild3 == existingchild newchild4 = newchild minkeychild4 = minkeynewchild else throw(AssertionError("Tree structure is corrupted 1")) end # Two cases: either we need to split the tree node # if newchild4>0 else we convert a 2-node to a 3-node # if newchild4==0 if newchild4 == 0 # Change the parent from a 2-node to a 3-node t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3, p1parent, minkeychild2, minkeychild3) if curdepth == depth replaceparent!(t.data, newchild, p1) else replaceparent!(t.tree, newchild, p1) end break end # Split the parent t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0, p1parent, minkeychild2, minkeychild2) newtreenode = TreeNode{K}(newchild3, newchild4, 0, p1parent, minkeychild4, minkeychild2) newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode) if curdepth == depth replaceparent!(t.data, newchild2, p1) replaceparent!(t.data, newchild3, newparentnum) replaceparent!(t.data, newchild4, newparentnum) else replaceparent!(t.tree, newchild2, p1) replaceparent!(t.tree, newchild3, newparentnum) replaceparent!(t.tree, newchild4, newparentnum) end # Update the loop variables for the next level of the # ascension existingchild = p1 newchild = newparentnum p1 = p1parent minkeynewchild = minkeychild3 curdepth -= 1 if curdepth == 0 splitroot = true break end end # If the root has been split, then we need to add a level # to the tree that is the parent of the old root and the new node. if splitroot @invariant existingchild == t.rootloc newroot = TreeNode{K}(existingchild, newchild, 0, 0, minkeynewchild, minkeynewchild) newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot) replaceparent!(t.tree, existingchild, newrootloc) replaceparent!(t.tree, newchild, newrootloc) t.rootloc = newrootloc t.depth += 1 end return true, newind end
{ "fpath_tuple": [ "DataStructures.jl", "src", "balanced_tree.jl" ], "ground_truth": "function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}\n\n ## First we find the greatest data node that is <= k.\n leafind, exactfound = findkey(t, k)\n parent = t.data[leafind].parent\n\n ## The following code is necessary because in the case of a\n ## brand new tree, the initial tree and data entries were incompletely\n ## initialized by the constructor. In this case, the call to insert!\n ## underway carries\n ## valid K and D values, so these valid values may now be\n ## stored in the dummy placeholder nodes so that they no\n ## longer hold undefined references.\n\n if size(t.data,1) == 2\n @invariant t.rootloc == 1 && t.depth == 1\n t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2,\n t.tree[1].child3, t.tree[1].parent,\n k, k)\n t.data[1] = KDRec{K,D}(t.data[1].parent, k, d)\n t.data[2] = KDRec{K,D}(t.data[2].parent, k, d)\n end\n\n ## If we have found exactly k in the tree, then we\n ## replace the data associated with k and return.\n\n if exactfound && !allowdups\n t.data[leafind] = KDRec{K,D}(parent, k,d)\n return false, leafind\n end\n\n # We get here if k was not already found in the tree or\n # if duplicates are allowed.\n # In this case we insert a new node.\n depth = t.depth\n ord = t.ord\n\n ## Store the new data item in the tree's data array. Later\n ## go back and fix the parent.\n\n newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d))\n push!(t.useddatacells, newind)\n p1 = parent\n newchild = newind\n minkeynewchild = k\n splitroot = false\n curdepth = depth\n existingchild = leafind\n\n \n ## This loop ascends the tree (i.e., follows the path from a leaf to the root)\n ## starting from the parent p1 of\n ## where the new key k will go.\n ## Variables updated by the loop:\n ## p1: parent of where the new node goes\n ## newchild: index of the child to be inserted\n ## minkeynewchild: the minimum key in the subtree rooted at newchild\n ## existingchild: a child of p1; the newchild must\n ## be inserted in the slot to the right of existingchild\n ## curdepth: depth of newchild\n ## For each 3-node we encounter\n ## during the ascent, we add a new child, which requires splitting\n ## the 3-node into two 2-nodes. Then we keep going until we hit the root.\n ## If we encounter a 2-node, then the ascent can stop; we can\n ## change the 2-node to a 3-node with the new child.\n\n while true\n\n\n # Let newchild1,...newchild4 be the new children of\n # the parent node\n # Initially, take the three children of the existing parent\n # node and set newchild4 to 0.\n\n newchild1 = t.tree[p1].child1\n newchild2 = t.tree[p1].child2\n minkeychild2 = t.tree[p1].splitkey1\n newchild3 = t.tree[p1].child3\n minkeychild3 = t.tree[p1].splitkey2\n p1parent = t.tree[p1].parent\n newchild4 = 0\n\n # Now figure out which of the 4 children is the new node\n # and insert it into newchild1 ... newchild4\n\n if newchild1 == existingchild\n newchild4 = newchild3\n minkeychild4 = minkeychild3\n newchild3 = newchild2\n minkeychild3 = minkeychild2\n newchild2 = newchild\n minkeychild2 = minkeynewchild\n elseif newchild2 == existingchild\n newchild4 = newchild3\n minkeychild4 = minkeychild3\n newchild3 = newchild\n minkeychild3 = minkeynewchild\n elseif newchild3 == existingchild\n newchild4 = newchild\n minkeychild4 = minkeynewchild\n else\n throw(AssertionError(\"Tree structure is corrupted 1\"))\n end\n\n # Two cases: either we need to split the tree node\n # if newchild4>0 else we convert a 2-node to a 3-node\n # if newchild4==0\n\n if newchild4 == 0\n # Change the parent from a 2-node to a 3-node\n t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3,\n p1parent, minkeychild2, minkeychild3)\n if curdepth == depth\n replaceparent!(t.data, newchild, p1)\n else\n replaceparent!(t.tree, newchild, p1)\n end\n break\n end\n # Split the parent\n t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0,\n p1parent, minkeychild2, minkeychild2)\n newtreenode = TreeNode{K}(newchild3, newchild4, 0,\n p1parent, minkeychild4, minkeychild2)\n newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode)\n if curdepth == depth\n replaceparent!(t.data, newchild2, p1)\n replaceparent!(t.data, newchild3, newparentnum)\n replaceparent!(t.data, newchild4, newparentnum)\n else\n replaceparent!(t.tree, newchild2, p1)\n replaceparent!(t.tree, newchild3, newparentnum)\n replaceparent!(t.tree, newchild4, newparentnum)\n end\n # Update the loop variables for the next level of the\n # ascension\n existingchild = p1\n newchild = newparentnum\n p1 = p1parent\n minkeynewchild = minkeychild3\n curdepth -= 1\n if curdepth == 0\n splitroot = true\n break\n end\n end\n\n # If the root has been split, then we need to add a level\n # to the tree that is the parent of the old root and the new node.\n\n if splitroot\n @invariant existingchild == t.rootloc\n newroot = TreeNode{K}(existingchild, newchild, 0,\n 0, minkeynewchild, minkeynewchild)\n \n newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot)\n replaceparent!(t.tree, existingchild, newrootloc)\n replaceparent!(t.tree, newchild, newrootloc)\n t.rootloc = newrootloc\n t.depth += 1\n end\n return true, newind\nend", "task_id": "DataStructures/10" }
358
520
DataStructures.jl
10
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering} ## First we find the greatest data node that is <= k. leafind, exactfound = findkey(t, k) parent = t.data[leafind].parent ## The following code is necessary because in the case of a ## brand new tree, the initial tree and data entries were incompletely ## initialized by the constructor. In this case, the call to insert! ## underway carries ## valid K and D values, so these valid values may now be ## stored in the dummy placeholder nodes so that they no ## longer hold undefined references. if size(t.data,1) == 2 @invariant t.rootloc == 1 && t.depth == 1 t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2, t.tree[1].child3, t.tree[1].parent, k, k) t.data[1] = KDRec{K,D}(t.data[1].parent, k, d) t.data[2] = KDRec{K,D}(t.data[2].parent, k, d) end ## If we have found exactly k in the tree, then we ## replace the data associated with k and return. if exactfound && !allowdups t.data[leafind] = KDRec{K,D}(parent, k,d) return false, leafind end # We get here if k was not already found in the tree or # if duplicates are allowed. # In this case we insert a new node. depth = t.depth ord = t.ord ## Store the new data item in the tree's data array. Later ## go back and fix the parent. newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d)) push!(t.useddatacells, newind) p1 = parent newchild = newind minkeynewchild = k splitroot = false curdepth = depth existingchild = leafind ## This loop ascends the tree (i.e., follows the path from a leaf to the root) ## starting from the parent p1 of ## where the new key k will go. ## Variables updated by the loop: ## p1: parent of where the new node goes ## newchild: index of the child to be inserted ## minkeynewchild: the minimum key in the subtree rooted at newchild ## existingchild: a child of p1; the newchild must ## be inserted in the slot to the right of existingchild ## curdepth: depth of newchild ## For each 3-node we encounter ## during the ascent, we add a new child, which requires splitting ## the 3-node into two 2-nodes. Then we keep going until we hit the root. ## If we encounter a 2-node, then the ascent can stop; we can ## change the 2-node to a 3-node with the new child. while true # Let newchild1,...newchild4 be the new children of # the parent node # Initially, take the three children of the existing parent # node and set newchild4 to 0. newchild1 = t.tree[p1].child1 newchild2 = t.tree[p1].child2 minkeychild2 = t.tree[p1].splitkey1 newchild3 = t.tree[p1].child3 minkeychild3 = t.tree[p1].splitkey2 p1parent = t.tree[p1].parent newchild4 = 0 # Now figure out which of the 4 children is the new node # and insert it into newchild1 ... newchild4 if newchild1 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild2 minkeychild3 = minkeychild2 newchild2 = newchild minkeychild2 = minkeynewchild elseif newchild2 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild minkeychild3 = minkeynewchild elseif newchild3 == existingchild newchild4 = newchild minkeychild4 = minkeynewchild else throw(AssertionError("Tree structure is corrupted 1")) end # Two cases: either we need to split the tree node # if newchild4>0 else we convert a 2-node to a 3-node # if newchild4==0 if newchild4 == 0 # Change the parent from a 2-node to a 3-node t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3, p1parent, minkeychild2, minkeychild3) if curdepth == depth replaceparent!(t.data, newchild, p1) else replaceparent!(t.tree, newchild, p1) end break end # Split the parent t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0, p1parent, minkeychild2, minkeychild2) newtreenode = TreeNode{K}(newchild3, newchild4, 0, p1parent, minkeychild4, minkeychild2) newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode) if curdepth == depth replaceparent!(t.data, newchild2, p1) replaceparent!(t.data, newchild3, newparentnum) replaceparent!(t.data, newchild4, newparentnum) else replaceparent!(t.tree, newchild2, p1) replaceparent!(t.tree, newchild3, newparentnum) replaceparent!(t.tree, newchild4, newparentnum) end # Update the loop variables for the next level of the # ascension existingchild = p1 newchild = newparentnum p1 = p1parent minkeynewchild = minkeychild3 curdepth -= 1 if curdepth == 0 splitroot = true break end end # If the root has been split, then we need to add a level # to the tree that is the parent of the old root and the new node. if splitroot @invariant existingchild == t.rootloc newroot = TreeNode{K}(existingchild, newchild, 0, 0, minkeynewchild, minkeynewchild) newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot) replaceparent!(t.tree, existingchild, newrootloc) replaceparent!(t.tree, newchild, newrootloc) t.rootloc = newrootloc t.depth += 1 end return true, newind end
Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering}
[ 358, 520 ]
function Base.insert!(t::BalancedTree23{K,D,Ord}, k, d, allowdups::Bool) where {K,D,Ord <: Ordering} ## First we find the greatest data node that is <= k. leafind, exactfound = findkey(t, k) parent = t.data[leafind].parent ## The following code is necessary because in the case of a ## brand new tree, the initial tree and data entries were incompletely ## initialized by the constructor. In this case, the call to insert! ## underway carries ## valid K and D values, so these valid values may now be ## stored in the dummy placeholder nodes so that they no ## longer hold undefined references. if size(t.data,1) == 2 @invariant t.rootloc == 1 && t.depth == 1 t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2, t.tree[1].child3, t.tree[1].parent, k, k) t.data[1] = KDRec{K,D}(t.data[1].parent, k, d) t.data[2] = KDRec{K,D}(t.data[2].parent, k, d) end ## If we have found exactly k in the tree, then we ## replace the data associated with k and return. if exactfound && !allowdups t.data[leafind] = KDRec{K,D}(parent, k,d) return false, leafind end # We get here if k was not already found in the tree or # if duplicates are allowed. # In this case we insert a new node. depth = t.depth ord = t.ord ## Store the new data item in the tree's data array. Later ## go back and fix the parent. newind = push_or_reuse!(t.data, t.freedatainds, KDRec{K,D}(0,k,d)) push!(t.useddatacells, newind) p1 = parent newchild = newind minkeynewchild = k splitroot = false curdepth = depth existingchild = leafind ## This loop ascends the tree (i.e., follows the path from a leaf to the root) ## starting from the parent p1 of ## where the new key k will go. ## Variables updated by the loop: ## p1: parent of where the new node goes ## newchild: index of the child to be inserted ## minkeynewchild: the minimum key in the subtree rooted at newchild ## existingchild: a child of p1; the newchild must ## be inserted in the slot to the right of existingchild ## curdepth: depth of newchild ## For each 3-node we encounter ## during the ascent, we add a new child, which requires splitting ## the 3-node into two 2-nodes. Then we keep going until we hit the root. ## If we encounter a 2-node, then the ascent can stop; we can ## change the 2-node to a 3-node with the new child. while true # Let newchild1,...newchild4 be the new children of # the parent node # Initially, take the three children of the existing parent # node and set newchild4 to 0. newchild1 = t.tree[p1].child1 newchild2 = t.tree[p1].child2 minkeychild2 = t.tree[p1].splitkey1 newchild3 = t.tree[p1].child3 minkeychild3 = t.tree[p1].splitkey2 p1parent = t.tree[p1].parent newchild4 = 0 # Now figure out which of the 4 children is the new node # and insert it into newchild1 ... newchild4 if newchild1 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild2 minkeychild3 = minkeychild2 newchild2 = newchild minkeychild2 = minkeynewchild elseif newchild2 == existingchild newchild4 = newchild3 minkeychild4 = minkeychild3 newchild3 = newchild minkeychild3 = minkeynewchild elseif newchild3 == existingchild newchild4 = newchild minkeychild4 = minkeynewchild else throw(AssertionError("Tree structure is corrupted 1")) end # Two cases: either we need to split the tree node # if newchild4>0 else we convert a 2-node to a 3-node # if newchild4==0 if newchild4 == 0 # Change the parent from a 2-node to a 3-node t.tree[p1] = TreeNode{K}(newchild1, newchild2, newchild3, p1parent, minkeychild2, minkeychild3) if curdepth == depth replaceparent!(t.data, newchild, p1) else replaceparent!(t.tree, newchild, p1) end break end # Split the parent t.tree[p1] = TreeNode{K}(newchild1, newchild2, 0, p1parent, minkeychild2, minkeychild2) newtreenode = TreeNode{K}(newchild3, newchild4, 0, p1parent, minkeychild4, minkeychild2) newparentnum = push_or_reuse!(t.tree, t.freetreeinds, newtreenode) if curdepth == depth replaceparent!(t.data, newchild2, p1) replaceparent!(t.data, newchild3, newparentnum) replaceparent!(t.data, newchild4, newparentnum) else replaceparent!(t.tree, newchild2, p1) replaceparent!(t.tree, newchild3, newparentnum) replaceparent!(t.tree, newchild4, newparentnum) end # Update the loop variables for the next level of the # ascension existingchild = p1 newchild = newparentnum p1 = p1parent minkeynewchild = minkeychild3 curdepth -= 1 if curdepth == 0 splitroot = true break end end # If the root has been split, then we need to add a level # to the tree that is the parent of the old root and the new node. if splitroot @invariant existingchild == t.rootloc newroot = TreeNode{K}(existingchild, newchild, 0, 0, minkeynewchild, minkeynewchild) newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot) replaceparent!(t.tree, existingchild, newrootloc) replaceparent!(t.tree, newchild, newrootloc) t.rootloc = newrootloc t.depth += 1 end return true, newind end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/balanced_tree.jl ##CHUNK 1 ## prevloc0: returns the previous item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 1 if there is no previous item (i.e., we started ## from the first one in the sorted order). function prevloc0(t::BalancedTree23, i::Int) @invariant i != 1 && i in t.useddatacells ii = i @inbounds p = t.data[i].parent prevchild = 0 depthp = t.depth @inbounds while true if depthp < t.depth p = t.tree[ii].parent end if t.tree[p].child3 == ii prevchild = t.tree[p].child2 break ##CHUNK 2 ## nextloc0: returns the next item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 2 if there is no next item (i.e., we started ## from the last one in the sorted order). function nextloc0(t, i::Int) ii = i @invariant i != 2 && i in t.useddatacells @inbounds p = t.data[i].parent nextchild = 0 depthp = t.depth @inbounds while true if depthp < t.depth p = t.tree[ii].parent end if t.tree[p].child1 == ii nextchild = t.tree[p].child2 ##CHUNK 3 end if t.tree[p].child2 == ii prevchild = t.tree[p].child1 break end ii = p depthp -= 1 end @inbounds while true if depthp == t.depth return prevchild end p = prevchild c3 = t.tree[p].child3 prevchild = c3 > 0 ? c3 : t.tree[p].child2 depthp += 1 end end ## This function takes two indices into t.data and checks which ##CHUNK 4 macro invariant_support_statement(expr) end struct KDRec{K,D} parent::Int k::K d::D KDRec{K,D}(p::Int, k1::K, d1::D) where {K,D} = new{K,D}(p,k1,d1) KDRec{K,D}(p::Int) where {K,D} = new{K,D}(p) end ## TreeNode is an internal node of the tree. ## child1,child2,child3: ## These are the three children node numbers. ## If the node is a 2-node (rather than 3), then child3 == 0. ## If this is a leaf then child1,child2,child3 are subscripts ## of data nodes, else they are subscripts of other tree nodes. ## splitkey1: ## the minimum key of the subtree at child2. If this is a leaf ##CHUNK 5 return prevchild end p = prevchild c3 = t.tree[p].child3 prevchild = c3 > 0 ? c3 : t.tree[p].child2 depthp += 1 end end ## This function takes two indices into t.data and checks which ## one comes first in the sorted order by chasing them both ## up the tree until a common ancestor is found. ## The return value is -1 if i1 precedes i2, 0 if i1 == i2 ##, 1 if i2 precedes i1. function compareInd(t::BalancedTree23, i1::Int, i2::Int) @invariant(i1 in t.useddatacells && i2 in t.useddatacells) if i1 == i2 return 0 end ##CHUNK 6 if depthp == t.depth return nextchild end p = nextchild nextchild = t.tree[p].child1 depthp += 1 end end ## prevloc0: returns the previous item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 1 if there is no previous item (i.e., we started ## from the first one in the sorted order). function prevloc0(t::BalancedTree23, i::Int) @invariant i != 1 && i in t.useddatacells ii = i ##CHUNK 7 leafind, exactfound = findkey(t, k) parent = t.data[leafind].parent ## The following code is necessary because in the case of a ## brand new tree, the initial tree and data entries were incompletely ## initialized by the constructor. In this case, the call to insert! ## underway carries ## valid K and D values, so these valid values may now be ## stored in the dummy placeholder nodes so that they no ## longer hold undefined references. if size(t.data,1) == 2 @invariant t.rootloc == 1 && t.depth == 1 t.tree[1] = TreeNode{K}(t.tree[1].child1, t.tree[1].child2, t.tree[1].child3, t.tree[1].parent, k, k) t.data[1] = KDRec{K,D}(t.data[1].parent, k, d) t.data[2] = KDRec{K,D}(t.data[2].parent, k, d) end ##CHUNK 8 ## then it is the key of child2. ## splitkey2: ## if child3 > 0 then splitkey2 is the minimum key of the subtree at child3. ## If this is a leaf, then it is the key of child3. ## Again, there are two constructors for the same reason mentioned above. struct TreeNode{K} child1::Int child2::Int child3::Int parent::Int splitkey1::K splitkey2::K TreeNode{K}(::Type{K}, c1::Int, c2::Int, c3::Int, p::Int) where {K} = new{K}(c1, c2, c3, p) TreeNode{K}(c1::Int, c2::Int, c3::Int, p::Int, sk1::K, sk2::K) where {K} = new{K}(c1, c2, c3, p, sk1, sk2) end ## The next two functions are called to initialize the tree ##CHUNK 9 0, minkeynewchild, minkeynewchild) newrootloc = push_or_reuse!(t.tree, t.freetreeinds, newroot) replaceparent!(t.tree, existingchild, newrootloc) replaceparent!(t.tree, newchild, newrootloc) t.rootloc = newrootloc t.depth += 1 end return true, newind end ## nextloc0: returns the next item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 2 if there is no next item (i.e., we started ## from the last one in the sorted order). function nextloc0(t, i::Int) ii = i ##CHUNK 10 ## where the given key lives (if it is present), or ## if the key is not present, to the lower bound for the key, ## i.e., the data item that comes immediately before it. ## If there are multiple equal keys, then it finds the last one. ## It returns the index of the key found and a boolean indicating ## whether the exact key was found or not. function findkey(t::BalancedTree23, k) curnode = t.rootloc for depthcount = 1 : t.depth - 1 @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_nonleaf(t.ord, thisnode, k) : cmp3_nonleaf(t.ord, thisnode, k) curnode = cmp == 1 ? thisnode.child1 : cmp == 2 ? thisnode.child2 : thisnode.child3 end @inbounds thisnode = t.tree[curnode] cmp = thisnode.child3 == 0 ? cmp2_leaf(t.ord, thisnode, k) : Based on the information above, please generate test code for the following function: function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering} ## Put the cell indexed by 'it' into the deletion list. ## ## Create the following data items maintained in the ## upcoming loop. ## ## p is a tree-node ancestor of the deleted node ## The children of p are stored in ## t.deletionchild[..] ## The number of these children is newchildcount, which is 1, 2 or 3. ## The keys that lower bound the children ## are stored in t.deletionleftkey[..] ## There is a special case for t.deletionleftkey[1]; the ## flag deletionleftkey1_valid indicates that the left key ## for the immediate right neighbor of the ## deleted node has not yet been been stored in the tree. ## Once it is stored, t.deletionleftkey[1] is no longer needed ## or used. ## The flag mustdeleteroot means that the tree has contracted ## enough that it loses a level. p = t.data[it].parent newchildcount = 0 c1 = t.tree[p].child1 deletionleftkey1_valid = true if c1 != it deletionleftkey1_valid = false newchildcount += 1 t.deletionchild[newchildcount] = c1 t.deletionleftkey[newchildcount] = t.data[c1].k end c2 = t.tree[p].child2 if c2 != it newchildcount += 1 t.deletionchild[newchildcount] = c2 t.deletionleftkey[newchildcount] = t.data[c2].k end c3 = t.tree[p].child3 if c3 != it && c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.data[c3].k end @invariant newchildcount == 1 || newchildcount == 2 push!(t.freedatainds, it) pop!(t.useddatacells,it) defaultKey = t.tree[1].splitkey1 curdepth = t.depth mustdeleteroot = false pparent = -1 ## The following loop ascends the tree and contracts nodes (reduces their ## number of children) as ## needed. If newchildcount == 2 or 3, then the ascent is terminated ## and a node is created with 2 or 3 children. ## If newchildcount == 1, then the ascent must continue since a tree ## node cannot have one child. while true pparent = t.tree[p].parent ## Simple cases when the new child count is 2 or 3 if newchildcount == 2 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], 0, pparent, t.deletionleftkey[2], defaultKey) break end if newchildcount == 3 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], t.deletionchild[3], pparent, t.deletionleftkey[2], t.deletionleftkey[3]) break end @invariant newchildcount == 1 ## For the rest of this loop, we cover the case ## that p has one child. ## If newchildcount == 1 and curdepth==1, this means that ## the root of the tree has only one child. In this case, we can ## delete the root and make its one child the new root (see below). if curdepth == 1 mustdeleteroot = true break end ## We now branch on three cases depending on whether p is child1, ## child2 or child3 of its parent. if t.tree[pparent].child1 == p rightsib = t.tree[pparent].child2 ## Here p is child1 and rightsib is child2. ## If rightsib has 2 children, then p and ## rightsib are merged into a single node ## that has three children. ## If rightsib has 3 children, then p and ## rightsib are reformed so that each has ## two children. if t.tree[rightsib].child3 == 0 rc1 = t.tree[rightsib].child1 rc2 = t.tree[rightsib].child2 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, rc2, pparent, t.tree[pparent].splitkey1, t.tree[rightsib].splitkey1) if curdepth == t.depth replaceparent!(t.data, rc1, p) replaceparent!(t.data, rc2, p) else replaceparent!(t.tree, rc1, p) replaceparent!(t.tree, rc2, p) end push!(t.freetreeinds, rightsib) newchildcount = 1 t.deletionchild[1] = p else rc1 = t.tree[rightsib].child1 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0, pparent, t.tree[pparent].splitkey1, defaultKey) sk1 = t.tree[rightsib].splitkey1 t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2, t.tree[rightsib].child3, 0, pparent, t.tree[rightsib].splitkey2, defaultKey) if curdepth == t.depth replaceparent!(t.data, rc1, p) else replaceparent!(t.tree, rc1, p) end newchildcount = 2 t.deletionchild[1] = p t.deletionchild[2] = rightsib t.deletionleftkey[2] = sk1 end ## If pparent had a third child (besides p and rightsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent elseif t.tree[pparent].child2 == p ## Here p is child2 and leftsib is child1. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. leftsib = t.tree[pparent].child1 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey1 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 1 t.deletionchild[1] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 2 t.deletionchild[1] = leftsib t.deletionchild[2] = p t.deletionleftkey[2] = sk2 end ## If pparent had a third child (besides p and leftsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent deletionleftkey1_valid = false else ## Here p is child3 and leftsib is child2. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. @invariant t.tree[pparent].child3 == p leftsib = t.tree[pparent].child2 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey2 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 2 t.deletionchild[1] = t.tree[pparent].child1 t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionchild[2] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 3 t.deletionchild[1] = t.tree[pparent].child1 t.deletionchild[2] = leftsib t.deletionchild[3] = p t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionleftkey[3] = sk2 end p = pparent deletionleftkey1_valid = false end curdepth -= 1 end if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ## has never been stored in the tree. It must be stored ## as splitkey1 or splitkey2 of some ancestor of the ## deleted node, so we continue ascending the tree ## until we find a node which has p (and therefore the ## deleted node) as its descendent through its second ## or third child. ## It cannot be the case that the deleted node is ## is a descendent of the root always through ## first children, since this would mean the deleted ## node is the leftmost placeholder, which ## cannot be deleted. if deletionleftkey1_valid while true pparentnode = t.tree[pparent] if pparentnode.child2 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, t.deletionleftkey[1], pparentnode.splitkey2) break elseif pparentnode.child3 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, pparentnode.splitkey1, t.deletionleftkey[1]) break else p = pparent pparent = pparentnode.parent curdepth -= 1 @invariant curdepth > 0 end end end return nothing end
{ "fpath_tuple": [ "DataStructures.jl", "src", "balanced_tree.jl" ], "ground_truth": "function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}\n\n ## Put the cell indexed by 'it' into the deletion list.\n ##\n ## Create the following data items maintained in the\n ## upcoming loop.\n ##\n ## p is a tree-node ancestor of the deleted node\n ## The children of p are stored in\n ## t.deletionchild[..]\n ## The number of these children is newchildcount, which is 1, 2 or 3.\n ## The keys that lower bound the children\n ## are stored in t.deletionleftkey[..]\n ## There is a special case for t.deletionleftkey[1]; the\n ## flag deletionleftkey1_valid indicates that the left key\n ## for the immediate right neighbor of the\n ## deleted node has not yet been been stored in the tree.\n ## Once it is stored, t.deletionleftkey[1] is no longer needed\n ## or used.\n ## The flag mustdeleteroot means that the tree has contracted\n ## enough that it loses a level.\n\n p = t.data[it].parent\n newchildcount = 0\n c1 = t.tree[p].child1\n deletionleftkey1_valid = true\n if c1 != it\n deletionleftkey1_valid = false\n newchildcount += 1\n t.deletionchild[newchildcount] = c1\n t.deletionleftkey[newchildcount] = t.data[c1].k\n end\n c2 = t.tree[p].child2\n if c2 != it\n newchildcount += 1\n t.deletionchild[newchildcount] = c2\n t.deletionleftkey[newchildcount] = t.data[c2].k\n end\n c3 = t.tree[p].child3\n if c3 != it && c3 > 0\n newchildcount += 1\n t.deletionchild[newchildcount] = c3\n t.deletionleftkey[newchildcount] = t.data[c3].k\n end\n @invariant newchildcount == 1 || newchildcount == 2\n push!(t.freedatainds, it)\n pop!(t.useddatacells,it)\n defaultKey = t.tree[1].splitkey1\n curdepth = t.depth\n mustdeleteroot = false\n pparent = -1\n\n ## The following loop ascends the tree and contracts nodes (reduces their\n ## number of children) as\n ## needed. If newchildcount == 2 or 3, then the ascent is terminated\n ## and a node is created with 2 or 3 children.\n ## If newchildcount == 1, then the ascent must continue since a tree\n ## node cannot have one child.\n\n while true\n pparent = t.tree[p].parent\n ## Simple cases when the new child count is 2 or 3\n if newchildcount == 2\n t.tree[p] = TreeNode{K}(t.deletionchild[1],\n t.deletionchild[2], 0, pparent,\n t.deletionleftkey[2], defaultKey)\n\n break\n end\n if newchildcount == 3\n t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2],\n t.deletionchild[3], pparent,\n t.deletionleftkey[2], t.deletionleftkey[3])\n break\n end\n @invariant newchildcount == 1\n ## For the rest of this loop, we cover the case\n ## that p has one child.\n\n ## If newchildcount == 1 and curdepth==1, this means that\n ## the root of the tree has only one child. In this case, we can\n ## delete the root and make its one child the new root (see below).\n\n if curdepth == 1\n mustdeleteroot = true\n break\n end\n\n ## We now branch on three cases depending on whether p is child1,\n ## child2 or child3 of its parent.\n\n if t.tree[pparent].child1 == p\n rightsib = t.tree[pparent].child2\n\n ## Here p is child1 and rightsib is child2.\n ## If rightsib has 2 children, then p and\n ## rightsib are merged into a single node\n ## that has three children.\n ## If rightsib has 3 children, then p and\n ## rightsib are reformed so that each has\n ## two children.\n\n if t.tree[rightsib].child3 == 0\n rc1 = t.tree[rightsib].child1\n rc2 = t.tree[rightsib].child2\n t.tree[p] = TreeNode{K}(t.deletionchild[1],\n rc1, rc2,\n pparent,\n t.tree[pparent].splitkey1,\n t.tree[rightsib].splitkey1)\n if curdepth == t.depth\n replaceparent!(t.data, rc1, p)\n replaceparent!(t.data, rc2, p)\n else\n replaceparent!(t.tree, rc1, p)\n replaceparent!(t.tree, rc2, p)\n end\n push!(t.freetreeinds, rightsib)\n newchildcount = 1\n t.deletionchild[1] = p\n else\n rc1 = t.tree[rightsib].child1\n t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0,\n pparent,\n t.tree[pparent].splitkey1,\n defaultKey)\n sk1 = t.tree[rightsib].splitkey1\n t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2,\n t.tree[rightsib].child3,\n 0,\n pparent,\n t.tree[rightsib].splitkey2,\n defaultKey)\n if curdepth == t.depth\n replaceparent!(t.data, rc1, p)\n else\n replaceparent!(t.tree, rc1, p)\n end\n newchildcount = 2\n t.deletionchild[1] = p\n t.deletionchild[2] = rightsib\n t.deletionleftkey[2] = sk1\n end\n\n ## If pparent had a third child (besides p and rightsib)\n ## then we add this to t.deletionchild\n\n c3 = t.tree[pparent].child3\n if c3 > 0\n newchildcount += 1\n t.deletionchild[newchildcount] = c3\n t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2\n end\n p = pparent\n elseif t.tree[pparent].child2 == p\n\n ## Here p is child2 and leftsib is child1.\n ## If leftsib has 2 children, then p and\n ## leftsib are merged into a single node\n ## that has three children.\n ## If leftsib has 3 children, then p and\n ## leftsib are reformed so that each has\n ## two children.\n\n leftsib = t.tree[pparent].child1\n lk = deletionleftkey1_valid ?\n t.deletionleftkey[1] :\n t.tree[pparent].splitkey1\n if t.tree[leftsib].child3 == 0\n lc1 = t.tree[leftsib].child1\n lc2 = t.tree[leftsib].child2\n t.tree[p] = TreeNode{K}(lc1, lc2,\n t.deletionchild[1],\n pparent,\n t.tree[leftsib].splitkey1,\n lk)\n if curdepth == t.depth\n replaceparent!(t.data, lc1, p)\n replaceparent!(t.data, lc2, p)\n else\n replaceparent!(t.tree, lc1, p)\n replaceparent!(t.tree, lc2, p)\n end\n push!(t.freetreeinds, leftsib)\n newchildcount = 1\n t.deletionchild[1] = p\n else\n lc3 = t.tree[leftsib].child3\n t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,\n pparent, lk, defaultKey)\n sk2 = t.tree[leftsib].splitkey2\n t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,\n t.tree[leftsib].child2,\n 0, pparent,\n t.tree[leftsib].splitkey1,\n defaultKey)\n if curdepth == t.depth\n replaceparent!(t.data, lc3, p)\n else\n replaceparent!(t.tree, lc3, p)\n end\n newchildcount = 2\n t.deletionchild[1] = leftsib\n t.deletionchild[2] = p\n t.deletionleftkey[2] = sk2\n end\n\n ## If pparent had a third child (besides p and leftsib)\n ## then we add this to t.deletionchild\n\n c3 = t.tree[pparent].child3\n if c3 > 0\n newchildcount += 1\n t.deletionchild[newchildcount] = c3\n t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2\n end\n p = pparent\n deletionleftkey1_valid = false\n else\n ## Here p is child3 and leftsib is child2.\n ## If leftsib has 2 children, then p and\n ## leftsib are merged into a single node\n ## that has three children.\n ## If leftsib has 3 children, then p and\n ## leftsib are reformed so that each has\n ## two children.\n\n @invariant t.tree[pparent].child3 == p\n leftsib = t.tree[pparent].child2\n lk = deletionleftkey1_valid ?\n t.deletionleftkey[1] :\n t.tree[pparent].splitkey2\n if t.tree[leftsib].child3 == 0\n lc1 = t.tree[leftsib].child1\n lc2 = t.tree[leftsib].child2\n t.tree[p] = TreeNode{K}(lc1, lc2,\n t.deletionchild[1],\n pparent,\n t.tree[leftsib].splitkey1,\n lk)\n if curdepth == t.depth\n replaceparent!(t.data, lc1, p)\n replaceparent!(t.data, lc2, p)\n else\n replaceparent!(t.tree, lc1, p)\n replaceparent!(t.tree, lc2, p)\n end\n push!(t.freetreeinds, leftsib)\n newchildcount = 2\n t.deletionchild[1] = t.tree[pparent].child1\n t.deletionleftkey[2] = t.tree[pparent].splitkey1\n t.deletionchild[2] = p\n else\n lc3 = t.tree[leftsib].child3\n t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0,\n pparent, lk, defaultKey)\n sk2 = t.tree[leftsib].splitkey2\n t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1,\n t.tree[leftsib].child2,\n 0, pparent,\n t.tree[leftsib].splitkey1,\n defaultKey)\n if curdepth == t.depth\n replaceparent!(t.data, lc3, p)\n else\n replaceparent!(t.tree, lc3, p)\n end\n newchildcount = 3\n t.deletionchild[1] = t.tree[pparent].child1\n t.deletionchild[2] = leftsib\n t.deletionchild[3] = p\n t.deletionleftkey[2] = t.tree[pparent].splitkey1\n t.deletionleftkey[3] = sk2\n end\n p = pparent\n deletionleftkey1_valid = false\n end\n curdepth -= 1\n end\n if mustdeleteroot\n @invariant !deletionleftkey1_valid\n @invariant p == t.rootloc\n t.rootloc = t.deletionchild[1]\n t.depth -= 1\n push!(t.freetreeinds, p)\n end\n\n ## If deletionleftkey1_valid, this means that the new\n ## min key of the deleted node and its right neighbors\n ## has never been stored in the tree. It must be stored\n ## as splitkey1 or splitkey2 of some ancestor of the\n ## deleted node, so we continue ascending the tree\n ## until we find a node which has p (and therefore the\n ## deleted node) as its descendent through its second\n ## or third child.\n ## It cannot be the case that the deleted node is\n ## is a descendent of the root always through\n ## first children, since this would mean the deleted\n ## node is the leftmost placeholder, which\n ## cannot be deleted.\n\n if deletionleftkey1_valid\n while true\n pparentnode = t.tree[pparent]\n if pparentnode.child2 == p\n t.tree[pparent] = TreeNode{K}(pparentnode.child1,\n pparentnode.child2,\n pparentnode.child3,\n pparentnode.parent,\n t.deletionleftkey[1],\n pparentnode.splitkey2)\n break\n elseif pparentnode.child3 == p\n t.tree[pparent] = TreeNode{K}(pparentnode.child1,\n pparentnode.child2,\n pparentnode.child3,\n pparentnode.parent,\n pparentnode.splitkey1,\n t.deletionleftkey[1])\n break\n else\n p = pparent\n pparent = pparentnode.parent\n curdepth -= 1\n @invariant curdepth > 0\n end\n end\n end\n return nothing\nend", "task_id": "DataStructures/11" }
655
984
DataStructures.jl
11
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering} ## Put the cell indexed by 'it' into the deletion list. ## ## Create the following data items maintained in the ## upcoming loop. ## ## p is a tree-node ancestor of the deleted node ## The children of p are stored in ## t.deletionchild[..] ## The number of these children is newchildcount, which is 1, 2 or 3. ## The keys that lower bound the children ## are stored in t.deletionleftkey[..] ## There is a special case for t.deletionleftkey[1]; the ## flag deletionleftkey1_valid indicates that the left key ## for the immediate right neighbor of the ## deleted node has not yet been been stored in the tree. ## Once it is stored, t.deletionleftkey[1] is no longer needed ## or used. ## The flag mustdeleteroot means that the tree has contracted ## enough that it loses a level. p = t.data[it].parent newchildcount = 0 c1 = t.tree[p].child1 deletionleftkey1_valid = true if c1 != it deletionleftkey1_valid = false newchildcount += 1 t.deletionchild[newchildcount] = c1 t.deletionleftkey[newchildcount] = t.data[c1].k end c2 = t.tree[p].child2 if c2 != it newchildcount += 1 t.deletionchild[newchildcount] = c2 t.deletionleftkey[newchildcount] = t.data[c2].k end c3 = t.tree[p].child3 if c3 != it && c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.data[c3].k end @invariant newchildcount == 1 || newchildcount == 2 push!(t.freedatainds, it) pop!(t.useddatacells,it) defaultKey = t.tree[1].splitkey1 curdepth = t.depth mustdeleteroot = false pparent = -1 ## The following loop ascends the tree and contracts nodes (reduces their ## number of children) as ## needed. If newchildcount == 2 or 3, then the ascent is terminated ## and a node is created with 2 or 3 children. ## If newchildcount == 1, then the ascent must continue since a tree ## node cannot have one child. while true pparent = t.tree[p].parent ## Simple cases when the new child count is 2 or 3 if newchildcount == 2 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], 0, pparent, t.deletionleftkey[2], defaultKey) break end if newchildcount == 3 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], t.deletionchild[3], pparent, t.deletionleftkey[2], t.deletionleftkey[3]) break end @invariant newchildcount == 1 ## For the rest of this loop, we cover the case ## that p has one child. ## If newchildcount == 1 and curdepth==1, this means that ## the root of the tree has only one child. In this case, we can ## delete the root and make its one child the new root (see below). if curdepth == 1 mustdeleteroot = true break end ## We now branch on three cases depending on whether p is child1, ## child2 or child3 of its parent. if t.tree[pparent].child1 == p rightsib = t.tree[pparent].child2 ## Here p is child1 and rightsib is child2. ## If rightsib has 2 children, then p and ## rightsib are merged into a single node ## that has three children. ## If rightsib has 3 children, then p and ## rightsib are reformed so that each has ## two children. if t.tree[rightsib].child3 == 0 rc1 = t.tree[rightsib].child1 rc2 = t.tree[rightsib].child2 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, rc2, pparent, t.tree[pparent].splitkey1, t.tree[rightsib].splitkey1) if curdepth == t.depth replaceparent!(t.data, rc1, p) replaceparent!(t.data, rc2, p) else replaceparent!(t.tree, rc1, p) replaceparent!(t.tree, rc2, p) end push!(t.freetreeinds, rightsib) newchildcount = 1 t.deletionchild[1] = p else rc1 = t.tree[rightsib].child1 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0, pparent, t.tree[pparent].splitkey1, defaultKey) sk1 = t.tree[rightsib].splitkey1 t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2, t.tree[rightsib].child3, 0, pparent, t.tree[rightsib].splitkey2, defaultKey) if curdepth == t.depth replaceparent!(t.data, rc1, p) else replaceparent!(t.tree, rc1, p) end newchildcount = 2 t.deletionchild[1] = p t.deletionchild[2] = rightsib t.deletionleftkey[2] = sk1 end ## If pparent had a third child (besides p and rightsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent elseif t.tree[pparent].child2 == p ## Here p is child2 and leftsib is child1. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. leftsib = t.tree[pparent].child1 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey1 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 1 t.deletionchild[1] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 2 t.deletionchild[1] = leftsib t.deletionchild[2] = p t.deletionleftkey[2] = sk2 end ## If pparent had a third child (besides p and leftsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent deletionleftkey1_valid = false else ## Here p is child3 and leftsib is child2. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. @invariant t.tree[pparent].child3 == p leftsib = t.tree[pparent].child2 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey2 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 2 t.deletionchild[1] = t.tree[pparent].child1 t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionchild[2] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 3 t.deletionchild[1] = t.tree[pparent].child1 t.deletionchild[2] = leftsib t.deletionchild[3] = p t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionleftkey[3] = sk2 end p = pparent deletionleftkey1_valid = false end curdepth -= 1 end if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ## has never been stored in the tree. It must be stored ## as splitkey1 or splitkey2 of some ancestor of the ## deleted node, so we continue ascending the tree ## until we find a node which has p (and therefore the ## deleted node) as its descendent through its second ## or third child. ## It cannot be the case that the deleted node is ## is a descendent of the root always through ## first children, since this would mean the deleted ## node is the leftmost placeholder, which ## cannot be deleted. if deletionleftkey1_valid while true pparentnode = t.tree[pparent] if pparentnode.child2 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, t.deletionleftkey[1], pparentnode.splitkey2) break elseif pparentnode.child3 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, pparentnode.splitkey1, t.deletionleftkey[1]) break else p = pparent pparent = pparentnode.parent curdepth -= 1 @invariant curdepth > 0 end end end return nothing end
Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering}
[ 655, 984 ]
function Base.delete!(t::BalancedTree23{K,D,Ord}, it::Int) where {K,D,Ord<:Ordering} ## Put the cell indexed by 'it' into the deletion list. ## ## Create the following data items maintained in the ## upcoming loop. ## ## p is a tree-node ancestor of the deleted node ## The children of p are stored in ## t.deletionchild[..] ## The number of these children is newchildcount, which is 1, 2 or 3. ## The keys that lower bound the children ## are stored in t.deletionleftkey[..] ## There is a special case for t.deletionleftkey[1]; the ## flag deletionleftkey1_valid indicates that the left key ## for the immediate right neighbor of the ## deleted node has not yet been been stored in the tree. ## Once it is stored, t.deletionleftkey[1] is no longer needed ## or used. ## The flag mustdeleteroot means that the tree has contracted ## enough that it loses a level. p = t.data[it].parent newchildcount = 0 c1 = t.tree[p].child1 deletionleftkey1_valid = true if c1 != it deletionleftkey1_valid = false newchildcount += 1 t.deletionchild[newchildcount] = c1 t.deletionleftkey[newchildcount] = t.data[c1].k end c2 = t.tree[p].child2 if c2 != it newchildcount += 1 t.deletionchild[newchildcount] = c2 t.deletionleftkey[newchildcount] = t.data[c2].k end c3 = t.tree[p].child3 if c3 != it && c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.data[c3].k end @invariant newchildcount == 1 || newchildcount == 2 push!(t.freedatainds, it) pop!(t.useddatacells,it) defaultKey = t.tree[1].splitkey1 curdepth = t.depth mustdeleteroot = false pparent = -1 ## The following loop ascends the tree and contracts nodes (reduces their ## number of children) as ## needed. If newchildcount == 2 or 3, then the ascent is terminated ## and a node is created with 2 or 3 children. ## If newchildcount == 1, then the ascent must continue since a tree ## node cannot have one child. while true pparent = t.tree[p].parent ## Simple cases when the new child count is 2 or 3 if newchildcount == 2 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], 0, pparent, t.deletionleftkey[2], defaultKey) break end if newchildcount == 3 t.tree[p] = TreeNode{K}(t.deletionchild[1], t.deletionchild[2], t.deletionchild[3], pparent, t.deletionleftkey[2], t.deletionleftkey[3]) break end @invariant newchildcount == 1 ## For the rest of this loop, we cover the case ## that p has one child. ## If newchildcount == 1 and curdepth==1, this means that ## the root of the tree has only one child. In this case, we can ## delete the root and make its one child the new root (see below). if curdepth == 1 mustdeleteroot = true break end ## We now branch on three cases depending on whether p is child1, ## child2 or child3 of its parent. if t.tree[pparent].child1 == p rightsib = t.tree[pparent].child2 ## Here p is child1 and rightsib is child2. ## If rightsib has 2 children, then p and ## rightsib are merged into a single node ## that has three children. ## If rightsib has 3 children, then p and ## rightsib are reformed so that each has ## two children. if t.tree[rightsib].child3 == 0 rc1 = t.tree[rightsib].child1 rc2 = t.tree[rightsib].child2 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, rc2, pparent, t.tree[pparent].splitkey1, t.tree[rightsib].splitkey1) if curdepth == t.depth replaceparent!(t.data, rc1, p) replaceparent!(t.data, rc2, p) else replaceparent!(t.tree, rc1, p) replaceparent!(t.tree, rc2, p) end push!(t.freetreeinds, rightsib) newchildcount = 1 t.deletionchild[1] = p else rc1 = t.tree[rightsib].child1 t.tree[p] = TreeNode{K}(t.deletionchild[1], rc1, 0, pparent, t.tree[pparent].splitkey1, defaultKey) sk1 = t.tree[rightsib].splitkey1 t.tree[rightsib] = TreeNode{K}(t.tree[rightsib].child2, t.tree[rightsib].child3, 0, pparent, t.tree[rightsib].splitkey2, defaultKey) if curdepth == t.depth replaceparent!(t.data, rc1, p) else replaceparent!(t.tree, rc1, p) end newchildcount = 2 t.deletionchild[1] = p t.deletionchild[2] = rightsib t.deletionleftkey[2] = sk1 end ## If pparent had a third child (besides p and rightsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent elseif t.tree[pparent].child2 == p ## Here p is child2 and leftsib is child1. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. leftsib = t.tree[pparent].child1 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey1 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 1 t.deletionchild[1] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 2 t.deletionchild[1] = leftsib t.deletionchild[2] = p t.deletionleftkey[2] = sk2 end ## If pparent had a third child (besides p and leftsib) ## then we add this to t.deletionchild c3 = t.tree[pparent].child3 if c3 > 0 newchildcount += 1 t.deletionchild[newchildcount] = c3 t.deletionleftkey[newchildcount] = t.tree[pparent].splitkey2 end p = pparent deletionleftkey1_valid = false else ## Here p is child3 and leftsib is child2. ## If leftsib has 2 children, then p and ## leftsib are merged into a single node ## that has three children. ## If leftsib has 3 children, then p and ## leftsib are reformed so that each has ## two children. @invariant t.tree[pparent].child3 == p leftsib = t.tree[pparent].child2 lk = deletionleftkey1_valid ? t.deletionleftkey[1] : t.tree[pparent].splitkey2 if t.tree[leftsib].child3 == 0 lc1 = t.tree[leftsib].child1 lc2 = t.tree[leftsib].child2 t.tree[p] = TreeNode{K}(lc1, lc2, t.deletionchild[1], pparent, t.tree[leftsib].splitkey1, lk) if curdepth == t.depth replaceparent!(t.data, lc1, p) replaceparent!(t.data, lc2, p) else replaceparent!(t.tree, lc1, p) replaceparent!(t.tree, lc2, p) end push!(t.freetreeinds, leftsib) newchildcount = 2 t.deletionchild[1] = t.tree[pparent].child1 t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionchild[2] = p else lc3 = t.tree[leftsib].child3 t.tree[p] = TreeNode{K}(lc3, t.deletionchild[1], 0, pparent, lk, defaultKey) sk2 = t.tree[leftsib].splitkey2 t.tree[leftsib] = TreeNode{K}(t.tree[leftsib].child1, t.tree[leftsib].child2, 0, pparent, t.tree[leftsib].splitkey1, defaultKey) if curdepth == t.depth replaceparent!(t.data, lc3, p) else replaceparent!(t.tree, lc3, p) end newchildcount = 3 t.deletionchild[1] = t.tree[pparent].child1 t.deletionchild[2] = leftsib t.deletionchild[3] = p t.deletionleftkey[2] = t.tree[pparent].splitkey1 t.deletionleftkey[3] = sk2 end p = pparent deletionleftkey1_valid = false end curdepth -= 1 end if mustdeleteroot @invariant !deletionleftkey1_valid @invariant p == t.rootloc t.rootloc = t.deletionchild[1] t.depth -= 1 push!(t.freetreeinds, p) end ## If deletionleftkey1_valid, this means that the new ## min key of the deleted node and its right neighbors ## has never been stored in the tree. It must be stored ## as splitkey1 or splitkey2 of some ancestor of the ## deleted node, so we continue ascending the tree ## until we find a node which has p (and therefore the ## deleted node) as its descendent through its second ## or third child. ## It cannot be the case that the deleted node is ## is a descendent of the root always through ## first children, since this would mean the deleted ## node is the leftmost placeholder, which ## cannot be deleted. if deletionleftkey1_valid while true pparentnode = t.tree[pparent] if pparentnode.child2 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, t.deletionleftkey[1], pparentnode.splitkey2) break elseif pparentnode.child3 == p t.tree[pparent] = TreeNode{K}(pparentnode.child1, pparentnode.child2, pparentnode.child3, pparentnode.parent, pparentnode.splitkey1, t.deletionleftkey[1]) break else p = pparent pparent = pparentnode.parent curdepth -= 1 @invariant curdepth > 0 end end end return nothing end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 pop!(s, last(s)) end function Base.pop!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : throw(KeyError(n)) end function Base.pop!(s::IntSet, n::Integer, default) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : default end function Base.pop!(f::Function, s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : f() end _delete!(s::IntSet, n::Integer) = _setint!(s, n, s.inverse) Base.delete!(s::IntSet, n::Integer) = n < 0 ? s : _delete!(s, n) Base.popfirst!(s::IntSet) = pop!(s, first(s)) Base.empty!(s::IntSet) = (fill!(s.bits, false); s.inverse = false; s) Base.isempty(s::IntSet) = s.inverse ? length(s.bits) == typemax(Int) && all(s.bits) : !any(s.bits) #FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end #FILE: DataStructures.jl/src/sparse_int_set.jl ##CHUNK 1 Base.union(s::SparseIntSet, ns) = union!(copy(s), ns) function Base.union!(s::SparseIntSet, ns) for n in ns push!(s, n) end return s end Base.intersect(s1::SparseIntSet) = copy(s1) Base.intersect(s1::SparseIntSet, ss...) = intersect(s1, intersect(ss...)) function Base.intersect(s1::SparseIntSet, ns) s = SparseIntSet() for n in ns n in s1 && push!(s, n) end return s end Base.intersect!(s1::SparseIntSet, ss...) = intersect!(s1, intersect(ss...)) #FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T #FILE: DataStructures.jl/src/delegate.jl ##CHUNK 1 funcnames = targets.args n = length(funcnames) fdefs = Vector{Any}(undef, n) for i in 1:n funcname = esc(funcnames[i]) fdefs[i] = quote ($funcname)(a::($typename), args...) = (($funcname)(a.$fieldname, args...); a) end end return Expr(:block, fdefs...) end #CURRENT FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end @inline function _buffer_index(cb::CircularBuffer, i::Int) n = cb.capacity idx = cb.first + i - 1 return ifelse(idx > n, idx - n, idx) end """ cb[i] ##CHUNK 2 # if full, increment and overwrite, otherwise push if cb.length == cb.capacity cb.first = (cb.first == cb.capacity ? 1 : cb.first + 1) else cb.length += 1 end @inbounds cb.buffer[_buffer_index(cb, cb.length)] = data_converted return cb end """ popfirst!(cb::CircularBuffer) Remove the element from the front of the `CircularBuffer`. """ function Base.popfirst!(cb::CircularBuffer) @boundscheck (cb.length == 0) && throw(ArgumentError("array must be non-empty")) i = cb.first cb.first = (cb.first + 1 > cb.capacity ? 1 : cb.first + 1) ##CHUNK 3 function Base.pushfirst!(cb::CircularBuffer, data) # if full, decrement and overwrite, otherwise pushfirst cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1) if length(cb) < cb.capacity cb.length += 1 end @inbounds cb.buffer[cb.first] = data return cb end """ append!(cb::CircularBuffer, datavec::AbstractVector) Push at most last `capacity` items. """ function Base.append!(cb::CircularBuffer, datavec::AbstractVector) # push at most last `capacity` items n = length(datavec) for i in max(1, n-capacity(cb)+1):n push!(cb, datavec[i]) ##CHUNK 4 cb.length -= 1 return @inbounds cb.buffer[i] end """ pushfirst!(cb::CircularBuffer, data) Insert one or more items at the beginning of CircularBuffer and overwrite back if full. """ function Base.pushfirst!(cb::CircularBuffer, data) # if full, decrement and overwrite, otherwise pushfirst cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1) if length(cb) < cb.capacity cb.length += 1 end @inbounds cb.buffer[cb.first] = data return cb end ##CHUNK 5 """ push!(cb::CircularBuffer, data) Add an element to the back and overwrite front if full. """ @inline function Base.push!(cb::CircularBuffer{T}, data) where T # As per the behaviour of Base.push! data_converted = convert(T, data) # if full, increment and overwrite, otherwise push if cb.length == cb.capacity cb.first = (cb.first == cb.capacity ? 1 : cb.first + 1) else cb.length += 1 end @inbounds cb.buffer[_buffer_index(cb, cb.length)] = data_converted return cb end Based on the information above, please generate test code for the following function: function Base.resize!(cb::CircularBuffer, n::Integer) if n != capacity(cb) buf_new = Vector{eltype(cb)}(undef, n) len_new = min(length(cb), n) for i in 1:len_new @inbounds buf_new[i] = cb[i] end cb.capacity = n cb.first = 1 cb.length = len_new cb.buffer = buf_new end return cb end
{ "fpath_tuple": [ "DataStructures.jl", "src", "circular_buffer.jl" ], "ground_truth": "function Base.resize!(cb::CircularBuffer, n::Integer)\n if n != capacity(cb)\n buf_new = Vector{eltype(cb)}(undef, n)\n len_new = min(length(cb), n)\n for i in 1:len_new\n @inbounds buf_new[i] = cb[i]\n end\n\n cb.capacity = n\n cb.first = 1\n cb.length = len_new\n cb.buffer = buf_new\n end\n return cb\nend", "task_id": "DataStructures/12" }
243
257
DataStructures.jl
12
function Base.resize!(cb::CircularBuffer, n::Integer) if n != capacity(cb) buf_new = Vector{eltype(cb)}(undef, n) len_new = min(length(cb), n) for i in 1:len_new @inbounds buf_new[i] = cb[i] end cb.capacity = n cb.first = 1 cb.length = len_new cb.buffer = buf_new end return cb end
Base.resize!(cb::CircularBuffer, n::Integer)
[ 243, 257 ]
function Base.resize!(cb::CircularBuffer, n::Integer) if n != capacity(cb) buf_new = Vector{eltype(cb)}(undef, n) len_new = min(length(cb), n) for i in 1:len_new @inbounds buf_new[i] = cb[i] end cb.capacity = n cb.first = 1 cb.length = len_new cb.buffer = buf_new end return cb end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end @inline function _buffer_index(cb::CircularBuffer, i::Int) n = cb.capacity idx = cb.first + i - 1 return ifelse(idx > n, idx - n, idx) end """ cb[i] ##CHUNK 2 end CircularBuffer(iter) = CircularBuffer{eltype(iter)}(iter) """ empty!(cb::CircularBuffer) Reset the buffer. """ function Base.empty!(cb::CircularBuffer) cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 sum += ft.bi_tree[i] i -= i&(-i) end sum end Base.getindex(ft::FenwickTree{T}, ind::Integer) where T = prefixsum(ft, ind) #FILE: DataStructures.jl/src/sparse_int_set.jl ##CHUNK 1 iterator_length = length(it) if state > iterator_length return nothing end for i in state:iterator_length @inbounds id = it.shortest_set.packed[i] if in_valid(id, it) && !in_excluded(id, it) return map(x->findfirst_packed_id(id, x), it.valid_sets), i + 1 end end return nothing end #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 break end end pq.index[x.first] = i pq.xs[i] = x end function percolate_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) xj = pq.xs[j] if lt(pq.o, x.second, xj.second) pq.index[xj.first] = i pq.xs[i] = xj i = j else break end #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 # Backwards deque iteration function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back)) i < cb.front && return nothing x = cb.data[i] i -= 1 # If we're past the beginning of a block, go to the previous one if i < cb.front && !ishead(cb) cb = cb.prev i = cb.back end return (x, (cb, i)) end Base.iterate(d::Deque{T}, s...) where {T} = iterate(DequeIterator{T}(d), s...) Base.length(di::DequeIterator{T}) where {T} = di.d.len ##CHUNK 2 cb = cb.prev i = cb.back end return (x, (cb, i)) end Base.iterate(d::Deque{T}, s...) where {T} = iterate(DequeIterator{T}(d), s...) Base.length(di::DequeIterator{T}) where {T} = di.d.len Base.collect(d::Deque{T}) where {T} = T[x for x in d] # Showing function Base.show(io::IO, d::Deque) print(io, "Deque [$(collect(d))]") end function Base.dump(io::IO, d::Deque) ##CHUNK 3 # Iteration struct DequeIterator{T} d::Deque{T} end Base.last(di::DequeIterator) = last(di.d) # Backwards deque iteration function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back)) i < cb.front && return nothing x = cb.data[i] i -= 1 # If we're past the beginning of a block, go to the previous one if i < cb.front && !ishead(cb) ##CHUNK 4 println(io, "Deque (length = $(d.len), nblocks = $(d.nblocks))") cb::DequeBlock = d.head i = 1 while true print(io, "block $i [$(cb.front):$(cb.back)] ==> ") for j = cb.front : cb.back print(io, cb.data[j]) print(io, ' ') end println(io) cb_next::DequeBlock = cb.next if cb !== cb_next cb = cb_next i += 1 else break end end end ##CHUNK 5 cb_next::DequeBlock = cb.next if cb !== cb_next cb = cb_next i += 1 else break end end end # Manipulation """ empty!(d::Deque{T}) where T Reset the deque `d`. """ function Base.empty!(d::Deque{T}) where T Based on the information above, please generate test code for the following function: function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T i > cb.back && return nothing x = cb.data[i] i += 1 if i > cb.back && !isrear(cb) cb = cb.next i = 1 end return (x, (cb, i)) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T\n i > cb.back && return nothing\n x = cb.data[i]\n\n i += 1\n if i > cb.back && !isrear(cb)\n cb = cb.next\n i = 1\n end\n\n return (x, (cb, i))\nend", "task_id": "DataStructures/13" }
141
152
DataStructures.jl
13
function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T i > cb.back && return nothing x = cb.data[i] i += 1 if i > cb.back && !isrear(cb) cb = cb.next i = 1 end return (x, (cb, i)) end
Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T
[ 141, 152 ]
function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T i > cb.back && return nothing x = cb.data[i] i += 1 if i > cb.back && !isrear(cb) cb = cb.next i = 1 end return (x, (cb, i)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 end CircularBuffer(iter) = CircularBuffer{eltype(iter)}(iter) """ empty!(cb::CircularBuffer) Reset the buffer. """ function Base.empty!(cb::CircularBuffer) cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end ##CHUNK 2 cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end @inline function _buffer_index(cb::CircularBuffer, i::Int) n = cb.capacity idx = cb.first + i - 1 return ifelse(idx > n, idx - n, idx) end """ cb[i] #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 end Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict) isempty(h) && return nothing check_for_rehash(h) && rehash!(h) index = get_first_filled_index(h) return (Pair(h.keys[index], h.vals[index]), index+1) end Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict, i) length(h.keys) < i && return nothing index = get_next_filled_index(h, i) (index < 0) && return nothing return (Pair(h.keys[index], h.vals[index]), index+1) end Base.filter!(f, d::Union{RobinDict, OrderedRobinDict}) = Base.filter_in_one_pass!(f, d) function Base.merge(d::OrderedRobinDict, others::AbstractDict...) K,V = _merge_kvtypes(d, others...) #FILE: DataStructures.jl/src/balanced_tree.jl ##CHUNK 1 ## prevloc0: returns the previous item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 1 if there is no previous item (i.e., we started ## from the first one in the sorted order). function prevloc0(t::BalancedTree23, i::Int) @invariant i != 1 && i in t.useddatacells ii = i @inbounds p = t.data[i].parent prevchild = 0 depthp = t.depth @inbounds while true if depthp < t.depth p = t.tree[ii].parent end if t.tree[p].child3 == ii prevchild = t.tree[p].child2 break ##CHUNK 2 if depthp == t.depth return nextchild end p = nextchild nextchild = t.tree[p].child1 depthp += 1 end end ## prevloc0: returns the previous item in the tree according to the ## sort order, given an index i (subscript of t.data) of a current ## item. ## The routine returns 1 if there is no previous item (i.e., we started ## from the first one in the sorted order). function prevloc0(t::BalancedTree23, i::Int) @invariant i != 1 && i in t.useddatacells ii = i #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T i > cb.back && return nothing x = cb.data[i] i += 1 if i > cb.back && !isrear(cb) cb = cb.next i = 1 end return (x, (cb, i)) end # Backwards deque iteration Base.iterate(d::Deque{T}, s...) where {T} = iterate(DequeIterator{T}(d), s...) Base.length(di::DequeIterator{T}) where {T} = di.d.len ##CHUNK 2 # Iteration struct DequeIterator{T} d::Deque{T} end Base.last(di::DequeIterator) = last(di.d) function Base.iterate(di::DequeIterator{T}, (cb, i) = (di.d.head, di.d.head.front)) where T i > cb.back && return nothing x = cb.data[i] i += 1 if i > cb.back && !isrear(cb) cb = cb.next i = 1 end ##CHUNK 3 cb::DequeBlock = d.head i = 1 while true print(io, "block $i [$(cb.front):$(cb.back)] ==> ") for j = cb.front : cb.back print(io, cb.data[j]) print(io, ' ') end println(io) cb_next::DequeBlock = cb.next if cb !== cb_next cb = cb_next i += 1 else break end end end ##CHUNK 4 return (x, (cb, i)) end # Backwards deque iteration Base.iterate(d::Deque{T}, s...) where {T} = iterate(DequeIterator{T}(d), s...) Base.length(di::DequeIterator{T}) where {T} = di.d.len Base.collect(d::Deque{T}) where {T} = T[x for x in d] # Showing function Base.show(io::IO, d::Deque) print(io, "Deque [$(collect(d))]") end function Base.dump(io::IO, d::Deque) println(io, "Deque (length = $(d.len), nblocks = $(d.nblocks))") ##CHUNK 5 Base.collect(d::Deque{T}) where {T} = T[x for x in d] # Showing function Base.show(io::IO, d::Deque) print(io, "Deque [$(collect(d))]") end function Base.dump(io::IO, d::Deque) println(io, "Deque (length = $(d.len), nblocks = $(d.nblocks))") cb::DequeBlock = d.head i = 1 while true print(io, "block $i [$(cb.front):$(cb.back)] ==> ") for j = cb.front : cb.back print(io, cb.data[j]) print(io, ' ') end println(io) Based on the information above, please generate test code for the following function: function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back)) i < cb.front && return nothing x = cb.data[i] i -= 1 # If we're past the beginning of a block, go to the previous one if i < cb.front && !ishead(cb) cb = cb.prev i = cb.back end return (x, (cb, i)) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back))\n i < cb.front && return nothing\n x = cb.data[i]\n\n i -= 1\n # If we're past the beginning of a block, go to the previous one\n if i < cb.front && !ishead(cb)\n cb = cb.prev\n i = cb.back\n end\n\n return (x, (cb, i))\nend", "task_id": "DataStructures/14" }
156
168
DataStructures.jl
14
function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back)) i < cb.front && return nothing x = cb.data[i] i -= 1 # If we're past the beginning of a block, go to the previous one if i < cb.front && !ishead(cb) cb = cb.prev i = cb.back end return (x, (cb, i)) end
Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back))
[ 156, 168 ]
function Base.iterate(di::Iterators.Reverse{<:Deque}, (cb, i) = (di.itr.rear, di.itr.rear.back)) i < cb.front && return nothing x = cb.data[i] i -= 1 # If we're past the beginning of a block, go to the previous one if i < cb.front && !ishead(cb) cb = cb.prev i = cb.back end return (x, (cb, i)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end ##CHUNK 2 Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ ##CHUNK 3 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end const _deque_hashseed = UInt === UInt64 ? 0x950aa17a3246be82 : 0x4f26f881 function Base.hash(x::Deque, h::UInt) h += _deque_hashseed for (i, x) in enumerate(x) h += i * hash(x) end return h end ##CHUNK 4 new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ pushfirst!(d::Deque{T}, x) where T Add an element to the front of deque `d`. """ function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa ##CHUNK 5 new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] ##CHUNK 6 pop!(d::Deque{T}) where T Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end ##CHUNK 7 end d.len -= 1 return x end """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 ##CHUNK 8 head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ ##CHUNK 9 if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end ##CHUNK 10 # block at the head of the train, elements towards the back head_deque_block(ty::Type{T}, n::Integer) where {T} = DequeBlock{T}(n, n+1) capacity(blk::DequeBlock) = blk.capa Base.length(blk::DequeBlock) = blk.back - blk.front + 1 Base.isempty(blk::DequeBlock) = blk.back < blk.front ishead(blk::DequeBlock) = blk.prev === blk isrear(blk::DequeBlock) = blk.next === blk # reset the block to empty, and position function reset!(blk::DequeBlock{T}, front::Integer) where T empty!(blk.data) resize!(blk.data, blk.capa) blk.front = front blk.back = front - 1 blk.prev = blk blk.next = blk end Based on the information above, please generate test code for the following function: function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.empty!(d::Deque{T}) where T\n # release all blocks except the head\n if d.nblocks > 1\n cb::DequeBlock{T} = d.rear\n while cb != d.head\n empty!(cb.data)\n cb = cb.prev\n end\n end\n\n # clean the head block (but retain the block itself)\n reset!(d.head, 1)\n\n # reset queue fields\n d.nblocks = 1\n d.len = 0\n d.rear = d.head\n return d\nend", "task_id": "DataStructures/15" }
212
230
DataStructures.jl
15
function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end
Base.empty!(d::Deque{T}) where T
[ 212, 230 ]
function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_sorted_containers.jl ##CHUNK 1 sv = zero1 skhalf = zero1 svhalf = zero1 for l = 1 : N lUi = convert(T, l) brl = bitreverse(lUi) sk += brl m1[brl] = lUi sv += lUi if brl < div(N, 2) skhalf += brl svhalf += lUi end end count = 0 sk2 = zero1 sv2 = zero1 for (k,v) in m1 sk2 += k sv2 += v #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 ##CHUNK 2 d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 ##CHUNK 3 end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T ##CHUNK 4 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) ##CHUNK 5 Add an element to the front of deque `d`. """ function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head ##CHUNK 6 # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ """ pushfirst!(d::Deque{T}, x) where T ##CHUNK 7 """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end ##CHUNK 8 d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end const _deque_hashseed = UInt === UInt64 ? 0x950aa17a3246be82 : 0x4f26f881 function Base.hash(x::Deque, h::UInt) h += _deque_hashseed for (i, x) in enumerate(x) h += i * hash(x) end return h end """ ==(x::Deque, y::Deque) ##CHUNK 9 blksize::Int len::Int head::DequeBlock{T} rear::DequeBlock{T} function Deque{T}(blksize::Integer) where T head = rear = rear_deque_block(T, blksize) new{T}(1, blksize, 0, head, rear) end Deque{T}() where {T} = Deque{T}(DEFAULT_DEQUEUE_BLOCKSIZE) end """ isempty(d::Deque) Verifies if deque `d` is empty. """ Base.isempty(d::Deque) = d.len == 0 Based on the information above, please generate test code for the following function: function Base.push!(d::Deque{T}, x) where T rear = d.rear if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.push!(d::Deque{T}, x) where T\n rear = d.rear\n\n if isempty(rear)\n rear.front = 1\n rear.back = 0\n end\n\n if rear.back < rear.capa\n @inbounds rear.data[rear.back += 1] = convert(T, x)\n else\n new_rear = rear_deque_block(T, d.blksize)\n new_rear.back = 1\n new_rear.data[1] = convert(T, x)\n new_rear.prev = rear\n d.rear = rear.next = new_rear\n d.nblocks += 1\n end\n d.len += 1\n return d\nend", "task_id": "DataStructures/16" }
238
258
DataStructures.jl
16
function Base.push!(d::Deque{T}, x) where T rear = d.rear if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end
Base.push!(d::Deque{T}, x) where T
[ 238, 258 ]
function Base.push!(d::Deque{T}, x) where T rear = d.rear if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/list.jl ##CHUNK 1 function list(elts::T...) where T l = nil(T) for i=length(elts):-1:1 l = cons(elts[i],l) end return l end Base.length(l::Nil) = 0 function Base.length(l::Cons) n = 0 for i in l n += 1 end return n end Base.map(f::Base.Callable, l::Nil) = l #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end const _deque_hashseed = UInt === UInt64 ? 0x950aa17a3246be82 : 0x4f26f881 function Base.hash(x::Deque, h::UInt) h += _deque_hashseed ##CHUNK 2 if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ ##CHUNK 3 """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head ##CHUNK 4 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front ##CHUNK 5 # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ function Base.push!(d::Deque{T}, x) where T rear = d.rear ##CHUNK 6 """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end ##CHUNK 7 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ pushfirst!(d::Deque{T}, x) where T Add an element to the front of deque `d`. """ """ pop!(d::Deque{T}) where T Remove the element at the back of deque `d`. """ ##CHUNK 8 """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ function Base.push!(d::Deque{T}, x) where T rear = d.rear if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 ##CHUNK 9 end end # Manipulation """ empty!(d::Deque{T}) where T Reset the deque `d`. """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end Based on the information above, please generate test code for the following function: function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.pushfirst!(d::Deque{T}, x) where T\n head = d.head\n\n if isempty(head)\n n = head.capa\n head.front = n + 1\n head.back = n\n end\n\n if head.front > 1\n @inbounds head.data[head.front -= 1] = convert(T, x)\n else\n n::Int = d.blksize\n new_head = head_deque_block(T, n)\n new_head.front = n\n new_head.data[n] = convert(T, x)\n new_head.next = head\n d.head = head.prev = new_head\n d.nblocks += 1\n end\n d.len += 1\n return d\nend", "task_id": "DataStructures/17" }
265
287
DataStructures.jl
17
function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end
Base.pushfirst!(d::Deque{T}, x) where T
[ 265, 287 ]
function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end ##CHUNK 2 if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ ##CHUNK 3 """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ function Base.push!(d::Deque{T}, x) where T rear = d.rear if isempty(rear) rear.front = 1 rear.back = 0 end if rear.back < rear.capa @inbounds rear.data[rear.back += 1] = convert(T, x) else new_rear = rear_deque_block(T, d.blksize) new_rear.back = 1 ##CHUNK 4 Remove the element at the back of deque `d`. """ """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block ##CHUNK 5 """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end ##CHUNK 6 # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ function Base.push!(d::Deque{T}, x) where T rear = d.rear ##CHUNK 7 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ pushfirst!(d::Deque{T}, x) where T Add an element to the front of deque `d`. """ function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 ##CHUNK 8 end end # Manipulation """ empty!(d::Deque{T}) where T Reset the deque `d`. """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end ##CHUNK 9 first(d::Deque) Returns the first element of the deque `d`. """ function Base.first(d::Deque) isempty(d) && throw(ArgumentError("Deque must be non-empty")) blk = d.head return blk.data[blk.front] end """ last(d::Deque) Returns the last element of the deque `d`. """ function Base.last(d::Deque) isempty(d) && throw(ArgumentError("Deque must be non-empty")) blk = d.rear return blk.data[blk.back] end ##CHUNK 10 """ last(d::Deque) Returns the last element of the deque `d`. """ function Base.last(d::Deque) isempty(d) && throw(ArgumentError("Deque must be non-empty")) blk = d.rear return blk.data[blk.back] end # Iteration struct DequeIterator{T} d::Deque{T} end Base.last(di::DequeIterator) = last(di.d) Based on the information above, please generate test code for the following function: function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.pop!(d::Deque{T}) where T\n isempty(d) && throw(ArgumentError(\"Deque must be non-empty\"))\n rear = d.rear\n @assert rear.back >= rear.front\n\n @inbounds x = rear.data[rear.back]\n Base._unsetindex!(rear.data, rear.back) # see issue/884\n rear.back -= 1\n if rear.back < rear.front\n if d.nblocks > 1\n # release and detach the rear block\n empty!(rear.data)\n d.rear = rear.prev::DequeBlock{T}\n d.rear.next = d.rear\n d.nblocks -= 1\n end\n end\n d.len -= 1\n return x\nend", "task_id": "DataStructures/18" }
294
313
DataStructures.jl
18
function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end
Base.pop!(d::Deque{T}) where T
[ 294, 313 ]
function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 ##CHUNK 2 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T ##CHUNK 3 Remove the element at the back of deque `d`. """ function Base.pop!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) rear = d.rear @assert rear.back >= rear.front @inbounds x = rear.data[rear.back] Base._unsetindex!(rear.data, rear.back) # see issue/884 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end ##CHUNK 4 pushfirst!(d::Deque{T}, x) where T Add an element to the front of deque `d`. """ function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) ##CHUNK 5 """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end ##CHUNK 6 new_rear.data[1] = convert(T, x) new_rear.prev = rear d.rear = rear.next = new_rear d.nblocks += 1 end d.len += 1 return d end """ pushfirst!(d::Deque{T}, x) where T Add an element to the front of deque `d`. """ function Base.pushfirst!(d::Deque{T}, x) where T head = d.head if isempty(head) n = head.capa head.front = n + 1 ##CHUNK 7 rear.back -= 1 if rear.back < rear.front if d.nblocks > 1 # release and detach the rear block empty!(rear.data) d.rear = rear.prev::DequeBlock{T} d.rear.next = d.rear d.nblocks -= 1 end end d.len -= 1 return x end """ popfirst!(d::Deque{T}) where T Remove the element at the front of deque `d`. """ ##CHUNK 8 end end # Manipulation """ empty!(d::Deque{T}) where T Reset the deque `d`. """ function Base.empty!(d::Deque{T}) where T # release all blocks except the head if d.nblocks > 1 cb::DequeBlock{T} = d.rear while cb != d.head empty!(cb.data) cb = cb.prev end end ##CHUNK 9 """ length(d::Deque) Returns the number of elements in deque `d`. """ Base.length(d::Deque) = d.len num_blocks(d::Deque) = d.nblocks Base.eltype(::Type{Deque{T}}) where T = T """ first(d::Deque) Returns the first element of the deque `d`. """ function Base.first(d::Deque) isempty(d) && throw(ArgumentError("Deque must be non-empty")) blk = d.head return blk.data[blk.front] end ##CHUNK 10 # clean the head block (but retain the block itself) reset!(d.head, 1) # reset queue fields d.nblocks = 1 d.len = 0 d.rear = d.head return d end """ push!(d::Deque{T}, x) where T Add an element to the back of deque `d`. """ function Base.push!(d::Deque{T}, x) where T rear = d.rear Based on the information above, please generate test code for the following function: function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "deque.jl" ], "ground_truth": "function Base.popfirst!(d::Deque{T}) where T\n isempty(d) && throw(ArgumentError(\"Deque must be non-empty\"))\n head = d.head\n @assert head.back >= head.front\n\n @inbounds x = head.data[head.front]\n Base._unsetindex!(head.data, head.front) # see issue/884\n head.front += 1\n if head.back < head.front\n if d.nblocks > 1\n # release and detach the head block\n empty!(head.data)\n d.head = head.next::DequeBlock{T}\n d.head.prev = d.head\n d.nblocks -= 1\n end\n end\n d.len -= 1\n return x\nend", "task_id": "DataStructures/19" }
320
339
DataStructures.jl
19
function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end
Base.popfirst!(d::Deque{T}) where T
[ 320, 339 ]
function Base.popfirst!(d::Deque{T}) where T isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 mutable struct CircularBuffer{T} <: AbstractVector{T} capacity::Int first::Int length::Int buffer::Vector{T} function CircularBuffer{T}(f,len,buf) where {T} f <= length(buf) || throw(ArgumentError("Value of 'first' must be inbounds of buffer")) len <= length(buf) || throw(ArgumentError("Value of 'length' must be <= length of buffer")) return new{T}(length(buf), f, len, buf) end # Convert any `Integer` to whatever `Int` is on the relevant machine CircularBuffer{T}(f::Integer, len::Integer, buf::Integer) where {T} = CircularBuffer{T}(Int(f), Int(len), Int(buf)) end function CircularBuffer{T}(iter, capacity::Integer) where {T} vec = copyto!(Vector{T}(undef,capacity), iter) CircularBuffer{T}(1, length(iter),vec) end #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 function Base.last(s::IntSet) l = length(s.bits) if s.inverse idx = l < typemax(Int) ? typemax(Int) : something(findprevnot(s.bits, l), 0) else idx = something(findprev(s.bits, l), 0) end idx == 0 ? throw(ArgumentError("collection must be non-empty")) : idx - 1 end Base.length(s::IntSet) = (n = sum(s.bits); ifelse(s.inverse, typemax(Int) - n, n)) complement(s::IntSet) = complement!(copy(s)) complement!(s::IntSet) = (s.inverse = !s.inverse; s) function Base.show(io::IO, s::IntSet) print(io, "IntSet([") first = true for n in s if s.inverse && n > 2 ##CHUNK 2 const _intset_bounds_err_msg = "elements of IntSet must be between 0 and typemax(Int)-1" function Base.push!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) _setint!(s, n, !s.inverse) end Base.push!(s::IntSet, ns::Integer...) = (for n in ns; push!(s, n); end; s) function Base.pop!(s::IntSet) s.inverse && throw(ArgumentError("cannot pop the last element of complement IntSet")) pop!(s, last(s)) end function Base.pop!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : throw(KeyError(n)) end function Base.pop!(s::IntSet, n::Integer, default) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : default end #FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end Base.empty!(h::BinaryMinMaxHeap) = (empty!(h.valtree); h) """ popall!(h::BinaryMinMaxHeap, ::Ordering = Forward) Remove and return all the elements of `h` according to the given ordering. Default is `Forward` (smallest to largest). """ ##CHUNK 2 """ first(h::BinaryMinMaxHeap) Get the first (minimum) of the heap. """ @inline Base.first(h::BinaryMinMaxHeap) = minimum(h) @inline function Base.minimum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end #FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 l.node.next = node oldfirst.prev = node l.len += 1 return l end function Base.pop!(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List must be non-empty")) last = l.node.prev.prev data = l.node.prev.data last.next = l.node l.node.prev = last l.len -= 1 return data end function Base.popfirst!(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List must be non-empty")) first = l.node.next.next data = l.node.next.data #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 throw(ArgumentError("PriorityQueue(kv): kv needs to be an iterator of tuples or pairs")) else rethrow(e) end end end # Construction inferring Key/Value types from input # e.g. PriorityQueue{} PriorityQueue(o1::Ordering, o2::Ordering) = throw(ArgumentError("PriorityQueue with two parameters must be called with an Ordering and an iterable of pairs")) PriorityQueue(kv, o::Ordering=Forward) = PriorityQueue(o, kv) function PriorityQueue(o::Ordering, kv) try _priority_queue_with_eltype(o, kv, eltype(kv)) catch e if not_iterator_of_pairs(kv) throw(ArgumentError("PriorityQueue(kv): kv needs to be an iterator of tuples or pairs")) else rethrow(e) #FILE: DataStructures.jl/src/sorted_container_iteration.jl ##CHUNK 1 end ## Must repeat this to break ambiguity; cannot use SDMContainer Base.@propagate_inbounds function Base.setindex!(m::SortedMultiDict, d_, i::IntSemiToken) @boundscheck has_data((m,i)) @inbounds m.bt.data[i.address] = KDRec{keytype(m),valtype(m)}(m.bt.data[i.address].parent, m.bt.data[i.address].k, convert(valtype(m),d_)) return m end """ Base.searchsortedfirst(m::SortedContainer, k) Return the semitoken of the first item in the sorted container `m` that is greater than or equal to #CURRENT FILE: DataStructures.jl/src/dibit_vector.jl ##CHUNK 1 @inline function Base.push!(x::DiBitVector, v::Integer) len = length(x) len == UInt64(length(x.data)) << 5 && push!(x.data, zero(UInt64)) x.len = (len + 1) % UInt64 x[len+1] = convert(UInt64, v) return x end @inline function Base.pop!(x::DiBitVector) x.len == 0 && throw(ArgumentError("array must be non-empty")) v = x[end] x.len = (x.len - 1) % UInt64 x.len == UInt64((length(x.data) -1)) << 5 && pop!(x.data) return v end @inline Base.zero(x::DiBitVector) = DiBitVector(x.len, 0) ##CHUNK 2 bits |= convert(UInt64, v) << offset(i) @inbounds x.data[index(i)] = bits end @inline function Base.setindex!(x::DiBitVector, v::Integer, i::Int) v & 3 == v || throw(DomainError("Can only contain 0:3 (tried $v)")) @boundscheck checkbounds(x, i) unsafe_setindex!(x, convert(UInt64, v), i) end @inline function Base.push!(x::DiBitVector, v::Integer) len = length(x) len == UInt64(length(x.data)) << 5 && push!(x.data, zero(UInt64)) x.len = (len + 1) % UInt64 x[len+1] = convert(UInt64, v) return x end @inline function Base.pop!(x::DiBitVector) x.len == 0 && throw(ArgumentError("array must be non-empty")) Based on the information above, please generate test code for the following function: function DiBitVector(n::Integer, v::Integer) if Int(n) < 0 throw(ArgumentError("n ($n) must be greater than or equal to zero")) end if !(Int(v) in 0:3) throw(ArgumentError("v ($v) must be in 0:3")) end fv = (0x0000000000000000, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0xffffffffffffffff)[v + 1] vec = Vector{UInt64}(undef, cld(n, 32)) fill!(vec, fv) return new(vec, n % UInt64) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "dibit_vector.jl" ], "ground_truth": "function DiBitVector(n::Integer, v::Integer)\n if Int(n) < 0\n throw(ArgumentError(\"n ($n) must be greater than or equal to zero\"))\n end\n if !(Int(v) in 0:3)\n throw(ArgumentError(\"v ($v) must be in 0:3\"))\n end\n fv = (0x0000000000000000, 0x5555555555555555,\n 0xaaaaaaaaaaaaaaaa, 0xffffffffffffffff)[v + 1]\n vec = Vector{UInt64}(undef, cld(n, 32))\n fill!(vec, fv)\n return new(vec, n % UInt64)\n end", "task_id": "DataStructures/20" }
15
27
DataStructures.jl
20
function DiBitVector(n::Integer, v::Integer) if Int(n) < 0 throw(ArgumentError("n ($n) must be greater than or equal to zero")) end if !(Int(v) in 0:3) throw(ArgumentError("v ($v) must be in 0:3")) end fv = (0x0000000000000000, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0xffffffffffffffff)[v + 1] vec = Vector{UInt64}(undef, cld(n, 32)) fill!(vec, fv) return new(vec, n % UInt64) end
DiBitVector(n::Integer, v::Integer)
[ 15, 27 ]
function DiBitVector(n::Integer, v::Integer) if Int(n) < 0 throw(ArgumentError("n ($n) must be greater than or equal to zero")) end if !(Int(v) in 0:3) throw(ArgumentError("v ($v) must be in 0:3")) end fv = (0x0000000000000000, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0xffffffffffffffff)[v + 1] vec = Vector{UInt64}(undef, cld(n, 32)) fill!(vec, fv) return new(vec, n % UInt64) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 print(io, "])") end function Base.:(==)(s1::IntSet, s2::IntSet) l1 = length(s1.bits) l2 = length(s2.bits) l1 < l2 && return ==(s2, s1) # Swap so s1 is always equal-length or longer # Try to do this without allocating memory or checking bit-by-bit if s1.inverse == s2.inverse # If the lengths are the same, simply punt to bitarray comparison l1 == l2 && return s1.bits == s2.bits # Otherwise check the last bit. If equal, we only need to check up to l2 return findprev(s1.bits, l1) == findprev(s2.bits, l2) && unsafe_getindex(s1.bits, 1:l2) == s2.bits else # one complement, one not. Could feasibly be true on 32 bit machines # Only if all non-overlapping bits are set and overlaps are inverted return l1 == typemax(Int) && map!(!, unsafe_getindex(s1.bits, 1:l2)) == s2.bits && ##CHUNK 2 # If the lengths are the same, simply punt to bitarray comparison l1 == l2 && return s1.bits == s2.bits # Otherwise check the last bit. If equal, we only need to check up to l2 return findprev(s1.bits, l1) == findprev(s2.bits, l2) && unsafe_getindex(s1.bits, 1:l2) == s2.bits else # one complement, one not. Could feasibly be true on 32 bit machines # Only if all non-overlapping bits are set and overlaps are inverted return l1 == typemax(Int) && map!(!, unsafe_getindex(s1.bits, 1:l2)) == s2.bits && (l1 == l2 || all(unsafe_getindex(s1.bits, l2+1:l1))) end end const hashis_seed = UInt === UInt64 ? 0x88989f1fc7dea67d : 0xc7dea67d function Base.hash(s::IntSet, h::UInt) # Only hash the bits array up to the last-set bit to prevent extra empty # bits from changing the hash result l = findprev(s.bits, length(s.bits)) return hash(unsafe_getindex(s.bits, 1:l), h) ⊻ hash(s.inverse) ⊻ hashis_seed #FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 element is a child of the root. """ function is_minmax_heap(A::AbstractVector) for i in 1:length(A) if on_minlevel(i) # check that A[i] < children A[i] # and grandchildren A[i] for j in children_and_grandchildren(length(A), i) A[i] ≤ A[j] || return false end else # max layer for j in children_and_grandchildren(length(A), i) A[i] ≥ A[j] || return false end end end return true end ##CHUNK 2 left, right = children(i) _children_and_grandchildren = (left, children(left)..., right, children(right)...) return Iterators.filter(<=(maxlen), _children_and_grandchildren) end """ is_minmax_heap(h::AbstractVector) -> Bool Return `true` if `A` is a min-max heap. A min-max heap is a heap where the minimum element is the root and the maximum element is a child of the root. """ function is_minmax_heap(A::AbstractVector) for i in 1:length(A) if on_minlevel(i) # check that A[i] < children A[i] # and grandchildren A[i] for j in children_and_grandchildren(length(A), i) A[i] ≤ A[j] || return false #FILE: DataStructures.jl/src/accumulator.jl ##CHUNK 1 for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities va = a[k] vb = b[k] va >= 0 || throw(MultiplicityException(k, va)) vb >= 0 || throw(MultiplicityException(k, vb)) a[k] = min(va, vb) drop_nonpositive!(a, k) # Drop any that ended up zero end return a end function Base.show(io::IO, acc::Accumulator{T,V}) where {T,V} l = length(acc) if l>0 print(io, "Accumulator(") else print(io,"Accumulator{$T,$V}(") end for (count, (k, v)) in enumerate(acc) print(io, k, " => ", v) ##CHUNK 2 va >= 0 || throw(MultiplicityException(kb, va)) a[kb] = max(va, vb) end return a end Base.intersect(a::Accumulator, b::Accumulator, c::Accumulator...) = intersect(intersect(a,b), c...) Base.intersect(a::Accumulator, b::Accumulator) = intersect!(copy(a), b) function Base.intersect!(a::Accumulator, b::Accumulator) for k in union(keys(a), keys(b)) # union not intersection as we want to check both multiplicities va = a[k] vb = b[k] va >= 0 || throw(MultiplicityException(k, va)) vb >= 0 || throw(MultiplicityException(k, vb)) a[k] = min(va, vb) drop_nonpositive!(a, k) # Drop any that ended up zero end return a #FILE: DataStructures.jl/src/heaps/arrays_as_heaps.jl ##CHUNK 1 x = xs[1] y = pop!(xs) if !isempty(xs) percolate_down!(xs, 1, y, o) end return x end """ heappush!(v, x, [ord]) Given a binary heap-ordered array, push a new element `x`, preserving the heap property. For efficiency, this function does not check that the array is indeed heap-ordered. """ @inline function heappush!(xs::AbstractArray, x, o::Ordering=Forward) push!(xs, x) percolate_up!(xs, length(xs), o) return xs end ##CHUNK 2 @inline percolate_up!(xs::AbstractArray, i::Integer, o::Ordering) = percolate_up!(xs, i, xs[i], o) """ heappop!(v, [ord]) Given a binary heap-ordered array, remove and return the lowest ordered element. For efficiency, this function does not check that the array is indeed heap-ordered. """ function heappop!(xs::AbstractArray, o::Ordering=Forward) x = xs[1] y = pop!(xs) if !isempty(xs) percolate_down!(xs, 1, y, o) end return x end """ heappush!(v, x, [ord]) #FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end #FILE: DataStructures.jl/src/sorted_container_iteration.jl ##CHUNK 1 `@inbounds` may elide the correctness check and results in undefined behavior if the token is invalid. Time: O(1) """ Base.@propagate_inbounds function Base.getindex(m::SortedDict, i::IntSemiToken) @boundscheck has_data((m,i)) @inbounds d = m.bt.data[i.address].d return d end # Must repeat this to break ambiguity; cannot use SDMContainer. Base.@propagate_inbounds function Base.getindex(m::SortedMultiDict, i::IntSemiToken) @boundscheck has_data((m,i)) @inbounds d = m.bt.data[i.address].d return d end #CURRENT FILE: DataStructures.jl/src/dict_support.jl Based on the information above, please generate test code for the following function: function not_iterator_of_pairs(kv::T) where T # if the object is not iterable, return true, else check the eltype of the iteration Base.isiterable(T) || return true # else, check if we can check `eltype`: if Base.IteratorEltype(kv) isa Base.HasEltype typ = eltype(kv) if !(typ == Any) return !(typ <: Union{<: Tuple, <: Pair}) end end # we can't check eltype, or eltype is not useful, # so brute force it. return any(x->!isa(x, Union{Tuple,Pair}), kv) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "dict_support.jl" ], "ground_truth": "function not_iterator_of_pairs(kv::T) where T\n # if the object is not iterable, return true, else check the eltype of the iteration\n Base.isiterable(T) || return true \n # else, check if we can check `eltype`:\n if Base.IteratorEltype(kv) isa Base.HasEltype\n typ = eltype(kv)\n if !(typ == Any)\n return !(typ <: Union{<: Tuple, <: Pair})\n end\n end\n # we can't check eltype, or eltype is not useful, \n # so brute force it.\n return any(x->!isa(x, Union{Tuple,Pair}), kv)\nend", "task_id": "DataStructures/21" }
3
16
DataStructures.jl
21
function not_iterator_of_pairs(kv::T) where T # if the object is not iterable, return true, else check the eltype of the iteration Base.isiterable(T) || return true # else, check if we can check `eltype`: if Base.IteratorEltype(kv) isa Base.HasEltype typ = eltype(kv) if !(typ == Any) return !(typ <: Union{<: Tuple, <: Pair}) end end # we can't check eltype, or eltype is not useful, # so brute force it. return any(x->!isa(x, Union{Tuple,Pair}), kv) end
not_iterator_of_pairs(kv::T) where T
[ 3, 16 ]
function not_iterator_of_pairs(kv::T) where T # if the object is not iterable, return true, else check the eltype of the iteration Base.isiterable(T) || return true # else, check if we can check `eltype`: if Base.IteratorEltype(kv) isa Base.HasEltype typ = eltype(kv) if !(typ == Any) return !(typ <: Union{<: Tuple, <: Pair}) end end # we can't check eltype, or eltype is not useful, # so brute force it. return any(x->!isa(x, Union{Tuple,Pair}), kv) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end ##CHUNK 2 x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node #FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 """ popmin!(h::BinaryMinMaxHeap) -> min Remove the minimum value from the heap. """ function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end """ #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 "b" => 3 ``` """ function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end function Base.popat!(pq::PriorityQueue, key) idx = pq.index[key] force_up!(pq, idx) popfirst!(pq) end #CURRENT FILE: DataStructures.jl/src/disjoint_set.jl ##CHUNK 1 Assume `x ≠ y` (unsafe). """ """ push!(s::IntDisjointSet{T}) Make a new subset with an automatically chosen new element `x`. Returns the new element. Throw an `ArgumentError` if the capacity of the set would be exceeded. """ function Base.push!(s::IntDisjointSet{T}) where {T<:Integer} l = length(s) l < typemax(T) || throw(ArgumentError(_intdisjointset_bounds_err_msg(T))) x = l + one(T) push!(s.parents, x) push!(s.ranks, zero(T)) s.ngroups += one(T) return x end ##CHUNK 2 function Base.push!(s::IntDisjointSet{T}) where {T<:Integer} l = length(s) l < typemax(T) || throw(ArgumentError(_intdisjointset_bounds_err_msg(T))) x = l + one(T) push!(s.parents, x) push!(s.ranks, zero(T)) s.ngroups += one(T) return x end """ DisjointSet{T}(xs) A forest of disjoint sets of arbitrary value type `T`. It is a wrapper of `IntDisjointSet{Int}`, which uses a dictionary to map the input value to an internal index. """ mutable struct DisjointSet{T} <: AbstractSet{T} intmap::Dict{T,Int} ##CHUNK 3 in_same_set(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} = find_root!(s, x) == find_root!(s, y) """ union!(s::IntDisjointSet{T}, x::T, y::T) Merge the subset containing `x` and that containing `y` into one and return the root of the new set. """ function Base.union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents xroot = find_root_impl!(parents, x) yroot = find_root_impl!(parents, y) return xroot != yroot ? root_union!(s, xroot, yroot) : xroot end """ root_union!(s::IntDisjointSet{T}, x::T, y::T) Form a new set that is the union of the two sets whose root elements are `x` and `y` and return the root of the new set. ##CHUNK 4 Find the root element of the subset that contains an member `x`. Path compression happens here. """ find_root!(s::IntDisjointSet{T}, x::T) where {T<:Integer} = find_root_impl!(s.parents, x) """ in_same_set(s::IntDisjointSet{T}, x::T, y::T) Returns `true` if `x` and `y` belong to the same subset in `s`, and `false` otherwise. """ in_same_set(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} = find_root!(s, x) == find_root!(s, y) """ union!(s::IntDisjointSet{T}, x::T, y::T) Merge the subset containing `x` and that containing `y` into one and return the root of the new set. """ function Base.union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents ##CHUNK 5 """ num_groups(s::IntDisjointSet) Get a number of groups. """ num_groups(s::IntDisjointSet) = s.ngroups Base.eltype(::Type{IntDisjointSet{T}}) where {T<:Integer} = T # find the root element of the subset that contains x # path compression is implemented here function find_root_impl!(parents::Vector{T}, x::Integer) where {T<:Integer} p = parents[x] @inbounds if parents[p] != p parents[x] = p = _find_root_impl!(parents, p) end return p end # unsafe version of the above function _find_root_impl!(parents::Vector{T}, x::Integer) where {T<:Integer} Based on the information above, please generate test code for the following function: function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents rks = s.ranks @inbounds xrank = rks[x] @inbounds yrank = rks[y] if xrank < yrank x, y = y, x elseif xrank == yrank rks[x] += one(T) end @inbounds parents[y] = x s.ngroups -= one(T) return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "disjoint_set.jl" ], "ground_truth": "function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer}\n parents = s.parents\n rks = s.ranks\n @inbounds xrank = rks[x]\n @inbounds yrank = rks[y]\n\n if xrank < yrank\n x, y = y, x\n elseif xrank == yrank\n rks[x] += one(T)\n end\n @inbounds parents[y] = x\n s.ngroups -= one(T)\n return x\nend", "task_id": "DataStructures/22" }
103
117
DataStructures.jl
22
function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents rks = s.ranks @inbounds xrank = rks[x] @inbounds yrank = rks[y] if xrank < yrank x, y = y, x elseif xrank == yrank rks[x] += one(T) end @inbounds parents[y] = x s.ngroups -= one(T) return x end
root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer}
[ 103, 117 ]
function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents rks = s.ranks @inbounds xrank = rks[x] @inbounds yrank = rks[y] if xrank < yrank x, y = y, x elseif xrank == yrank rks[x] += one(T) end @inbounds parents[y] = x s.ngroups -= one(T) return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_priority_queue.jl ##CHUNK 1 end @testset "LowLevelHeapOperations" begin pmax = 1000 n = 10000 r = rand(1:pmax, n) priorities = Dict(zip(1:n, r)) @testset "low level heap operations" begin xs = heapify!([v for v in values(priorities)]) @test issorted([heappop!(xs) for _ in length(priorities)]) end @testset "heapify/issorted" begin xs = heapify(10:-1:1) @test issorted([heappop!(xs) for _ in 1:10]) end @testset "heappush!" begin xs = Vector{Int}() #FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end ##CHUNK 2 if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values #FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 head.back = n end if head.front > 1 @inbounds head.data[head.front -= 1] = convert(T, x) else n::Int = d.blksize new_head = head_deque_block(T, n) new_head.front = n new_head.data[n] = convert(T, x) new_head.next = head d.head = head.prev = new_head d.nblocks += 1 end d.len += 1 return d end """ pop!(d::Deque{T}) where T #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 If n is smaller than the current buffer length, the first n elements will be retained. """ function Base.resize!(cb::CircularBuffer, n::Integer) if n != capacity(cb) buf_new = Vector{eltype(cb)}(undef, n) len_new = min(length(cb), n) for i in 1:len_new @inbounds buf_new[i] = cb[i] end cb.capacity = n cb.first = 1 cb.length = len_new cb.buffer = buf_new end return cb end #FILE: DataStructures.jl/src/sparse_int_set.jl ##CHUNK 1 Base.union(s::SparseIntSet, ns) = union!(copy(s), ns) function Base.union!(s::SparseIntSet, ns) for n in ns push!(s, n) end return s end Base.intersect(s1::SparseIntSet) = copy(s1) Base.intersect(s1::SparseIntSet, ss...) = intersect(s1, intersect(ss...)) function Base.intersect(s1::SparseIntSet, ns) s = SparseIntSet() for n in ns n in s1 && push!(s, n) end return s end Base.intersect!(s1::SparseIntSet, ss...) = intersect!(s1, intersect(ss...)) ##CHUNK 2 @inline function Base.pop!(s::SparseIntSet, id::Integer, default) id < 0 && throw(ArgumentError("Int to pop needs to be positive.")) return in(id, s) ? (@inbounds pop!(s, id)) : default end Base.popfirst!(s::SparseIntSet) = pop!(s, first(s)) @inline Base.iterate(set::SparseIntSet, args...) = iterate(set.packed, args...) Base.last(s::SparseIntSet) = isempty(s) ? throw(ArgumentError("Empty set has no last element.")) : last(s.packed) Base.union(s::SparseIntSet, ns) = union!(copy(s), ns) function Base.union!(s::SparseIntSet, ns) for n in ns push!(s, n) end return s end Base.intersect(s1::SparseIntSet) = copy(s1) Base.intersect(s1::SparseIntSet, ss...) = intersect(s1, intersect(ss...)) #FILE: DataStructures.jl/test/bench_heaps.jl ##CHUNK 1 push!(h, 0.5) pop!(h) # bench n = length(xs) t1 = @elapsed for i = 1 : n push!(h, xs[i]) end t2 = @elapsed for i = 1 : n pop!(h) end @printf(" On %-24s: push.elapsed = %7.4fs pop.elapsed = %7.4fs\n", title, t1, t2) end # Benchmark on push! and pop! xs = rand(10^6) #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 index::Dict{K, Int} function PriorityQueue{K,V,O}(o::O) where {K,V,O<:Ordering} new{K,V,O}(Vector{Pair{K,V}}(), o, Dict{K, Int}()) end PriorityQueue{K, V, O}(xs::Vector{Pair{K,V}}, o::O, index::Dict{K, Int}) where {K,V,O<:Ordering} = new(xs, o, index) function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering} xs = Vector{Pair{K,V}}(undef, length(itr)) index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) #CURRENT FILE: DataStructures.jl/src/disjoint_set.jl ##CHUNK 1 Base.iterate(s::DisjointSet) = iterate(s.revmap) Base.iterate(s::DisjointSet, i) = iterate(s.revmap, i) Base.length(s::DisjointSet) = length(s.internal) """ num_groups(s::DisjointSet) Get a number of groups. """ num_groups(s::DisjointSet) = num_groups(s.internal) Base.eltype(::Type{DisjointSet{T}}) where T = T Base.empty(s::DisjointSet{T}, ::Type{U}=T) where {T,U} = DisjointSet{U}() function Base.sizehint!(s::DisjointSet, n::Integer) sizehint!(s.intmap, n) sizehint!(s.revmap, n) sizehint!(s.internal, n) return s end Based on the information above, please generate test code for the following function: function DisjointSet{T}(xs) where T # xs must be iterable imap = Dict{T,Int}() rmap = Vector{T}() n = length(xs)::Int sizehint!(imap, n) sizehint!(rmap, n) id = 0 for x in xs imap[x] = (id += 1) push!(rmap,x) end return new{T}(imap, rmap, IntDisjointSet(n)) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "disjoint_set.jl" ], "ground_truth": "function DisjointSet{T}(xs) where T # xs must be iterable\n imap = Dict{T,Int}()\n rmap = Vector{T}()\n n = length(xs)::Int\n sizehint!(imap, n)\n sizehint!(rmap, n)\n id = 0\n for x in xs\n imap[x] = (id += 1)\n push!(rmap,x)\n end\n return new{T}(imap, rmap, IntDisjointSet(n))\n end", "task_id": "DataStructures/23" }
150
162
DataStructures.jl
23
function DisjointSet{T}(xs) where T # xs must be iterable imap = Dict{T,Int}() rmap = Vector{T}() n = length(xs)::Int sizehint!(imap, n) sizehint!(rmap, n) id = 0 for x in xs imap[x] = (id += 1) push!(rmap,x) end return new{T}(imap, rmap, IntDisjointSet(n)) end
DisjointSet{T}(xs) where T
[ 150, 162 ]
function DisjointSet{T}(xs) where T # xs must be iterable imap = Dict{T,Int}() rmap = Vector{T}() n = length(xs)::Int sizehint!(imap, n) sizehint!(rmap, n) id = 0 for x in xs imap[x] = (id += 1) push!(rmap,x) end return new{T}(imap, rmap, IntDisjointSet(n)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_mutable_binheap.jl ##CHUNK 1 ord = h.ordering nodes = h.nodes n = length(h) m = div(n,2) for i = 1 : m v = nodes[i].value lc = i * 2 if lc <= n if Base.lt(ord, nodes[lc].value, v) return false end end rc = lc + 1 if rc <= n if Base.lt(ord, nodes[rc].value, v) return false end end end return true ##CHUNK 2 for i = 1 : length(nodemap) id = nodemap[i] if id > 0 push!(vs, nodes[id].value) end end vs end function verify_heap(h::MutableBinaryHeap{VT,O}) where {VT,O} ord = h.ordering nodes = h.nodes n = length(h) m = div(n,2) for i = 1 : m v = nodes[i].value lc = i * 2 if lc <= n if Base.lt(ord, nodes[lc].value, v) return false #FILE: DataStructures.jl/src/list.jl ##CHUNK 1 function list(elts::T...) where T l = nil(T) for i=length(elts):-1:1 l = cons(elts[i],l) end return l end Base.length(l::Nil) = 0 function Base.length(l::Cons) n = 0 for i in l n += 1 end return n end Base.map(f::Base.Callable, l::Nil) = l ##CHUNK 2 function Base.length(l::Cons) n = 0 for i in l n += 1 end return n end Base.map(f::Base.Callable, l::Nil) = l function Base.map(f::Base.Callable, l::Cons{T}) where T first = f(l.head) l2 = cons(first, nil(typeof(first) <: T ? T : typeof(first))) for h in l.tail l2 = cons(f(h), l2) end reverse(l2) end #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 sum += ft.bi_tree[i] i -= i&(-i) end sum end Base.getindex(ft::FenwickTree{T}, ind::Integer) where T = prefixsum(ft, ind) #FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 end function _heap_bubble_down!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value n = length(nodes) last_parent = n >> 1 swapped = true i = nd_id while swapped && i <= last_parent il = i << 1 if il < n # contains both left and right children ir = il + 1 ##CHUNK 2 MutableBinaryMaxHeap(xs::AbstractVector{T}) where T = MutableBinaryMaxHeap{T}(xs) function Base.show(io::IO, h::MutableBinaryHeap) print(io, "MutableBinaryHeap(") nodes = h.nodes n = length(nodes) if n > 0 print(io, string(nodes[1].value)) for i = 2 : n print(io, ", $(nodes[i].value)") end end print(io, ")") end ################################################# # # interfaces ##CHUNK 3 function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 If n is smaller than the current buffer length, the first n elements will be retained. """ function Base.resize!(cb::CircularBuffer, n::Integer) if n != capacity(cb) buf_new = Vector{eltype(cb)}(undef, n) len_new = min(length(cb), n) for i in 1:len_new @inbounds buf_new[i] = cb[i] end cb.capacity = n cb.first = 1 cb.length = len_new cb.buffer = buf_new end return cb end #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 pop!(s, last(s)) end function Base.pop!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : throw(KeyError(n)) end function Base.pop!(s::IntSet, n::Integer, default) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : default end function Base.pop!(f::Function, s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : f() end _delete!(s::IntSet, n::Integer) = _setint!(s, n, s.inverse) Base.delete!(s::IntSet, n::Integer) = n < 0 ? s : _delete!(s, n) Base.popfirst!(s::IntSet) = pop!(s, first(s)) Base.empty!(s::IntSet) = (fill!(s.bits, false); s.inverse = false; s) Base.isempty(s::IntSet) = s.inverse ? length(s.bits) == typemax(Int) && all(s.bits) : !any(s.bits) #CURRENT FILE: DataStructures.jl/src/heaps.jl Based on the information above, please generate test code for the following function: function nextreme(ord::Base.Ordering, n::Int, arr::AbstractVector{T}) where T if n <= 0 return T[] # sort(arr)[1:n] returns [] for n <= 0 elseif n >= length(arr) return sort(arr, order = ord) end rev = Base.ReverseOrdering(ord) buffer = heapify(arr[1:n], rev) for i = n + 1 : length(arr) @inbounds xi = arr[i] if Base.lt(rev, buffer[1], xi) buffer[1] = xi percolate_down!(buffer, 1, rev) end end return sort!(buffer, order = ord) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps.jl" ], "ground_truth": "function nextreme(ord::Base.Ordering, n::Int, arr::AbstractVector{T}) where T\n if n <= 0\n return T[] # sort(arr)[1:n] returns [] for n <= 0\n elseif n >= length(arr)\n return sort(arr, order = ord)\n end\n\n rev = Base.ReverseOrdering(ord)\n\n buffer = heapify(arr[1:n], rev)\n\n for i = n + 1 : length(arr)\n @inbounds xi = arr[i]\n if Base.lt(rev, buffer[1], xi)\n buffer[1] = xi\n percolate_down!(buffer, 1, rev)\n end\n end\n\n return sort!(buffer, order = ord)\nend", "task_id": "DataStructures/24" }
111
131
DataStructures.jl
24
function nextreme(ord::Base.Ordering, n::Int, arr::AbstractVector{T}) where T if n <= 0 return T[] # sort(arr)[1:n] returns [] for n <= 0 elseif n >= length(arr) return sort(arr, order = ord) end rev = Base.ReverseOrdering(ord) buffer = heapify(arr[1:n], rev) for i = n + 1 : length(arr) @inbounds xi = arr[i] if Base.lt(rev, buffer[1], xi) buffer[1] = xi percolate_down!(buffer, 1, rev) end end return sort!(buffer, order = ord) end
nextreme(ord::Base.Ordering, n::Int, arr::AbstractVector{T}) where T
[ 111, 131 ]
function nextreme(ord::Base.Ordering, n::Int, arr::AbstractVector{T}) where T if n <= 0 return T[] # sort(arr)[1:n] returns [] for n <= 0 elseif n >= length(arr) return sort(arr, order = ord) end rev = Base.ReverseOrdering(ord) buffer = heapify(arr[1:n], rev) for i = n + 1 : length(arr) @inbounds xi = arr[i] if Base.lt(rev, buffer[1], xi) buffer[1] = xi percolate_down!(buffer, 1, rev) end end return sort!(buffer, order = ord) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 function Base.get(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) i == 0 ? default : pq.xs[i].second end function Base.get!(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) if i == 0 push!(pq, key=>default) return default else return pq.xs[i].second end end # Change the priority of an existing element, or enqueue it if it isn't present. function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end Base.@propagate_inbounds _iterate(t::RobinDict{K,V}, i) where {K,V} = i == 0 ? nothing : (Pair{K,V}(t.keys[i],t.vals[i]), i == typemax(Int) ? 0 : get_next_filled(t, i+1)) Base.@propagate_inbounds function Base.iterate(t::RobinDict) _iterate(t, t.idxfloor) end Base.@propagate_inbounds Base.iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i)) function _merge_kvtypes(d, others...) K, V = keytype(d), valtype(d) for other in others K = promote_type(K, keytype(other)) ##CHUNK 2 Base.@propagate_inbounds _iterate(t::RobinDict{K,V}, i) where {K,V} = i == 0 ? nothing : (Pair{K,V}(t.keys[i],t.vals[i]), i == typemax(Int) ? 0 : get_next_filled(t, i+1)) Base.@propagate_inbounds function Base.iterate(t::RobinDict) _iterate(t, t.idxfloor) end Base.@propagate_inbounds Base.iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i)) function _merge_kvtypes(d, others...) K, V = keytype(d), valtype(d) for other in others K = promote_type(K, keytype(other)) V = promote_type(V, valtype(other)) end return (K, V) end function Base.merge(d::RobinDict, others::AbstractDict...) K, V = _merge_kvtypes(d, others...) merge!(RobinDict{K,V}(), d, others...) end #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 pos_diff = i - des_ind else pos_diff = sz - des_ind + i end dist = calculate_distance(h, i) @assert dist == pos_diff max_disp = max(max_disp, dist) distlast = (i != 1) ? isslotfilled(h, i-1) ? calculate_distance(h, i-1) : 0 : isslotfilled(h, sz) ? calculate_distance(h, sz) : 0 @assert dist <= distlast + 1 end @assert h.idxfloor == min_idx @assert cnt == length(h) end h = RobinDict() for i = 1:10000 h[i] = i+1 end check_invariants(h) #CURRENT FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 function Base.iterate(s::IntSet, i::Int, invert=false) i <= 0 && return nothing return (i-1, findnextidx(s, i, invert)) end # Nextnot iterates through elements *not* in the set nextnot(s::IntSet, i) = iterate(s, i, true) function Base.last(s::IntSet) l = length(s.bits) if s.inverse idx = l < typemax(Int) ? typemax(Int) : something(findprevnot(s.bits, l), 0) else idx = something(findprev(s.bits, l), 0) end idx == 0 ? throw(ArgumentError("collection must be non-empty")) : idx - 1 end Base.length(s::IntSet) = (n = sum(s.bits); ifelse(s.inverse, typemax(Int) - n, n)) ##CHUNK 2 l = length(s.bits) if s.inverse idx = l < typemax(Int) ? typemax(Int) : something(findprevnot(s.bits, l), 0) else idx = something(findprev(s.bits, l), 0) end idx == 0 ? throw(ArgumentError("collection must be non-empty")) : idx - 1 end Base.length(s::IntSet) = (n = sum(s.bits); ifelse(s.inverse, typemax(Int) - n, n)) complement(s::IntSet) = complement!(copy(s)) complement!(s::IntSet) = (s.inverse = !s.inverse; s) function Base.show(io::IO, s::IntSet) print(io, "IntSet([") first = true for n in s if s.inverse && n > 2 state = nextnot(s, n - 3) ##CHUNK 3 pop!(s, last(s)) end function Base.pop!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : throw(KeyError(n)) end function Base.pop!(s::IntSet, n::Integer, default) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : default end function Base.pop!(f::Function, s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : f() end _delete!(s::IntSet, n::Integer) = _setint!(s, n, s.inverse) Base.delete!(s::IntSet, n::Integer) = n < 0 ? s : _delete!(s, n) Base.popfirst!(s::IntSet) = pop!(s, first(s)) Base.empty!(s::IntSet) = (fill!(s.bits, false); s.inverse = false; s) Base.isempty(s::IntSet) = s.inverse ? length(s.bits) == typemax(Int) && all(s.bits) : !any(s.bits) ##CHUNK 4 function Base.pop!(f::Function, s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : f() end _delete!(s::IntSet, n::Integer) = _setint!(s, n, s.inverse) Base.delete!(s::IntSet, n::Integer) = n < 0 ? s : _delete!(s, n) Base.popfirst!(s::IntSet) = pop!(s, first(s)) Base.empty!(s::IntSet) = (fill!(s.bits, false); s.inverse = false; s) Base.isempty(s::IntSet) = s.inverse ? length(s.bits) == typemax(Int) && all(s.bits) : !any(s.bits) # Mathematical set functions: union!, intersect!, setdiff!, symdiff! # When applied to two intsets, these all have a similar form: # - Reshape s1 to match s2, occasionally grabbing the bits that were removed # - Use map to apply some bitwise operation across the entire bitvector # - These operations use functors to work on the bitvector chunks, so are # very efficient... but a little untraditional. E.g., (p > q) => (p & ~q) # - If needed, append the removed bits back to s1 or invert the array Base.union(s::IntSet, ns) = union!(copy(s), ns) ##CHUNK 5 const _intset_bounds_err_msg = "elements of IntSet must be between 0 and typemax(Int)-1" function Base.push!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) _setint!(s, n, !s.inverse) end Base.push!(s::IntSet, ns::Integer...) = (for n in ns; push!(s, n); end; s) function Base.pop!(s::IntSet) s.inverse && throw(ArgumentError("cannot pop the last element of complement IntSet")) pop!(s, last(s)) end function Base.pop!(s::IntSet, n::Integer) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : throw(KeyError(n)) end function Base.pop!(s::IntSet, n::Integer, default) 0 <= n < typemax(Int) || throw(ArgumentError(_intset_bounds_err_msg)) n in s ? (_delete!(s, n); n) : default end ##CHUNK 6 l1 == l2 && return s1.bits == s2.bits # Otherwise check the last bit. If equal, we only need to check up to l2 return findprev(s1.bits, l1) == findprev(s2.bits, l2) && unsafe_getindex(s1.bits, 1:l2) == s2.bits else # one complement, one not. Could feasibly be true on 32 bit machines # Only if all non-overlapping bits are set and overlaps are inverted return l1 == typemax(Int) && map!(!, unsafe_getindex(s1.bits, 1:l2)) == s2.bits && (l1 == l2 || all(unsafe_getindex(s1.bits, l2+1:l1))) end end const hashis_seed = UInt === UInt64 ? 0x88989f1fc7dea67d : 0xc7dea67d function Base.hash(s::IntSet, h::UInt) # Only hash the bits array up to the last-set bit to prevent extra empty # bits from changing the hash result l = findprev(s.bits, length(s.bits)) return hash(unsafe_getindex(s.bits, 1:l), h) ⊻ hash(s.inverse) ⊻ hashis_seed end Based on the information above, please generate test code for the following function: function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert # i+1 could rollover causing a BoundsError in findnext/findnextnot nextidx = i == typemax(Int) ? 0 : something(findnextnot(s.bits, i+1), 0) # Extend indices beyond the length of the bits since it is inverted nextidx = nextidx == 0 ? max(i, length(s.bits))+1 : nextidx else nextidx = i == typemax(Int) ? 0 : something(findnext(s.bits, i+1), 0) end return nextidx end
{ "fpath_tuple": [ "DataStructures.jl", "src", "int_set.jl" ], "ground_truth": "function findnextidx(s::IntSet, i::Int, invert=false)\n if s.inverse ⊻ invert\n # i+1 could rollover causing a BoundsError in findnext/findnextnot\n nextidx = i == typemax(Int) ? 0 : something(findnextnot(s.bits, i+1), 0)\n # Extend indices beyond the length of the bits since it is inverted\n nextidx = nextidx == 0 ? max(i, length(s.bits))+1 : nextidx\n else\n nextidx = i == typemax(Int) ? 0 : something(findnext(s.bits, i+1), 0)\n end\n return nextidx\nend", "task_id": "DataStructures/25" }
159
169
DataStructures.jl
25
function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert # i+1 could rollover causing a BoundsError in findnext/findnextnot nextidx = i == typemax(Int) ? 0 : something(findnextnot(s.bits, i+1), 0) # Extend indices beyond the length of the bits since it is inverted nextidx = nextidx == 0 ? max(i, length(s.bits))+1 : nextidx else nextidx = i == typemax(Int) ? 0 : something(findnext(s.bits, i+1), 0) end return nextidx end
findnextidx(s::IntSet, i::Int, invert=false)
[ 159, 169 ]
function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert # i+1 could rollover causing a BoundsError in findnext/findnextnot nextidx = i == typemax(Int) ? 0 : something(findnextnot(s.bits, i+1), 0) # Extend indices beyond the length of the bits since it is inverted nextidx = nextidx == 0 ? max(i, length(s.bits))+1 : nextidx else nextidx = i == typemax(Int) ? 0 : something(findnext(s.bits, i+1), 0) end return nextidx end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end function Base.getindex(h::SwissDict{K,V}, key) where {K, V} index = ht_keyindex(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index]::V end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. # Examples #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 return v end function Base.getindex(h::RobinDict{K, V}, key) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index] end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. # Examples ```jldoctest julia> d = RobinDict("a"=>1, "b"=>2); julia> get(d, "a", 3) ##CHUNK 2 return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) return v end function Base.getindex(h::RobinDict{K, V}, key) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index] end """ get(collection, key, default) ##CHUNK 3 Return the value stored for the given key, or the given default value if no mapping for the key is present. # Examples ```jldoctest julia> d = RobinDict("a"=>1, "b"=>2); julia> get(d, "a", 3) 1 julia> get(d, "c", 3) 3 ``` """ function Base.get(h::RobinDict{K,V}, key, default) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? default : h.vals[index]::V end #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 """ function Base.get!(default::Base.Callable, h::OrderedRobinDict{K,V}, key0) where {K,V} index = get(h.dict, key0, -2) index > 0 && return @inbounds h.vals[index] v = convert(V, default()) setindex!(h, v, key0) return v end function Base.getindex(h::OrderedRobinDict{K,V}, key) where {K,V} index = get(h.dict, key, -1) return (index < 0) ? throw(KeyError(key)) : @inbounds h.vals[index]::V end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. ##CHUNK 2 function Base.getindex(h::OrderedRobinDict{K,V}, key) where {K,V} index = get(h.dict, key, -1) return (index < 0) ? throw(KeyError(key)) : @inbounds h.vals[index]::V end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. # Examples ```jldoctest julia> d = OrderedRobinDict("a"=>1, "b"=>2); julia> get(d, "a", 3) 1 julia> get(d, "c", 3) ##CHUNK 3 # Examples ```jldoctest julia> d = OrderedRobinDict("a"=>1, "b"=>2); julia> get(d, "a", 3) 1 julia> get(d, "c", 3) 3 ``` """ function Base.get(h::OrderedRobinDict{K,V}, key, default) where {K,V} index = get(h.dict, key, -1) return (index < 0) ? default : @inbounds h.vals[index]::V end """ get(f::Function, collection, key) #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j end pq.index[x.first] = i pq.xs[i] = x end Base.getindex(pq::PriorityQueue, key) = pq.xs[pq.index[key]].second function Base.get(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) i == 0 ? default : pq.xs[i].second end function Base.get!(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) if i == 0 push!(pq, key=>default) return default ##CHUNK 2 function Base.get(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) i == 0 ? default : pq.xs[i].second end function Base.get!(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) if i == 0 push!(pq, key=>default) return default else return pq.xs[i].second end end # Change the priority of an existing element, or enqueue it if it isn't present. function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second #CURRENT FILE: DataStructures.jl/src/multi_dict.jl ##CHUNK 1 if !haskey(d.d, k) d.d[k] = V[] end push!(d.d[k], v) return d end function Base.in(pr::(Tuple{Any,Any}), d::MultiDict{K,V}) where {K,V} k = convert(K, pr[1]) v = get(d,k,Base.secret_table_token) (v !== Base.secret_table_token) && (pr[2] in v) end Base.pop!(d::MultiDict, key) = pop!(d, key, Base.secret_table_token) Base.push!(d::MultiDict, kv::Pair) = insert!(d, kv[1], kv[2]) #Base.push!(d::MultiDict, kv::Pair, kv2::Pair) = (push!(d.d, kv, kv2); d) #Base.push!(d::MultiDict, kv::Pair, kv2::Pair, kv3::Pair...) = (push!(d.d, kv, kv2, kv3...); d) Base.push!(d::MultiDict, kv) = insert!(d, kv[1], kv[2]) Based on the information above, please generate test code for the following function: function Base.pop!(d::MultiDict, key, default) vs = get(d, key, Base.secret_table_token) if vs === Base.secret_table_token if default !== Base.secret_table_token return default else throw(KeyError(key)) end end v = pop!(vs) (length(vs) == 0) && delete!(d, key) return v end
{ "fpath_tuple": [ "DataStructures.jl", "src", "multi_dict.jl" ], "ground_truth": "function Base.pop!(d::MultiDict, key, default)\n vs = get(d, key, Base.secret_table_token)\n if vs === Base.secret_table_token\n if default !== Base.secret_table_token\n return default\n else\n throw(KeyError(key))\n end\n end\n v = pop!(vs)\n (length(vs) == 0) && delete!(d, key)\n return v\nend", "task_id": "DataStructures/26" }
64
76
DataStructures.jl
26
function Base.pop!(d::MultiDict, key, default) vs = get(d, key, Base.secret_table_token) if vs === Base.secret_table_token if default !== Base.secret_table_token return default else throw(KeyError(key)) end end v = pop!(vs) (length(vs) == 0) && delete!(d, key) return v end
Base.pop!(d::MultiDict, key, default)
[ 64, 76 ]
function Base.pop!(d::MultiDict, key, default) vs = get(d, key, Base.secret_table_token) if vs === Base.secret_table_token if default !== Base.secret_table_token return default else throw(KeyError(key)) end end v = pop!(vs) (length(vs) == 0) && delete!(d, key) return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 index = ht_keyindex(h, key) if index > 0 _delete!(h, index) end maybe_rehash_shrink!(h) return h end Base.@propagate_inbounds function Base.iterate(h::SwissDict, state = h.idxfloor) is = _iterslots(h, state) is === nothing && return nothing i, s = is @inbounds p = h.keys[i] => h.vals[i] return (p, s) end Base.@propagate_inbounds function Base.iterate(v::Union{KeySet{<:Any, <:SwissDict}, Base.ValueIterator{<:SwissDict}}, state=v.dict.idxfloor) is = _iterslots(v.dict, state) is === nothing && return nothing i, s = is ##CHUNK 2 is === nothing && return nothing i, s = is @inbounds p = h.keys[i] => h.vals[i] return (p, s) end Base.@propagate_inbounds function Base.iterate(v::Union{KeySet{<:Any, <:SwissDict}, Base.ValueIterator{<:SwissDict}}, state=v.dict.idxfloor) is = _iterslots(v.dict, state) is === nothing && return nothing i, s = is return (v isa KeySet ? v.dict.keys[i] : v.dict.vals[i], s) end #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 2 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 3 (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 ##CHUNK 4 is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 function Base.merge!(d::AbstractDict, other::PriorityQueue) next = iterate(other, false) while next !== nothing (k, v), state = next d[k] = v next = iterate(other, state) end return d end function Base.merge!(combine::Function, d::AbstractDict, other::PriorityQueue) next = iterate(other, false) while next !== nothing (k, v), state = next d[k] = haskey(d, k) ? combine(d[k], v) : v next = iterate(other, state) end return d end #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ #CURRENT FILE: DataStructures.jl/src/multi_dict.jl ##CHUNK 1 struct EnumerateAll d::MultiDict end enumerateall(d::MultiDict) = EnumerateAll(d) Base.length(e::EnumerateAll) = count(e.d) function Base.iterate(e::EnumerateAll, s) dstate, k, vs, vstate = s dstate === nothing || vstate === nothing && return nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end ##CHUNK 2 #Base.push!(d::MultiDict, kv::Pair, kv2::Pair, kv3::Pair...) = (push!(d.d, kv, kv2, kv3...); d) Base.push!(d::MultiDict, kv) = insert!(d, kv[1], kv[2]) #Base.push!(d::MultiDict, kv, kv2...) = (push!(d.d, kv, kv2...); d) Base.count(d::MultiDict) = length(keys(d)) == 0 ? 0 : mapreduce(k -> length(d[k]), +, keys(d)) Base.size(d::MultiDict) = (length(keys(d)), count(d::MultiDict)) # enumerate struct EnumerateAll d::MultiDict end enumerateall(d::MultiDict) = EnumerateAll(d) Base.length(e::EnumerateAll) = count(e.d) function Base.iterate(e::EnumerateAll, s) dstate, k, vs, vstate = s Based on the information above, please generate test code for the following function: function Base.iterate(e::EnumerateAll) V = eltype(eltype(values(e.d))) vs = V[] dstate = iterate(e.d.d) vstate = iterate(vs) dstate === nothing || vstate === nothing && return nothing k = nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "multi_dict.jl" ], "ground_truth": "function Base.iterate(e::EnumerateAll)\n V = eltype(eltype(values(e.d)))\n vs = V[]\n dstate = iterate(e.d.d)\n vstate = iterate(vs)\n dstate === nothing || vstate === nothing && return nothing\n k = nothing\n while vstate === nothing\n ((k, vs), dst) = dstate\n dstate = iterate(e.d.d, dst)\n vstate = iterate(vs)\n end\n v, vst = vstate\n return ((k, v), (dstate, k, vs, vstate))\nend", "task_id": "DataStructures/27" }
98
112
DataStructures.jl
27
function Base.iterate(e::EnumerateAll) V = eltype(eltype(values(e.d))) vs = V[] dstate = iterate(e.d.d) vstate = iterate(vs) dstate === nothing || vstate === nothing && return nothing k = nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
Base.iterate(e::EnumerateAll)
[ 98, 112 ]
function Base.iterate(e::EnumerateAll) V = eltype(eltype(values(e.d))) vs = V[] dstate = iterate(e.d.d) vstate = iterate(vs) dstate === nothing || vstate === nothing && return nothing k = nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 is === nothing && return nothing i, s = is @inbounds p = h.keys[i] => h.vals[i] return (p, s) end Base.@propagate_inbounds function Base.iterate(v::Union{KeySet{<:Any, <:SwissDict}, Base.ValueIterator{<:SwissDict}}, state=v.dict.idxfloor) is = _iterslots(v.dict, state) is === nothing && return nothing i, s = is return (v isa KeySet ? v.dict.keys[i] : v.dict.vals[i], s) end ##CHUNK 2 index = ht_keyindex(h, key) if index > 0 _delete!(h, index) end maybe_rehash_shrink!(h) return h end Base.@propagate_inbounds function Base.iterate(h::SwissDict, state = h.idxfloor) is = _iterslots(h, state) is === nothing && return nothing i, s = is @inbounds p = h.keys[i] => h.vals[i] return (p, s) end Base.@propagate_inbounds function Base.iterate(v::Union{KeySet{<:Any, <:SwissDict}, Base.ValueIterator{<:SwissDict}}, state=v.dict.idxfloor) is = _iterslots(v.dict, state) is === nothing && return nothing i, s = is #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 2 (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 ##CHUNK 3 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 4 is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end ##CHUNK 5 end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 function Base.merge!(d::AbstractDict, other::PriorityQueue) next = iterate(other, false) while next !== nothing (k, v), state = next d[k] = v next = iterate(other, state) end return d end function Base.merge!(combine::Function, d::AbstractDict, other::PriorityQueue) next = iterate(other, false) while next !== nothing (k, v), state = next d[k] = haskey(d, k) ? combine(d[k], v) : v next = iterate(other, state) end return d end #CURRENT FILE: DataStructures.jl/src/multi_dict.jl ##CHUNK 1 dstate = iterate(e.d.d) vstate = iterate(vs) dstate === nothing || vstate === nothing && return nothing k = nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end ##CHUNK 2 struct EnumerateAll d::MultiDict end enumerateall(d::MultiDict) = EnumerateAll(d) Base.length(e::EnumerateAll) = count(e.d) function Base.iterate(e::EnumerateAll) V = eltype(eltype(values(e.d))) vs = V[] dstate = iterate(e.d.d) vstate = iterate(vs) dstate === nothing || vstate === nothing && return nothing k = nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate Based on the information above, please generate test code for the following function: function Base.iterate(e::EnumerateAll, s) dstate, k, vs, vstate = s dstate === nothing || vstate === nothing && return nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "multi_dict.jl" ], "ground_truth": "function Base.iterate(e::EnumerateAll, s)\n dstate, k, vs, vstate = s\n dstate === nothing || vstate === nothing && return nothing\n while vstate === nothing\n ((k, vs), dst) = dstate\n dstate = iterate(e.d.d, dst)\n vstate = iterate(vs)\n end\n v, vst = vstate\n return ((k, v), (dstate, k, vs, vstate))\nend", "task_id": "DataStructures/28" }
114
124
DataStructures.jl
28
function Base.iterate(e::EnumerateAll, s) dstate, k, vs, vstate = s dstate === nothing || vstate === nothing && return nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
Base.iterate(e::EnumerateAll, s)
[ 114, 124 ]
function Base.iterate(e::EnumerateAll, s) dstate, k, vs, vstate = s dstate === nothing || vstate === nothing && return nothing while vstate === nothing ((k, vs), dst) = dstate dstate = iterate(e.d.d, dst) vstate = iterate(vs) end v, vst = vstate return ((k, v), (dstate, k, vs, vstate)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end ##CHUNK 2 @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev ##CHUNK 3 l2 = MutableLinkedList{T}() for h in l push!(l2, h) end return l2 end function Base.getindex(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end return node.data end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node ##CHUNK 4 function Base.reverse(l::MutableLinkedList{T}) where T l2 = MutableLinkedList{T}() for h in l pushfirst!(l2, h) end return l2 end function Base.copy(l::MutableLinkedList{T}) where T l2 = MutableLinkedList{T}() for h in l push!(l2, h) end return l2 end function Base.getindex(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node ##CHUNK 5 len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end function Base.push!(l::MutableLinkedList{T}, data) where T oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node oldlast.next = node l.len += 1 return l ##CHUNK 6 function Base.append!(l::MutableLinkedList, elts...) for elt in elts for v in elt push!(l, v) end end return l end function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 ##CHUNK 7 for i in 1:idx node = node.next end return node.data end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end node.data = convert(T, data) return l end function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node ##CHUNK 8 end function Base.push!(l::MutableLinkedList{T}, data1, data...) where T push!(l, data1) for v in data push!(l, v) end return l end function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 return l end ##CHUNK 9 function Base.push!(l::MutableLinkedList{T}, data) where T oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node oldlast.next = node l.len += 1 return l end function Base.push!(l::MutableLinkedList{T}, data1, data...) where T push!(l, data1) for v in data push!(l, v) end return l end ##CHUNK 10 function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 return l end function Base.pop!(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List must be non-empty")) last = l.node.prev.prev data = l.node.prev.data last.next = l.node l.node.prev = last l.len -= 1 return data end Based on the information above, please generate test code for the following function: function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 end
{ "fpath_tuple": [ "DataStructures.jl", "src", "mutable_list.jl" ], "ground_truth": "function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T\n @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r))\n l2 = MutableLinkedList{T}()\n node = l.node\n for i in 1:first(r)\n node = node.next\n end\n len = length(r)\n for j in 1:len\n push!(l2, node.data)\n node = node.next\n end\n l2.len = len\n return l2\nend", "task_id": "DataStructures/29" }
127
141
DataStructures.jl
29
function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 end
Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T
[ 127, 141 ]
function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 function Base.show(io::IO, blk::DequeBlock) # avoids recursion into prev and next x = blk.data[blk.front:blk.back] print(io, "$(typeof(blk))(capa = $(blk.capa), front = $(blk.front), back = $(blk.back)): $x") end ####################################### # # Deque # ####################################### const DEFAULT_DEQUEUE_BLOCKSIZE = 1024 """ Deque{T} Deque{T}(blksize::Int) where T Constructs `Deque` object for elements of type `T`. ##CHUNK 2 # reset the block to empty, and position function reset!(blk::DequeBlock{T}, front::Integer) where T empty!(blk.data) resize!(blk.data, blk.capa) blk.front = front blk.back = front - 1 blk.prev = blk blk.next = blk end function Base.show(io::IO, blk::DequeBlock) # avoids recursion into prev and next x = blk.data[blk.front:blk.back] print(io, "$(typeof(blk))(capa = $(blk.capa), front = $(blk.front), back = $(blk.back)): $x") end ####################################### # # Deque #FILE: DataStructures.jl/src/accumulator.jl ##CHUNK 1 # manipulation """ inc!(ct::Accumulator, x, [v=1]) Increments the count for `x` by `v` (defaulting to one) """ inc!(ct::Accumulator, x, v::Number) = (ct[x] += v) inc!(ct::Accumulator{T, V}, x) where {T, V} = inc!(ct, x, one(V)) # inc! is preferred over push!, but we need to provide push! for the Bag interpretation # which is used by classified_collections.jl Base.push!(ct::Accumulator, x) = inc!(ct, x) Base.push!(ct::Accumulator, x, a::Number) = inc!(ct, x, a) # To remove ambiguities related to Accumulator now being a subtype of AbstractDict Base.push!(ct::Accumulator, x::Pair) = inc!(ct, x) ##CHUNK 2 # inc! is preferred over push!, but we need to provide push! for the Bag interpretation # which is used by classified_collections.jl Base.push!(ct::Accumulator, x) = inc!(ct, x) Base.push!(ct::Accumulator, x, a::Number) = inc!(ct, x, a) # To remove ambiguities related to Accumulator now being a subtype of AbstractDict Base.push!(ct::Accumulator, x::Pair) = inc!(ct, x) """ dec!(ct::Accumulator, x, [v=1]) Decrements the count for `x` by `v` (defaulting to one) """ dec!(ct::Accumulator, x, v::Number) = (ct[x] -= v) dec!(ct::Accumulator{T,V}, x) where {T,V} = dec!(ct, x, one(V)) #TODO: once we are done deprecating `pop!` for `reset!` then add `pop!` as an alias for `dec!` #FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 end function _binary_heap_pop!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T # extract node rt = nodes[nd_id] v = rt.value @inbounds nodemap[rt.handle] = 0 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end function _pop!(h::RobinDict, index) @inbounds val = h.vals[index] rh_delete!(h, index) return val end ##CHUNK 2 #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 #CURRENT FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end function Base.push!(l::MutableLinkedList{T}, data) where T oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node ##CHUNK 2 prev.next = next next.prev = prev l.len -= 1 return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev ##CHUNK 3 end function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) Based on the information above, please generate test code for the following function: function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last l1.node.prev = l2.node.prev # l1's first's prev is now l2's last l1.len += length(l2) # make l2 empty l2.node.prev = l2.node l2.node.next = l2.node l2.len = 0 return l1 end
{ "fpath_tuple": [ "DataStructures.jl", "src", "mutable_list.jl" ], "ground_truth": "function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T\n l1.node.prev.next = l2.node.next # l1's last's next is now l2's first\n l2.node.prev.next = l1.node # l2's last's next is now l1.node\n l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last\n l1.node.prev = l2.node.prev # l1's first's prev is now l2's last\n l1.len += length(l2)\n # make l2 empty\n l2.node.prev = l2.node\n l2.node.next = l2.node\n l2.len = 0\n return l1\nend", "task_id": "DataStructures/30" }
153
164
DataStructures.jl
30
function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last l1.node.prev = l2.node.prev # l1's first's prev is now l2's last l1.len += length(l2) # make l2 empty l2.node.prev = l2.node l2.node.next = l2.node l2.len = 0 return l1 end
Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T
[ 153, 164 ]
function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last l1.node.prev = l2.node.prev # l1's first's prev is now l2's last l1.len += length(l2) # make l2 empty l2.node.prev = l2.node l2.node.next = l2.node l2.len = 0 return l1 end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 end return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len ##CHUNK 2 end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end function Base.push!(l::MutableLinkedList{T}, data) where T oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node oldlast.next = node ##CHUNK 3 l2 = MutableLinkedList{T}() for h in l push!(l2, h) end return l2 end function Base.getindex(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end return node.data end function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node ##CHUNK 4 for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end node.data = convert(T, data) return l ##CHUNK 5 end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end node.data = convert(T, data) return l end function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last l1.node.prev = l2.node.prev # l1's first's prev is now l2's last l1.len += length(l2) # make l2 empty l2.node.prev = l2.node ##CHUNK 6 for i in 1:idx node = node.next end return node.data end function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 ##CHUNK 7 l2.node.next = l2.node l2.len = 0 return l1 end function Base.append!(l::MutableLinkedList, elts...) for elt in elts for v in elt push!(l, v) end end return l end function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next ##CHUNK 8 function Base.reverse(l::MutableLinkedList{T}) where T l2 = MutableLinkedList{T}() for h in l pushfirst!(l2, h) end return l2 end function Base.copy(l::MutableLinkedList{T}) where T l2 = MutableLinkedList{T}() for h in l push!(l2, h) end return l2 end function Base.getindex(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node ##CHUNK 9 end function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 return l end function Base.pop!(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List must be non-empty")) last = l.node.prev.prev data = l.node.prev.data last.next = l.node l.node.prev = last l.len -= 1 ##CHUNK 10 l.len += 1 return l end function Base.push!(l::MutableLinkedList{T}, data1, data...) where T push!(l, data1) for v in data push!(l, v) end return l end function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 Based on the information above, please generate test code for the following function: function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end
{ "fpath_tuple": [ "DataStructures.jl", "src", "mutable_list.jl" ], "ground_truth": "function Base.delete!(l::MutableLinkedList, idx::Int)\n @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx))\n node = l.node\n for i = 1:idx\n node = node.next\n end\n prev = node.prev\n next = node.next\n prev.next = next\n next.prev = prev\n l.len -= 1\n return l\nend", "task_id": "DataStructures/31" }
175
187
DataStructures.jl
31
function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end
Base.delete!(l::MutableLinkedList, idx::Int)
[ 175, 187 ]
function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 end return l end function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end function Base.push!(l::MutableLinkedList{T}, data) where T ##CHUNK 2 for i in 1:idx node = node.next end return node.data end function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 ##CHUNK 3 for i in 1:first(r) node = node.next end len = length(r) for j in 1:len push!(l2, node.data) node = node.next end l2.len = len return l2 end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end node.data = convert(T, data) return l ##CHUNK 4 prev = node.prev next = node.next prev.next = next next.prev = prev l.len -= 1 return l end function Base.push!(l::MutableLinkedList{T}, data) where T oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node oldlast.next = node l.len += 1 return l end ##CHUNK 5 l2 = MutableLinkedList{T}() for h in l push!(l2, h) end return l2 end function Base.getindex(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end return node.data end function Base.getindex(l::MutableLinkedList{T}, r::UnitRange) where T @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) l2 = MutableLinkedList{T}() node = l.node ##CHUNK 6 l2.node.next = l2.node l2.len = 0 return l1 end function Base.append!(l::MutableLinkedList, elts...) for elt in elts for v in elt push!(l, v) end end return l end function Base.delete!(l::MutableLinkedList, idx::Int) @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i = 1:idx node = node.next end ##CHUNK 7 end function Base.setindex!(l::MutableLinkedList{T}, data, idx::Int) where T @boundscheck 0 < idx <= l.len || throw(BoundsError(l, idx)) node = l.node for i in 1:idx node = node.next end node.data = convert(T, data) return l end function Base.append!(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T l1.node.prev.next = l2.node.next # l1's last's next is now l2's first l2.node.prev.next = l1.node # l2's last's next is now l1.node l2.node.next.prev = l1.node.prev # l2's first's prev is now l1's last l1.node.prev = l2.node.prev # l1's first's prev is now l2's last l1.len += length(l2) # make l2 empty l2.node.prev = l2.node ##CHUNK 8 node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 return l end function Base.pop!(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List must be non-empty")) last = l.node.prev.prev data = l.node.prev.data last.next = l.node l.node.prev = last l.len -= 1 return data end function Base.popfirst!(l::MutableLinkedList) ##CHUNK 9 oldlast = l.node.prev node = ListNode{T}(data) node.next = l.node node.prev = oldlast l.node.prev = node oldlast.next = node l.len += 1 return l end function Base.push!(l::MutableLinkedList{T}, data1, data...) where T push!(l, data1) for v in data push!(l, v) end return l end function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next ##CHUNK 10 function Base.push!(l::MutableLinkedList{T}, data1, data...) where T push!(l, data1) for v in data push!(l, v) end return l end function Base.pushfirst!(l::MutableLinkedList{T}, data) where T oldfirst = l.node.next node = ListNode{T}(data) node.prev = l.node node.next = oldfirst l.node.next = node oldfirst.prev = node l.len += 1 return l end function Base.pop!(l::MutableLinkedList) Based on the information above, please generate test code for the following function: function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end
{ "fpath_tuple": [ "DataStructures.jl", "src", "mutable_list.jl" ], "ground_truth": "function Base.delete!(l::MutableLinkedList, r::UnitRange)\n @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r))\n node = l.node\n for i in 1:first(r)\n node = node.next\n end\n prev = node.prev\n len = length(r)\n for j in 1:len\n node = node.next\n end\n next = node\n prev.next = next\n next.prev = prev\n l.len -= len\n return l\nend", "task_id": "DataStructures/32" }
189
205
DataStructures.jl
32
function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end
Base.delete!(l::MutableLinkedList, r::UnitRange)
[ 189, 205 ]
function Base.delete!(l::MutableLinkedList, r::UnitRange) @boundscheck 0 < first(r) < last(r) <= l.len || throw(BoundsError(l, r)) node = l.node for i in 1:first(r) node = node.next end prev = node.prev len = length(r) for j in 1:len node = node.next end next = node prev.next = next next.prev = prev l.len -= len return l end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end ##CHUNK 2 fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) ##CHUNK 3 end ``` """ function Base.get!(default::Callable, h::SwissDict{K,V}, key0) where {K, V} key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.setindex!(h::RobinDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) isequal(key, key0) || throw(ArgumentError("$key0 is not a valid key for type $K")) _setindex!(h, key, v0) end function _setindex!(h::RobinDict{K,V}, key::K, v0) where {K, V} v = convert(V, v0) index = rh_insert!(h, key, v) @assert index > 0 return h end """ empty!(collection) -> collection Remove all elements from a `collection`. # Examples ##CHUNK 2 # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end Base.@propagate_inbounds isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) Base.@propagate_inbounds isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function Base.setindex!(h::RobinDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) isequal(key, key0) || throw(ArgumentError("$key0 is not a valid key for type $K")) _setindex!(h, key, v0) end function _setindex!(h::RobinDict{K,V}, key::K, v0) where {K, V} v = convert(V, v0) index = rh_insert!(h, key, v) ##CHUNK 3 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end function _pop!(h::RobinDict, index) @inbounds val = h.vals[index] rh_delete!(h, index) return val end function Base.pop!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) return index > 0 ? _pop!(h, index) : throw(KeyError(key)) end """ pop!(collection, key[, default]) ##CHUNK 4 get!(dict, key) do # default value calculated here time() end ``` """ Base.get!(f::Function, collection, key) function Base.get!(default::Callable, h::RobinDict{K,V}, key0::K) where {K, V} key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) #CURRENT FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 time() end ``` """ function Base.get!(default::Base.Callable, h::OrderedRobinDict{K,V}, key0) where {K,V} index = get(h.dict, key0, -2) index > 0 && return @inbounds h.vals[index] v = convert(V, default()) setindex!(h, v, key0) return v end function Base.getindex(h::OrderedRobinDict{K,V}, key) where {K,V} index = get(h.dict, key, -1) return (index < 0) ? throw(KeyError(key)) : @inbounds h.vals[index]::V end """ get(collection, key, default) ##CHUNK 2 """ get!(f::Function, collection, key) Return the value stored for the given key, or if no mapping for the key is present, store `key => f()`, and return `f()`. This is intended to be called using `do` block syntax: ```julia get!(dict, key) do # default value calculated here time() end ``` """ function Base.get!(default::Base.Callable, h::OrderedRobinDict{K,V}, key0) where {K,V} index = get(h.dict, key0, -2) index > 0 && return @inbounds h.vals[index] v = convert(V, default()) setindex!(h, v, key0) ##CHUNK 3 julia> get!(d, "d", 4) 4 julia> d OrderedRobinDict{String, Int64} with 4 entries: "a" => 1 "b" => 2 "c" => 3 "d" => 4 ``` """ function Base.get!(h::OrderedRobinDict{K,V}, key0, default) where {K,V} index = get(h.dict, key0, -2) index > 0 && return h.vals[index] v = convert(V, default) setindex!(h, v, key0) return v end Based on the information above, please generate test code for the following function: function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "ordered_robin_dict.jl" ], "ground_truth": "function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V}\n key = convert(K, key0)\n v = convert(V, v0)\n index = get(h.dict, key, -2)\n\n if index < 0\n _setindex!(h, v0, key0)\n else\n @assert haskey(h, key0)\n @inbounds orig_v = h.vals[index]\n !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0)\n end\n\n check_for_rehash(h) && rehash!(h)\n\n return h\nend", "task_id": "DataStructures/33" }
125
141
DataStructures.jl
33
function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h end
Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V}
[ 125, 141 ]
function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end ##CHUNK 2 h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end function Base.sizehint!(d::RobinDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) ##CHUNK 3 @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull @assert h.age == age0 @assert h.count == count return h end Base.isempty(t::SwissDict) = (t.count == 0) Base.length(t::SwissDict) = t.count ##CHUNK 2 sz = length(h.keys) if h.count*4 < sz && sz > 16 rehash!(h, sz>>1) end end function Base.sizehint!(d::SwissDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals ##CHUNK 3 if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) ##CHUNK 4 keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) # heapify for i in heapparent(length(pq.xs)):-1:1 percolate_down!(pq, i) end return pq end end # A copy constructor #CURRENT FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 julia> empty!(A); julia> A OrderedRobinDict{String, Int64}() ``` """ function Base.empty!(h::OrderedRobinDict{K,V}) where {K, V} empty!(h.dict) empty!(h.keys) empty!(h.vals) h.count = 0 return h end function _setindex!(h::OrderedRobinDict, v, key) hk, hv = h.keys, h.vals push!(hk, key) push!(hv, v) nk = length(hk) ##CHUNK 2 empty!(h.vals) h.count = 0 return h end function _setindex!(h::OrderedRobinDict, v, key) hk, hv = h.keys, h.vals push!(hk, key) push!(hv, v) nk = length(hk) @inbounds h.dict[key] = Int32(nk) h.count += 1 end function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 Based on the information above, please generate test code for the following function: function rehash!(h::OrderedRobinDict{K, V}) where {K, V} keys = h.keys vals = h.vals hk = Vector{K}() hv = Vector{V}() for (idx, (k, v)) in enumerate(zip(keys, vals)) if get(h.dict, k, -1) == idx push!(hk, k) push!(hv, v) end end h.keys = hk h.vals = hv for (idx, k) in enumerate(h.keys) h.dict[k] = idx end return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "ordered_robin_dict.jl" ], "ground_truth": "function rehash!(h::OrderedRobinDict{K, V}) where {K, V}\n keys = h.keys\n vals = h.vals\n hk = Vector{K}()\n hv = Vector{V}()\n\n for (idx, (k, v)) in enumerate(zip(keys, vals))\n if get(h.dict, k, -1) == idx\n push!(hk, k)\n push!(hv, v)\n end\n end\n\n h.keys = hk\n h.vals = hv\n\n for (idx, k) in enumerate(h.keys)\n h.dict[k] = idx\n end\n return h\nend", "task_id": "DataStructures/34" }
151
171
DataStructures.jl
34
function rehash!(h::OrderedRobinDict{K, V}) where {K, V} keys = h.keys vals = h.vals hk = Vector{K}() hv = Vector{V}() for (idx, (k, v)) in enumerate(zip(keys, vals)) if get(h.dict, k, -1) == idx push!(hk, k) push!(hv, v) end end h.keys = hk h.vals = hv for (idx, k) in enumerate(h.keys) h.dict[k] = idx end return h end
rehash!(h::OrderedRobinDict{K, V}) where {K, V}
[ 151, 171 ]
function rehash!(h::OrderedRobinDict{K, V}) where {K, V} keys = h.keys vals = h.vals hk = Vector{K}() hv = Vector{V}() for (idx, (k, v)) in enumerate(zip(keys, vals)) if get(h.dict, k, -1) == idx push!(hk, k) push!(hv, v) end end h.keys = hk h.vals = hv for (idx, k) in enumerate(h.keys) h.dict[k] = idx end return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end function Base.sizehint!(d::RobinDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end Base.@propagate_inbounds isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) Base.@propagate_inbounds isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) ##CHUNK 2 # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end Base.@propagate_inbounds isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) Base.@propagate_inbounds isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function Base.setindex!(h::RobinDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) isequal(key, key0) || throw(ArgumentError("$key0 is not a valid key for type $K")) _setindex!(h, key, v0) end function _setindex!(h::RobinDict{K,V}, key::K, v0) where {K, V} v = convert(V, v0) index = rh_insert!(h, key, v) ##CHUNK 3 end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end ##CHUNK 4 newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] ##CHUNK 5 h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end function Base.sizehint!(d::RobinDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 sz = length(h.keys) if h.count*4 < sz && sz > 16 rehash!(h, sz>>1) end end function Base.sizehint!(d::SwissDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals ##CHUNK 2 if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) ##CHUNK 3 sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) ##CHUNK 4 # worst-case hysteresis: shrink at 25% vs grow at 30% if all hashes collide. # expected hysteresis is 25% to 42.5%. function maybe_rehash_grow!(h::SwissDict) sz = length(h.keys) if h.count > sz * SWISS_DICT_LOAD_FACTOR || (h.nbfull-1) * 10 > sz * 6 rehash!(h, sz<<2) end end function maybe_rehash_shrink!(h::SwissDict) sz = length(h.keys) if h.count*4 < sz && sz > 16 rehash!(h, sz>>1) end end function Base.sizehint!(d::SwissDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) # grow at least 25% ##CHUNK 5 h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] #CURRENT FILE: DataStructures.jl/src/ordered_robin_dict.jl Based on the information above, please generate test code for the following function: function Base.sizehint!(d::OrderedRobinDict, newsz) oldsz = length(d) # grow at least 25% if newsz < (oldsz*5)>>2 return d end sizehint!(d.keys, newsz) sizehint!(d.vals, newsz) sizehint!(d.dict, newsz) return d end
{ "fpath_tuple": [ "DataStructures.jl", "src", "ordered_robin_dict.jl" ], "ground_truth": "function Base.sizehint!(d::OrderedRobinDict, newsz)\n oldsz = length(d)\n # grow at least 25%\n if newsz < (oldsz*5)>>2\n return d\n end\n sizehint!(d.keys, newsz)\n sizehint!(d.vals, newsz)\n sizehint!(d.dict, newsz)\n return d\nend", "task_id": "DataStructures/35" }
173
183
DataStructures.jl
35
function Base.sizehint!(d::OrderedRobinDict, newsz) oldsz = length(d) # grow at least 25% if newsz < (oldsz*5)>>2 return d end sizehint!(d.keys, newsz) sizehint!(d.vals, newsz) sizehint!(d.dict, newsz) return d end
Base.sizehint!(d::OrderedRobinDict, newsz)
[ 173, 183 ]
function Base.sizehint!(d::OrderedRobinDict, newsz) oldsz = length(d) # grow at least 25% if newsz < (oldsz*5)>>2 return d end sizehint!(d.keys, newsz) sizehint!(d.vals, newsz) sizehint!(d.dict, newsz) return d end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 function Base.pop!(h::SwissDict, key) index = ht_keyindex(h, key) return index > 0 ? _pop!(h, index) : throw(KeyError(key)) end function Base.pop!(h::SwissDict, key, default) index = ht_keyindex(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::SwissDict) isempty(h) && throw(ArgumentError("SwissDict must be non-empty")) is = _iterslots(h, h.idxfloor) @assert is !== nothing idx, s = is @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] _delete!(h, idx) h.idxfloor = idx return key => val #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end ##CHUNK 2 index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end index = (index & (sz - 1)) + 1 end end """ get!(collection, key, default) Return the value stored for the given key, or if no mapping for the key is present, store `key => default`, and return `default`. ##CHUNK 3 index = rh_search(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::RobinDict) isempty(h) && throw(ArgumentError("dict must be non-empty")) idx = h.idxfloor @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] rh_delete!(h, idx) return key => val end """ delete!(collection, key) Delete the mapping for the given key in a collection, and return the collection. # Examples ```jldoctest #CURRENT FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 h.count -= 1 check_for_rehash(h) ? rehash!(h) : h end function get_first_filled_index(h::OrderedRobinDict) index = 1 while (true) isslotfilled(h, index) && return index index += 1 end end function get_next_filled_index(h::OrderedRobinDict, index) # get the next filled slot, including index and beyond while (index <= length(h.keys)) isslotfilled(h, index) && return index index += 1 end return -1 end ##CHUNK 2 "a" => 1 ``` """ function Base.delete!(h::OrderedRobinDict, key) pop!(h, key) return h end function _delete!(h::OrderedRobinDict, index) @inbounds h.dict[h.keys[index]] = -1 h.count -= 1 check_for_rehash(h) ? rehash!(h) : h end function get_first_filled_index(h::OrderedRobinDict) index = 1 while (true) isslotfilled(h, index) && return index index += 1 end ##CHUNK 3 end function get_next_filled_index(h::OrderedRobinDict, index) # get the next filled slot, including index and beyond while (index <= length(h.keys)) isslotfilled(h, index) && return index index += 1 end return -1 end Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict) isempty(h) && return nothing check_for_rehash(h) && rehash!(h) index = get_first_filled_index(h) return (Pair(h.keys[index], h.vals[index]), index+1) end Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict, i) length(h.keys) < i && return nothing ##CHUNK 4 Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict) isempty(h) && return nothing check_for_rehash(h) && rehash!(h) index = get_first_filled_index(h) return (Pair(h.keys[index], h.vals[index]), index+1) end Base.@propagate_inbounds function Base.iterate(h::OrderedRobinDict, i) length(h.keys) < i && return nothing index = get_next_filled_index(h, i) (index < 0) && return nothing return (Pair(h.keys[index], h.vals[index]), index+1) end Base.filter!(f, d::Union{RobinDict, OrderedRobinDict}) = Base.filter_in_one_pass!(f, d) function Base.merge(d::OrderedRobinDict, others::AbstractDict...) K,V = _merge_kvtypes(d, others...) merge!(OrderedRobinDict{K,V}(), d, others...) ##CHUNK 5 index = get(h.dict, key, -1) return (index < 0) ? default : h.keys[index]::K end Base.@propagate_inbounds isslotfilled(h::OrderedRobinDict, index) = (h.dict[h.keys[index]] == index) function _pop!(h::OrderedRobinDict, index) @inbounds val = h.vals[index] _delete!(h, index) return val end function Base.pop!(h::OrderedRobinDict, key) index = get(h.dict, key, -1) (index > 0) ? _pop!(h, index) : throw(KeyError(key)) end """ pop!(collection, key[, default]) ##CHUNK 6 @inbounds h.dict[key] = Int32(nk) h.count += 1 end function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h Based on the information above, please generate test code for the following function: function Base.pop!(h::OrderedRobinDict) check_for_rehash(h) && rehash!(h) index = length(h.keys) while (index > 0) isslotfilled(h, index) && break index -= 1 end index == 0 && rehash!(h) @inbounds key = h.keys[index] return key => _pop!(h, index) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "ordered_robin_dict.jl" ], "ground_truth": "function Base.pop!(h::OrderedRobinDict)\n check_for_rehash(h) && rehash!(h)\n index = length(h.keys)\n while (index > 0)\n isslotfilled(h, index) && break\n index -= 1\n end\n index == 0 && rehash!(h)\n @inbounds key = h.keys[index]\n return key => _pop!(h, index)\nend", "task_id": "DataStructures/36" }
343
353
DataStructures.jl
36
function Base.pop!(h::OrderedRobinDict) check_for_rehash(h) && rehash!(h) index = length(h.keys) while (index > 0) isslotfilled(h, index) && break index -= 1 end index == 0 && rehash!(h) @inbounds key = h.keys[index] return key => _pop!(h, index) end
Base.pop!(h::OrderedRobinDict)
[ 343, 353 ]
function Base.pop!(h::OrderedRobinDict) check_for_rehash(h) && rehash!(h) index = length(h.keys) while (index > 0) isslotfilled(h, index) && break index -= 1 end index == 0 && rehash!(h) @inbounds key = h.keys[index] return key => _pop!(h, index) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_priority_queue.jl ##CHUNK 1 end @testset "enqueing values via push!" begin pq = PriorityQueue() for (k, v) in priorities push!(pq, k=>v) end test_issorted!(pq, priorities) end @testset "enqueing via assign" begin pq = PriorityQueue() for (k, v) in priorities pq[k] = v end test_issorted!(pq, priorities) end @testset "changing priorities" begin pq = PriorityQueue() ##CHUNK 2 @testset "enqueing via assign" begin pq = PriorityQueue() for (k, v) in priorities pq[k] = v end test_issorted!(pq, priorities) end @testset "changing priorities" begin pq = PriorityQueue() for (k, v) in priorities pq[k] = v end for _ in 1:n k = rand(1:n) v = rand(1:pmax) pq[k] = v priorities[k] = v end ##CHUNK 3 end @test pq == pq2 end @testset "enqueing pairs via push!" begin pq = PriorityQueue() for kv in priorities push!(pq, kv) end test_issorted!(pq, priorities) end @testset "enqueing values via push!" begin pq = PriorityQueue() for (k, v) in priorities push!(pq, k=>v) end test_issorted!(pq, priorities) end ##CHUNK 4 for (k, v) in priorities pq[k] = v end for _ in 1:n k = rand(1:n) v = rand(1:pmax) pq[k] = v priorities[k] = v end test_issorted!(pq, priorities) end @testset "dequeuing" begin pq = PriorityQueue(priorities) @test_throws KeyError popat!(pq, 0) v, _ = popat!(pq, 10) @test v == 10 #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 function rehash!(h::OrderedRobinDict{K, V}) where {K, V} keys = h.keys vals = h.vals hk = Vector{K}() hv = Vector{V}() for (idx, (k, v)) in enumerate(zip(keys, vals)) if get(h.dict, k, -1) == idx push!(hk, k) push!(hv, v) end end h.keys = hk h.vals = hv for (idx, k) in enumerate(h.keys) h.dict[k] = idx end return h ##CHUNK 2 end # rehash when there are ALLOWABLE_USELESS_GROWTH % # tombstones, or non-mirrored entries in the dictionary function check_for_rehash(h::OrderedRobinDict) keysl = length(h.keys) dictl = length(h) return (keysl > (1 + ALLOWABLE_USELESS_GROWTH)*dictl) end function rehash!(h::OrderedRobinDict{K, V}) where {K, V} keys = h.keys vals = h.vals hk = Vector{K}() hv = Vector{V}() for (idx, (k, v)) in enumerate(zip(keys, vals)) if get(h.dict, k, -1) == idx push!(hk, k) push!(hv, v) #CURRENT FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 index::Dict{K, Int} function PriorityQueue{K,V,O}(o::O) where {K,V,O<:Ordering} new{K,V,O}(Vector{Pair{K,V}}(), o, Dict{K, Int}()) end PriorityQueue{K, V, O}(xs::Vector{Pair{K,V}}, o::O, index::Dict{K, Int}) where {K,V,O<:Ordering} = new(xs, o, index) end # A copy constructor PriorityQueue(xs::Vector{Pair{K,V}}, o::O, index::Dict{K, Int}) where {K,V,O<:Ordering} = PriorityQueue{K,V,O}(xs, o, index) # Any-Any constructors PriorityQueue(o::Ordering=Forward) = PriorityQueue{Any,Any,typeof(o)}(o) # Construction from Pairs PriorityQueue(ps::Pair...) = PriorityQueue(Forward, ps) PriorityQueue(o::Ordering, ps::Pair...) = PriorityQueue(o, ps) ##CHUNK 2 "a" => 1 "b" => 2 "c" => 3 "d" => 4 "e" => 5 ``` """ function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} key = pair.first if haskey(pq, key) throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end Base.push!(pq::PriorityQueue{K,V}, kv::Pair) where {K,V} = push!(pq, Pair{K,V}(kv.first, kv.second)) ##CHUNK 3 "a" => 2 "b" => 3 ``` """ struct PriorityQueue{K,V,O<:Ordering} <: AbstractDict{K,V} # Binary heap of (element, priority) pairs. xs::Vector{Pair{K,V}} o::O # Map elements to their index in xs index::Dict{K, Int} function PriorityQueue{K,V,O}(o::O) where {K,V,O<:Ordering} new{K,V,O}(Vector{Pair{K,V}}(), o, Dict{K, Int}()) end PriorityQueue{K, V, O}(xs::Vector{Pair{K,V}}, o::O, index::Dict{K, Int}) where {K,V,O<:Ordering} = new(xs, o, index) end ##CHUNK 4 throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end Base.push!(pq::PriorityQueue{K,V}, kv::Pair) where {K,V} = push!(pq, Pair{K,V}(kv.first, kv.second)) """ popfirst!(pq::PriorityQueue) Remove and return the lowest priority key and value from a priority queue `pq` as a pair. # Examples ```jldoctest julia> a = PriorityQueue(Base.Order.Forward, "a" => 2, "b" => 3, "c" => 1) Based on the information above, please generate test code for the following function: function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering} xs = Vector{Pair{K,V}}(undef, length(itr)) index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) # heapify for i in heapparent(length(pq.xs)):-1:1 percolate_down!(pq, i) end return pq end
{ "fpath_tuple": [ "DataStructures.jl", "src", "priorityqueue.jl" ], "ground_truth": "function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering}\n xs = Vector{Pair{K,V}}(undef, length(itr))\n index = Dict{K, Int}()\n for (i, (k, v)) in enumerate(itr)\n xs[i] = Pair{K,V}(k, v)\n if haskey(index, k)\n throw(ArgumentError(\"PriorityQueue keys must be unique\"))\n end\n index[k] = i\n end\n pq = new{K,V,O}(xs, o, index)\n\n # heapify\n for i in heapparent(length(pq.xs)):-1:1\n percolate_down!(pq, i)\n end\n\n return pq\n end", "task_id": "DataStructures/37" }
49
67
DataStructures.jl
37
function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering} xs = Vector{Pair{K,V}}(undef, length(itr)) index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) # heapify for i in heapparent(length(pq.xs)):-1:1 percolate_down!(pq, i) end return pq end
PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering}
[ 49, 67 ]
function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering} xs = Vector{Pair{K,V}}(undef, length(itr)) index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) # heapify for i in heapparent(length(pq.xs)):-1:1 percolate_down!(pq, i) end return pq end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.delete!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) if index > 0 rh_delete!(h, index) end return h end function get_next_filled(h::RobinDict, i) L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end function Base.getindex(h::SwissDict{K,V}, key) where {K, V} index = ht_keyindex(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index]::V end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. # Examples ##CHUNK 2 index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end function Base.getindex(h::SwissDict{K,V}, key) where {K, V} index = ht_keyindex(h, key) #CURRENT FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j end pq.index[x.first] = i pq.xs[i] = x end Base.getindex(pq::PriorityQueue, key) = pq.xs[pq.index[key]].second function Base.get(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) i == 0 ? default : pq.xs[i].second end function Base.get!(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) if i == 0 push!(pq, key=>default) return default ##CHUNK 2 function Base.get(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) i == 0 ? default : pq.xs[i].second end function Base.get!(pq::PriorityQueue, key, default) i = get(pq.index, key, 0) if i == 0 push!(pq, key=>default) return default else return pq.xs[i].second end end # Change the priority of an existing element, or enqueue it if it isn't present. """ push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} ##CHUNK 3 break end end pq.index[x.first] = i pq.xs[i] = x end function percolate_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) xj = pq.xs[j] if lt(pq.o, x.second, xj.second) pq.index[xj.first] = i pq.xs[i] = xj i = j else break end ##CHUNK 4 x = pq.xs[i] @inbounds while (l = heapleft(i)) <= length(pq) r = heapright(i) j = r > length(pq) || lt(pq.o, pq.xs[l].second, pq.xs[r].second) ? l : r xj = pq.xs[j] if lt(pq.o, xj.second, x.second) pq.index[xj.first] = i pq.xs[i] = xj i = j else break end end pq.index[x.first] = i pq.xs[i] = x end function percolate_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] ##CHUNK 5 @inbounds while i > 1 j = heapparent(i) xj = pq.xs[j] if lt(pq.o, x.second, xj.second) pq.index[xj.first] = i pq.xs[i] = xj i = j else break end end pq.index[x.first] = i pq.xs[i] = x end # Equivalent to percolate_up! with an element having lower priority than any other function force_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) ##CHUNK 6 """ function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} key = pair.first if haskey(pq, key) throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end Base.push!(pq::PriorityQueue{K,V}, kv::Pair) where {K,V} = push!(pq, Pair{K,V}(kv.first, kv.second)) """ popfirst!(pq::PriorityQueue) Remove and return the lowest priority key and value from a priority queue `pq` as a pair. ##CHUNK 7 end pq.index[x.first] = i pq.xs[i] = x end # Equivalent to percolate_up! with an element having lower priority than any other function force_up!(pq::PriorityQueue, i::Integer) x = pq.xs[i] @inbounds while i > 1 j = heapparent(i) pq.index[pq.xs[j].first] = i pq.xs[i] = pq.xs[j] i = j end pq.index[x.first] = i pq.xs[i] = x end Base.getindex(pq::PriorityQueue, key) = pq.xs[pq.index[key]].second Based on the information above, please generate test code for the following function: function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) else percolate_up!(pq, i) end else push!(pq, key=>value) end return value end
{ "fpath_tuple": [ "DataStructures.jl", "src", "priorityqueue.jl" ], "ground_truth": "function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V}\n i = get(pq.index, key, 0)\n if i != 0\n @inbounds oldvalue = pq.xs[i].second\n pq.xs[i] = Pair{K,V}(key, value)\n if lt(pq.o, oldvalue, value)\n percolate_down!(pq, i)\n else\n percolate_up!(pq, i)\n end\n else\n push!(pq, key=>value)\n end\n return value\nend", "task_id": "DataStructures/38" }
237
251
DataStructures.jl
38
function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) else percolate_up!(pq, i) end else push!(pq, key=>value) end return value end
Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V}
[ 237, 251 ]
function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) else percolate_up!(pq, i) end else push!(pq, key=>value) end return value end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/trie.jl ##CHUNK 1 end return t end end Trie() = Trie{Any,Any}() Trie(ks::AbstractVector{K}, vs::AbstractVector{V}) where {K,V} = Trie{eltype(K),V}(ks, vs) Trie(kv::AbstractVector{Tuple{K,V}}) where {K,V} = Trie{eltype(K),V}(kv) Trie(kv::AbstractDict{K,V}) where {K,V} = Trie{eltype(K),V}(kv) Trie(ks::AbstractVector{K}) where {K} = Trie{eltype(K),Nothing}(ks, similar(ks, Nothing)) function Base.setindex!(t::Trie{K,V}, val, key) where {K,V} value = convert(V, val) # we don't want to iterate before finding out it fails node = t for char in key node = get!(Trie{K,V}, node.children, char) end node.is_key = true node.value = value end ##CHUNK 2 function Base.setindex!(t::Trie{K,V}, val, key) where {K,V} value = convert(V, val) # we don't want to iterate before finding out it fails node = t for char in key node = get!(Trie{K,V}, node.children, char) end node.is_key = true node.value = value end function Base.getindex(t::Trie, key) node = subtrie(t, key) if node != nothing && node.is_key return node.value end throw(KeyError("key not found: $key")) end function subtrie(t::Trie, prefix) #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 index = rh_search(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::RobinDict) isempty(h) && throw(ArgumentError("dict must be non-empty")) idx = h.idxfloor @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] rh_delete!(h, idx) return key => val end """ delete!(collection, key) Delete the mapping for the given key in a collection, and return the collection. # Examples ```jldoctest #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 function Base.pop!(h::SwissDict, key) index = ht_keyindex(h, key) return index > 0 ? _pop!(h, index) : throw(KeyError(key)) end function Base.pop!(h::SwissDict, key, default) index = ht_keyindex(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::SwissDict) isempty(h) && throw(ArgumentError("SwissDict must be non-empty")) is = _iterslots(h, h.idxfloor) @assert is !== nothing idx, s = is @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] _delete!(h, idx) h.idxfloor = idx return key => val ##CHUNK 2 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end # get the index where a key is stored, or -pos if not present # and the key would be inserted at pos # This version is for use by setindex! and get!. It never rehashes. ht_keyindex2!(h::SwissDict, key) = ht_keyindex2!(h, key, _hashtag(hash(key))...) @inline function ht_keyindex2!(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) #CURRENT FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) # heapify for i in heapparent(length(pq.xs)):-1:1 percolate_down!(pq, i) end return pq end end # A copy constructor ##CHUNK 2 index::Dict{K, Int} function PriorityQueue{K,V,O}(o::O) where {K,V,O<:Ordering} new{K,V,O}(Vector{Pair{K,V}}(), o, Dict{K, Int}()) end PriorityQueue{K, V, O}(xs::Vector{Pair{K,V}}, o::O, index::Dict{K, Int}) where {K,V,O<:Ordering} = new(xs, o, index) function PriorityQueue{K,V,O}(o::O, itr) where {K,V,O<:Ordering} xs = Vector{Pair{K,V}}(undef, length(itr)) index = Dict{K, Int}() for (i, (k, v)) in enumerate(itr) xs[i] = Pair{K,V}(k, v) if haskey(index, k) throw(ArgumentError("PriorityQueue keys must be unique")) end index[k] = i end pq = new{K,V,O}(xs, o, index) ##CHUNK 3 pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) else percolate_up!(pq, i) end else push!(pq, key=>value) end return value end """ push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} Insert the a key `k` into a priority queue `pq` with priority `v`. # Examples ```jldoctest ##CHUNK 4 else return pq.xs[i].second end end # Change the priority of an existing element, or enqueue it if it isn't present. function Base.setindex!(pq::PriorityQueue{K, V}, value, key) where {K,V} i = get(pq.index, key, 0) if i != 0 @inbounds oldvalue = pq.xs[i].second pq.xs[i] = Pair{K,V}(key, value) if lt(pq.o, oldvalue, value) percolate_down!(pq, i) else percolate_up!(pq, i) end else push!(pq, key=>value) end return value ##CHUNK 5 ``` """ function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end function Base.popat!(pq::PriorityQueue, key) idx = pq.index[key] force_up!(pq, idx) popfirst!(pq) end Based on the information above, please generate test code for the following function: function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} key = pair.first if haskey(pq, key) throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end
{ "fpath_tuple": [ "DataStructures.jl", "src", "priorityqueue.jl" ], "ground_truth": "function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V}\n key = pair.first\n if haskey(pq, key)\n throw(ArgumentError(\"PriorityQueue keys must be unique\"))\n end\n push!(pq.xs, pair)\n pq.index[key] = length(pq)\n percolate_up!(pq, length(pq))\n\n return pq\nend", "task_id": "DataStructures/39" }
277
287
DataStructures.jl
39
function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} key = pair.first if haskey(pq, key) throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end
Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V}
[ 277, 287 ]
function Base.push!(pq::PriorityQueue{K,V}, pair::Pair{K,V}) where {K,V} key = pair.first if haskey(pq, key) throw(ArgumentError("PriorityQueue keys must be unique")) end push!(pq.xs, pair) pq.index[key] = length(pq) percolate_up!(pq, length(pq)) return pq end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 """ popmin!(h::BinaryMinMaxHeap) -> min Remove the minimum value from the heap. """ function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end """ ##CHUNK 2 y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end """ popmin!(h::BinaryMinMaxHeap, k::Integer) -> vals Remove up to the `k` smallest values from the heap. """ @inline function popmin!(h::BinaryMinMaxHeap, k::Integer) return [popmin!(h) for _ in 1:min(length(h), k)] end """ popmax!(h::BinaryMinMaxHeap) -> max ##CHUNK 3 Remove the maximum value from the heap. """ function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) end return x end """ popmax!(h::BinaryMinMaxHeap, k::Integer) -> vals Remove up to the `k` largest values from the heap. """ #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 2 return tree end function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end ##CHUNK 2 x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end ##CHUNK 3 node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color #FILE: DataStructures.jl/src/disjoint_set.jl ##CHUNK 1 Assume `x ≠ y` (unsafe). """ function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents rks = s.ranks @inbounds xrank = rks[x] @inbounds yrank = rks[y] if xrank < yrank x, y = y, x elseif xrank == yrank rks[x] += one(T) end @inbounds parents[y] = x s.ngroups -= one(T) return x end """ push!(s::IntDisjointSet{T}) #FILE: DataStructures.jl/test/bench_disjoint_set.jl ##CHUNK 1 function batch_union!(s::IntDisjointSets, x::Vector{Int}, y::Vector{Int}) for i = 1 : length(x) @inbounds union!(s, x[i], y[i]) end end s = IntDisjointSets(n) # warming x0 = rand(1:n, T0) y0 = rand(1:n, T0) batch_union!(s, x0, y0) # measure x = rand(1:n, T) y = rand(1:n, T) #CURRENT FILE: DataStructures.jl/src/priorityqueue.jl Based on the information above, please generate test code for the following function: function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "priorityqueue.jl" ], "ground_truth": "function Base.popfirst!(pq::PriorityQueue)\n x = pq.xs[1]\n y = pop!(pq.xs)\n if !isempty(pq)\n @inbounds pq.xs[1] = y\n pq.index[y.first] = 1\n percolate_down!(pq, 1)\n end\n delete!(pq.index, x.first)\n return x\nend", "task_id": "DataStructures/40" }
314
324
DataStructures.jl
40
function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end
Base.popfirst!(pq::PriorityQueue)
[ 314, 324 ]
function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 2 """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data ##CHUNK 3 julia> for k in 1:2:20 push!(tree, k) end julia> sorted_rank(tree, 17) 9 ``` """ function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end ##CHUNK 4 !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end end rank += (1 + get_subsize(node.leftChild)) return rank end """ getindex(tree::AVLTree{K}, ind::Integer) where K Considering the elements of `tree` sorted, returns the `ind`-th element in `tree`. Search operation is performed in \$O(\\log n)\$ time complexity. #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 2 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 3 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node #CURRENT FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 end return node end """ delete!(tree::RBTree, key) Deletes `key` from `tree`, if present, else returns the unmodified tree. """ function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild ##CHUNK 2 z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() ##CHUNK 3 node_y = nothing node_x = tree.root while node_x !== tree.nil node_y = node_x if node.data < node_x.data node_x = node_x.leftChild else node_x = node_x.rightChild end end node.parent = node_y if node_y == nothing tree.root = node elseif node.data < node_y.data node_y.leftChild = node else node_y.rightChild = node end Based on the information above, please generate test code for the following function: function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end
{ "fpath_tuple": [ "DataStructures.jl", "src", "red_black_tree.jl" ], "ground_truth": "function search_node(tree::RBTree{K}, d::K) where K\n node = tree.root\n while node !== tree.nil && d != node.data\n if d < node.data\n node = node.leftChild\n else\n node = node.rightChild\n end\n end\n return node\nend", "task_id": "DataStructures/41" }
54
64
DataStructures.jl
41
function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end
search_node(tree::RBTree{K}, d::K) where K
[ 54, 64 ]
function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 if balance < -1 if key > node.rightChild.data return left_rotate(node) else node.rightChild = right_rotate(node.rightChild) return left_rotate(node) end end return node end function Base.insert!(tree::AVLTree{K}, d::K) where K haskey(tree, d) && return tree tree.root = insert_node(tree.root, d) tree.count += 1 return tree end ##CHUNK 2 return node end function Base.insert!(tree::AVLTree{K}, d::K) where K haskey(tree, d) && return tree tree.root = insert_node(tree.root, d) tree.count += 1 return tree end """ push!(tree::AVLTree{K}, key) where K Insert `key` in AVL tree `tree`. """ function Base.push!(tree::AVLTree{K}, key) where K key0 = convert(K, key) insert!(tree, key0) end ##CHUNK 3 end return node end """ delete!(tree::AVLTree{K}, k::K) where K Delete key `k` from `tree` AVL tree. """ function Base.delete!(tree::AVLTree{K}, k::K) where K # if the key is not in the tree, do nothing and return the tree !haskey(tree, k) && return tree # if the key is present, delete it from the tree tree.root = delete_node!(tree.root, k) tree.count -= 1 return tree end ##CHUNK 4 function Base.delete!(tree::AVLTree{K}, k::K) where K # if the key is not in the tree, do nothing and return the tree !haskey(tree, k) && return tree # if the key is present, delete it from the tree tree.root = delete_node!(tree.root, k) tree.count -= 1 return tree end """ sorted_rank(tree::AVLTree{K}, key::K) where K Returns the rank of `key` present in the `tree`, if it present. A `KeyError` is thrown if `key` is not present. # Examples ```jldoctest julia> tree = AVLTree{Int}(); #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end ##CHUNK 2 end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) ##CHUNK 3 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) ##CHUNK 4 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) #CURRENT FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 2 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ Based on the information above, please generate test code for the following function: function Base.insert!(tree::RBTree{K}, d::K) where K # if the key exists in the tree, no need to insert haskey(tree, d) && return tree # insert, if not present in the tree node = RBTreeNode{K}(d) node.leftChild = node.rightChild = tree.nil insert_node!(tree, node) if node.parent == nothing node.color = false elseif node.parent.parent == nothing ; else fix_insert!(tree, node) end tree.count += 1 return tree end
{ "fpath_tuple": [ "DataStructures.jl", "src", "red_black_tree.jl" ], "ground_truth": "function Base.insert!(tree::RBTree{K}, d::K) where K\n # if the key exists in the tree, no need to insert\n haskey(tree, d) && return tree\n\n # insert, if not present in the tree\n node = RBTreeNode{K}(d)\n node.leftChild = node.rightChild = tree.nil\n\n insert_node!(tree, node)\n\n if node.parent == nothing\n node.color = false\n elseif node.parent.parent == nothing\n ;\n else\n fix_insert!(tree, node)\n end\n tree.count += 1\n return tree\nend", "task_id": "DataStructures/42" }
211
230
DataStructures.jl
42
function Base.insert!(tree::RBTree{K}, d::K) where K # if the key exists in the tree, no need to insert haskey(tree, d) && return tree # insert, if not present in the tree node = RBTreeNode{K}(d) node.leftChild = node.rightChild = tree.nil insert_node!(tree, node) if node.parent == nothing node.color = false elseif node.parent.parent == nothing ; else fix_insert!(tree, node) end tree.count += 1 return tree end
Base.insert!(tree::RBTree{K}, d::K) where K
[ 211, 230 ]
function Base.insert!(tree::RBTree{K}, d::K) where K # if the key exists in the tree, no need to insert haskey(tree, d) && return tree # insert, if not present in the tree node = RBTreeNode{K}(d) node.leftChild = node.rightChild = tree.nil insert_node!(tree, node) if node.parent == nothing node.color = false elseif node.parent.parent == nothing ; else fix_insert!(tree, node) end tree.count += 1 return tree end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 2 end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) ##CHUNK 3 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 4 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ #CURRENT FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 while node != tree.root && node.parent.color parent = node.parent grand_parent = parent.parent if (parent == grand_parent.leftChild) # parent is the leftChild of grand_parent uncle = grand_parent.rightChild if (uncle.color) # uncle is red in color grand_parent.color = true parent.color = false uncle.color = false node = grand_parent else # uncle is black in color if (node == parent.rightChild) # node is rightChild of its parent node = parent left_rotate!(tree, node) end # node is leftChild of its parent node.parent.color = false node.parent.parent.color = true ##CHUNK 2 right_rotate!(tree, node.parent.parent) end else # parent is the rightChild of grand_parent uncle = grand_parent.leftChild if (uncle.color) # uncle is red in color grand_parent.color = true parent.color = false uncle.color = false node = grand_parent else # uncle is black in color if (node == parent.leftChild) # node is leftChild of its parent node = parent right_rotate!(tree, node) end # node is rightChild of its parent node.parent.color = false node.parent.parent.color = true left_rotate!(tree, node.parent.parent) end ##CHUNK 3 uncle.color = false node = grand_parent else # uncle is black in color if (node == parent.rightChild) # node is rightChild of its parent node = parent left_rotate!(tree, node) end # node is leftChild of its parent node.parent.color = false node.parent.parent.color = true right_rotate!(tree, node.parent.parent) end else # parent is the rightChild of grand_parent uncle = grand_parent.leftChild if (uncle.color) # uncle is red in color grand_parent.color = true parent.color = false uncle.color = false node = grand_parent ##CHUNK 4 else # uncle is black in color if (node == parent.leftChild) # node is leftChild of its parent node = parent right_rotate!(tree, node) end # node is rightChild of its parent node.parent.color = false node.parent.parent.color = true left_rotate!(tree, node.parent.parent) end end end tree.root.color = false end """ insert!(tree, key) Inserts `key` in the `tree` if it is not present. """ ##CHUNK 5 function insert_node!(tree::RBTree, node::RBTreeNode) node_y = nothing node_x = tree.root while node_x !== tree.nil node_y = node_x if node.data < node_x.data node_x = node_x.leftChild else node_x = node_x.rightChild end end node.parent = node_y if node_y == nothing tree.root = node elseif node.data < node_y.data node_y.leftChild = node else node_y.rightChild = node Based on the information above, please generate test code for the following function: function delete_fix(tree::RBTree, node::Union{RBTreeNode, Nothing}) while node != tree.root && !node.color if node == node.parent.leftChild sibling = node.parent.rightChild if sibling.color sibling.color = false node.parent.color = true left_rotate!(tree, node.parent) sibling = node.parent.rightChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.rightChild.color sibling.leftChild.color = false sibling.color = true right_rotate!(tree, sibling) sibling = node.parent.rightChild end sibling.color = node.parent.color node.parent.color = false sibling.rightChild.color = false left_rotate!(tree, node.parent) node = tree.root end else sibling = node.parent.leftChild if sibling.color sibling.color = false node.parent.color = true right_rotate!(tree, node.parent) sibling = node.parent.leftChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.leftChild.color sibling.rightChild.color = false sibling.color = true left_rotate!(tree, sibling) sibling = node.parent.leftChild end sibling.color = node.parent.color node.parent.color = false sibling.leftChild.color = false right_rotate!(tree, node.parent) node = tree.root end end end node.color = false return nothing end
{ "fpath_tuple": [ "DataStructures.jl", "src", "red_black_tree.jl" ], "ground_truth": "function delete_fix(tree::RBTree, node::Union{RBTreeNode, Nothing})\n while node != tree.root && !node.color\n if node == node.parent.leftChild\n sibling = node.parent.rightChild\n if sibling.color\n sibling.color = false\n node.parent.color = true\n left_rotate!(tree, node.parent)\n sibling = node.parent.rightChild\n end\n\n if !sibling.rightChild.color && !sibling.leftChild.color\n sibling.color = true\n node = node.parent\n else\n if !sibling.rightChild.color\n sibling.leftChild.color = false\n sibling.color = true\n right_rotate!(tree, sibling)\n sibling = node.parent.rightChild\n end\n\n sibling.color = node.parent.color\n node.parent.color = false\n sibling.rightChild.color = false\n left_rotate!(tree, node.parent)\n node = tree.root\n end\n else\n sibling = node.parent.leftChild\n if sibling.color\n sibling.color = false\n node.parent.color = true\n right_rotate!(tree, node.parent)\n sibling = node.parent.leftChild\n end\n\n if !sibling.rightChild.color && !sibling.leftChild.color\n sibling.color = true\n node = node.parent\n else\n if !sibling.leftChild.color\n sibling.rightChild.color = false\n sibling.color = true\n left_rotate!(tree, sibling)\n sibling = node.parent.leftChild\n end\n\n sibling.color = node.parent.color\n node.parent.color = false\n sibling.leftChild.color = false\n right_rotate!(tree, node.parent)\n node = tree.root\n end\n end\n end\n node.color = false\n return nothing\nend", "task_id": "DataStructures/43" }
247
305
DataStructures.jl
43
function delete_fix(tree::RBTree, node::Union{RBTreeNode, Nothing}) while node != tree.root && !node.color if node == node.parent.leftChild sibling = node.parent.rightChild if sibling.color sibling.color = false node.parent.color = true left_rotate!(tree, node.parent) sibling = node.parent.rightChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.rightChild.color sibling.leftChild.color = false sibling.color = true right_rotate!(tree, sibling) sibling = node.parent.rightChild end sibling.color = node.parent.color node.parent.color = false sibling.rightChild.color = false left_rotate!(tree, node.parent) node = tree.root end else sibling = node.parent.leftChild if sibling.color sibling.color = false node.parent.color = true right_rotate!(tree, node.parent) sibling = node.parent.leftChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.leftChild.color sibling.rightChild.color = false sibling.color = true left_rotate!(tree, sibling) sibling = node.parent.leftChild end sibling.color = node.parent.color node.parent.color = false sibling.leftChild.color = false right_rotate!(tree, node.parent) node = tree.root end end end node.color = false return nothing end
delete_fix(tree::RBTree, node::Union{RBTreeNode, Nothing})
[ 247, 305 ]
function delete_fix(tree::RBTree, node::Union{RBTreeNode, Nothing}) while node != tree.root && !node.color if node == node.parent.leftChild sibling = node.parent.rightChild if sibling.color sibling.color = false node.parent.color = true left_rotate!(tree, node.parent) sibling = node.parent.rightChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.rightChild.color sibling.leftChild.color = false sibling.color = true right_rotate!(tree, sibling) sibling = node.parent.rightChild end sibling.color = node.parent.color node.parent.color = false sibling.rightChild.color = false left_rotate!(tree, node.parent) node = tree.root end else sibling = node.parent.leftChild if sibling.color sibling.color = false node.parent.color = true right_rotate!(tree, node.parent) sibling = node.parent.leftChild end if !sibling.rightChild.color && !sibling.leftChild.color sibling.color = true node = node.parent else if !sibling.leftChild.color sibling.rightChild.color = false sibling.color = true left_rotate!(tree, sibling) sibling = node.parent.leftChild end sibling.color = node.parent.color node.parent.color = false sibling.leftChild.color = false right_rotate!(tree, node.parent) node = tree.root end end end node.color = false return nothing end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 2 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) ##CHUNK 3 return tree end function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild ##CHUNK 4 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 5 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end ##CHUNK 2 y.subsize = compute_subtree_size(y) return y end """ right_rotate(node_x::AVLTreeNode) Performs a right-rotation on `node_x`, updates height of the nodes, and returns the rotated node. """ function right_rotate(z::AVLTreeNode) y = z.leftChild α = y.rightChild y.rightChild = z z.leftChild = α z.height = compute_height(z) y.height = compute_height(y) z.subsize = compute_subtree_size(z) y.subsize = compute_subtree_size(y) return y end ##CHUNK 3 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ #CURRENT FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 end RBTree() = RBTree{Any}() Base.length(tree::RBTree) = tree.count """ search_node(tree, key) Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`. """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild Based on the information above, please generate test code for the following function: function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end
{ "fpath_tuple": [ "DataStructures.jl", "src", "red_black_tree.jl" ], "ground_truth": "function Base.delete!(tree::RBTree{K}, d::K) where K\n z = tree.nil\n node = tree.root\n\n while node !== tree.nil\n if node.data == d\n z = node\n end\n\n if d < node.data\n node = node.leftChild\n else\n node = node.rightChild\n end\n end\n\n (z === tree.nil) && return tree\n\n y = z\n y_original_color = y.color\n x = RBTreeNode{K}()\n if z.leftChild === tree.nil\n x = z.rightChild\n rb_transplant(tree, z, z.rightChild)\n elseif z.rightChild === tree.nil\n x = z.leftChild\n rb_transplant(tree, z, z.leftChild)\n else\n y = minimum_node(tree, z.rightChild)\n y_original_color = y.color\n x = y.rightChild\n\n if y.parent == z\n x.parent = y\n else\n rb_transplant(tree, y, y.rightChild)\n y.rightChild = z.rightChild\n y.rightChild.parent = y\n end\n\n rb_transplant(tree, z, y)\n y.leftChild = z.leftChild\n y.leftChild.parent = y\n y.color = z.color\n end\n\n !y_original_color && delete_fix(tree, x)\n tree.count -= 1\n return tree\nend", "task_id": "DataStructures/44" }
341
390
DataStructures.jl
44
function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end
Base.delete!(tree::RBTree{K}, d::K) where K
[ 341, 390 ]
function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end ##CHUNK 2 end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 julia> tree[4] 7 julia> tree[8] 15 ``` """ function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end ##CHUNK 2 # Examples ```jldoctest julia> tree = AVLTree{Int}() AVLTree{Int64}(nothing, 0) julia> for k in 1:2:20 push!(tree, k) end julia> tree[4] 7 julia> tree[8] 15 ``` """ function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 sum += ft.bi_tree[i] i -= i&(-i) end sum end Base.getindex(ft::FenwickTree{T}, ind::Integer) where T = prefixsum(ft, ind) ##CHUNK 2 """ inc!(ft::FenwickTree{T}, ind::Integer, val) Increases the value of the [`FenwickTree`] by `val` from the index `ind` upto the length of the Fenwick Tree. """ function inc!(ft::FenwickTree{T}, ind::Integer, val = 1) where T val0 = convert(T, val) i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i <= n ft.bi_tree[i] += val0 i += i&(-i) end end """ dec!(ft::FenwickTree, ind::Integer, val) ##CHUNK 3 Return the cumulative sum from index 1 upto `ind` of the [`FenwickTree`](@ref) # Examples ``` julia> f = FenwickTree{Int}(6) julia> inc!(f, 2, 5) julia> prefixsum(f, 1) 0 julia> prefixsum(f, 3) 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end Base.@propagate_inbounds _iterate(t::RobinDict{K,V}, i) where {K,V} = i == 0 ? nothing : (Pair{K,V}(t.keys[i],t.vals[i]), i == typemax(Int) ? 0 : get_next_filled(t, i+1)) Base.@propagate_inbounds function Base.iterate(t::RobinDict) _iterate(t, t.idxfloor) end Base.@propagate_inbounds Base.iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i)) function _merge_kvtypes(d, others...) K, V = keytype(d), valtype(d) for other in others K = promote_type(K, keytype(other)) ##CHUNK 2 function Base.delete!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) if index > 0 rh_delete!(h, index) end return h end function get_next_filled(h::RobinDict, i) L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end #CURRENT FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color Based on the information above, please generate test code for the following function: function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
{ "fpath_tuple": [ "DataStructures.jl", "src", "red_black_tree.jl" ], "ground_truth": "function Base.getindex(tree::RBTree{K}, ind) where K\n @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError(\"$ind should be in between 1 and $(tree.count)\"))\n function traverse_tree_inorder(node::RBTreeNode{K}) where K\n if (node !== tree.nil)\n left = traverse_tree_inorder(node.leftChild)\n right = traverse_tree_inorder(node.rightChild)\n append!(push!(left, node.data), right)\n else\n return K[]\n end\n end\n arr = traverse_tree_inorder(tree.root)\n return @inbounds arr[ind]\nend", "task_id": "DataStructures/45" }
399
412
DataStructures.jl
45
function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
Base.getindex(tree::RBTree{K}, ind) where K
[ 399, 412 ]
function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 # Functions which are not exported, but are required for checking invariants hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end function get_idxfloor(h::RobinDict) @inbounds for i = 1:length(h.keys) if isslotfilled(h, i) return i end end return 0 #CURRENT FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h_new, index_curr)) break end probe_distance = calculate_distance(h_new, index_curr) if probe_current > probe_distance h_new.vals[index_curr], cval = cval, h_new.vals[index_curr] h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr] h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr] probe_current = probe_distance end ##CHUNK 2 break end probe_distance = calculate_distance(h_new, index_curr) if probe_current > probe_distance h_new.vals[index_curr], cval = cval, h_new.vals[index_curr] h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr] h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotempty(h_new, index_curr) h_new.count += 1 end @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey ##CHUNK 3 sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h_new, index_curr)) ##CHUNK 4 probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotempty(h_new, index_curr) h_new.count += 1 end @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr ##CHUNK 5 @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 ##CHUNK 6 h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end index = (index & (sz - 1)) + 1 end ##CHUNK 7 rethrow(e) end end end hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ##CHUNK 8 """ function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 ##CHUNK 9 index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] curr = next next = (next & (sz-1)) + 1 Based on the information above, please generate test code for the following function: function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end
{ "fpath_tuple": [ "DataStructures.jl", "src", "robin_dict.jl" ], "ground_truth": "function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V}\n sz = length(h.keys)\n (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2)\n\n # table full\n @assert h.count != length(h.keys)\n\n ckey, cval, chash = key, val, hash_key(key)\n sz = length(h.keys)\n index_init = desired_index(chash, sz)\n\n index_curr = index_init\n probe_distance = 0\n probe_current = 0\n @inbounds while true\n if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey))\n break\n end\n probe_distance = calculate_distance(h, index_curr)\n\n if probe_current > probe_distance\n h.vals[index_curr], cval = cval, h.vals[index_curr]\n h.keys[index_curr], ckey = ckey, h.keys[index_curr]\n h.hashes[index_curr], chash = chash, h.hashes[index_curr]\n probe_current = probe_distance\n end\n probe_current += 1\n index_curr = (index_curr & (sz - 1)) + 1\n end\n\n @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)\n h.vals[index_curr] = cval\n return index_curr\n end\n\n @inbounds if isslotempty(h, index_curr)\n h.count += 1\n end\n\n @inbounds h.vals[index_curr] = cval\n @inbounds h.keys[index_curr] = ckey\n @inbounds h.hashes[index_curr] = chash\n\n @assert probe_current >= 0\n\n if h.idxfloor == 0\n h.idxfloor = index_curr\n else\n h.idxfloor = min(h.idxfloor, index_curr)\n end\n return index_curr\nend", "task_id": "DataStructures/46" }
97
148
DataStructures.jl
46
function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end
rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V}
[ 97, 148 ]
function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 # Functions which are not exported, but are required for checking invariants hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end function get_idxfloor(h::RobinDict) @inbounds for i = 1:length(h.keys) if isslotfilled(h, i) return i end end return 0 #CURRENT FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] ##CHUNK 2 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end ##CHUNK 3 probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 ##CHUNK 4 sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 ##CHUNK 5 @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end ##CHUNK 6 rethrow(e) end end end hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) ##CHUNK 7 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end index = (index & (sz - 1)) + 1 end end ##CHUNK 8 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) ##CHUNK 9 sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) Based on the information above, please generate test code for the following function: function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h_new, index_curr)) break end probe_distance = calculate_distance(h_new, index_curr) if probe_current > probe_distance h_new.vals[index_curr], cval = cval, h_new.vals[index_curr] h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr] h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotempty(h_new, index_curr) h_new.count += 1 end @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr end
{ "fpath_tuple": [ "DataStructures.jl", "src", "robin_dict.jl" ], "ground_truth": "function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V}\n # table full\n @assert h_new.count != length(h_new.keys)\n\n ckey, cval, chash = key, val, hash\n sz = length(h_new.keys)\n index_init = desired_index(chash, sz)\n\n index_curr = index_init\n probe_distance = 0\n probe_current = 0\n @inbounds while true\n if (isslotempty(h_new, index_curr))\n break\n end\n probe_distance = calculate_distance(h_new, index_curr)\n\n if probe_current > probe_distance\n h_new.vals[index_curr], cval = cval, h_new.vals[index_curr]\n h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr]\n h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr]\n probe_current = probe_distance\n end\n probe_current += 1\n index_curr = (index_curr & (sz - 1)) + 1\n end\n\n @inbounds if isslotempty(h_new, index_curr)\n h_new.count += 1\n end\n\n @inbounds h_new.vals[index_curr] = cval\n @inbounds h_new.keys[index_curr] = ckey\n @inbounds h_new.hashes[index_curr] = chash\n\n @assert probe_current >= 0\n\n if h_new.idxfloor == 0\n h_new.idxfloor = index_curr\n else\n h_new.idxfloor = min(h_new.idxfloor, index_curr)\n end\n return index_curr\nend", "task_id": "DataStructures/47" }
150
193
DataStructures.jl
47
function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h_new, index_curr)) break end probe_distance = calculate_distance(h_new, index_curr) if probe_current > probe_distance h_new.vals[index_curr], cval = cval, h_new.vals[index_curr] h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr] h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotempty(h_new, index_curr) h_new.count += 1 end @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr end
rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V}
[ 150, 193 ]
function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 @inbounds while true if (isslotempty(h_new, index_curr)) break end probe_distance = calculate_distance(h_new, index_curr) if probe_current > probe_distance h_new.vals[index_curr], cval = cval, h_new.vals[index_curr] h_new.keys[index_curr], ckey = ckey, h_new.keys[index_curr] h_new.hashes[index_curr], chash = chash, h_new.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotempty(h_new, index_curr) h_new.count += 1 end @inbounds h_new.vals[index_curr] = cval @inbounds h_new.keys[index_curr] = ckey @inbounds h_new.hashes[index_curr] = chash @assert probe_current >= 0 if h_new.idxfloor == 0 h_new.idxfloor = index_curr else h_new.idxfloor = min(h_new.idxfloor, index_curr) end return index_curr end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) ##CHUNK 2 sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) ##CHUNK 3 sz = length(h.keys) if h.count*4 < sz && sz > 16 rehash!(h, sz>>1) end end function Base.sizehint!(d::SwissDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals ##CHUNK 4 h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] ##CHUNK 5 vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull @assert h.age == age0 @assert h.count == count return h end Base.isempty(t::SwissDict) = (t.count == 0) Base.length(t::SwissDict) = t.count ##CHUNK 6 fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) ##CHUNK 7 cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 end end h.keys = hk h.vals = hv for (idx, k) in enumerate(h.keys) h.dict[k] = idx end return h end function Base.sizehint!(d::OrderedRobinDict, newsz::Integer) oldsz = length(d) # grow at least 25% if newsz < (oldsz*5)>>2 return d end sizehint!(d.keys, newsz) sizehint!(d.vals, newsz) #CURRENT FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 ``` """ function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) ##CHUNK 2 fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end index = (index & (sz - 1)) + 1 Based on the information above, please generate test code for the following function: function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "robin_dict.jl" ], "ground_truth": "function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V}\n oldk = h.keys\n oldv = h.vals\n oldh = h.hashes\n sz = length(oldk)\n newsz = _tablesz(newsz)\n if h.count == 0\n resize!(h.keys, newsz)\n resize!(h.vals, newsz)\n resize!(h.hashes, newsz)\n fill!(h.hashes, 0)\n h.count = 0\n h.idxfloor = 0\n return h\n end\n\n h.keys = Vector{K}(undef, newsz)\n h.vals = Vector{V}(undef, newsz)\n h.hashes = zeros(UInt32,newsz)\n h.count = 0\n h.idxfloor = 0\n\n for i = 1:sz\n @inbounds if oldh[i] != 0\n k = oldk[i]\n v = oldv[i]\n rh_insert_for_rehash!(h, k, v, oldh[i])\n end\n end\n return h\nend", "task_id": "DataStructures/48" }
196
226
DataStructures.jl
48
function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end
rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V}
[ 196, 226 ]
function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) ##CHUNK 2 "b" => 2 julia> empty!(A); julia> A SwissDict{String, Int64}() ``` """ function Base.empty!(h::SwissDict{K,V}) where {K, V} fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 ##CHUNK 3 if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 # Functions which are not exported, but are required for checking invariants hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end function get_idxfloor(h::RobinDict) @inbounds for i = 1:length(h.keys) if isslotfilled(h, i) return i end end return 0 #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 julia> empty!(A); julia> A OrderedRobinDict{String, Int64}() ``` """ function Base.empty!(h::OrderedRobinDict{K,V}) where {K, V} empty!(h.dict) empty!(h.keys) empty!(h.vals) h.count = 0 return h end function _setindex!(h::OrderedRobinDict, v, key) hk, hv = h.keys, h.vals push!(hk, key) push!(hv, v) nk = length(hk) #CURRENT FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end ##CHUNK 2 sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 ##CHUNK 3 newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] ##CHUNK 4 rethrow(e) end end end hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) ##CHUNK 5 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 Based on the information above, please generate test code for the following function: function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "robin_dict.jl" ], "ground_truth": "function Base.empty!(h::RobinDict{K,V}) where {K, V}\n sz = length(h.keys)\n empty!(h.hashes)\n empty!(h.keys)\n empty!(h.vals)\n resize!(h.keys, sz)\n resize!(h.vals, sz)\n resize!(h.hashes, sz)\n fill!(h.hashes, 0)\n h.count = 0\n h.idxfloor = 0\n return h\nend", "task_id": "DataStructures/49" }
274
286
DataStructures.jl
49
function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end
Base.empty!(h::RobinDict{K,V}) where {K, V}
[ 274, 286 ]
function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) end function _delete!(h::SwissDict{K,V}, index) where {K,V} # Caller is responsible for maybe shrinking the SwissDict after the deletion. isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, index-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, index-1) isboundary = iszero(index & 0x0f) #boundaries: 16, 32, ... @inbounds _slotset!(h.slots, ifelse(isboundary, 0x01, 0x00), index) h.count -= 1 h.age += 1 ##CHUNK 2 end function _delete!(h::SwissDict{K,V}, index) where {K,V} # Caller is responsible for maybe shrinking the SwissDict after the deletion. isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, index-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, index-1) isboundary = iszero(index & 0x0f) #boundaries: 16, 32, ... @inbounds _slotset!(h.slots, ifelse(isboundary, 0x01, 0x00), index) h.count -= 1 h.age += 1 maybe_rehash_shrink!(h) end # fast iteration over active slots. function _iterslots(h::SwissDict, start::Int) i0 = ((start-1) & (length(h.keys)-1))>>4 + 1 off = (start-1) & 0x0f @inbounds sl = _find_free(h.slots[i0>>4 + 1]) sl = ((~sl & 0xffff)>>off) << off #FILE: DataStructures.jl/test/test_robin_dict.jl ##CHUNK 1 # Functions which are not exported, but are required for checking invariants hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end function get_idxfloor(h::RobinDict) @inbounds for i = 1:length(h.keys) if isslotfilled(h, i) return i end end return 0 #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 @inbounds h.dict[h.keys[index]] = -1 h.count -= 1 check_for_rehash(h) ? rehash!(h) : h end function get_first_filled_index(h::OrderedRobinDict) index = 1 while (true) isslotfilled(h, index) && return index index += 1 end end function get_next_filled_index(h::OrderedRobinDict, index) # get the next filled slot, including index and beyond while (index <= length(h.keys)) isslotfilled(h, index) && return index index += 1 end return -1 #CURRENT FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 rethrow(e) end end end hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) ##CHUNK 2 index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end index = (index & (sz - 1)) + 1 end end """ get!(collection, key, default) Return the value stored for the given key, or if no mapping for the key is present, store `key => default`, and return `default`. ##CHUNK 3 resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end ##CHUNK 4 sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 ##CHUNK 5 @inbounds while true if (isslotempty(h, index_curr)) || (isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey)) break end probe_distance = calculate_distance(h, index_curr) if probe_current > probe_distance h.vals[index_curr], cval = cval, h.vals[index_curr] h.keys[index_curr], ckey = ckey, h.keys[index_curr] h.hashes[index_curr], chash = chash, h.hashes[index_curr] probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end ##CHUNK 6 probe_current = probe_distance end probe_current += 1 index_curr = (index_curr & (sz - 1)) + 1 end @inbounds if isslotfilled(h, index_curr) && isequal(h.keys[index_curr], ckey) h.vals[index_curr] = cval return index_curr end @inbounds if isslotempty(h, index_curr) h.count += 1 end @inbounds h.vals[index_curr] = cval @inbounds h.keys[index_curr] = ckey @inbounds h.hashes[index_curr] = chash @assert probe_current >= 0 Based on the information above, please generate test code for the following function: function rh_delete!(h::RobinDict{K, V}, index) where {K, V} @assert index > 0 # this assumes that there is a key/value present in the dictionary at index index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "robin_dict.jl" ], "ground_truth": "function rh_delete!(h::RobinDict{K, V}, index) where {K, V}\n @assert index > 0\n\n # this assumes that there is a key/value present in the dictionary at index\n index0 = index\n sz = length(h.keys)\n @inbounds while true\n index0 = (index0 & (sz - 1)) + 1\n if isslotempty(h, index0) || calculate_distance(h, index0) == 0\n break\n end\n end\n #index0 represents the position before which we have to shift backwards\n\n # the backwards shifting algorithm\n curr = index\n next = (index & (sz - 1)) + 1\n\n @inbounds while next != index0\n h.vals[curr] = h.vals[next]\n h.keys[curr] = h.keys[next]\n h.hashes[curr] = h.hashes[next]\n curr = next\n next = (next & (sz-1)) + 1\n end\n\n #curr is at the last position, reset back to normal\n isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1)\n isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1)\n @inbounds h.hashes[curr] = 0x0\n\n h.count -= 1\n # this is necessary because key at idxfloor might get deleted\n h.idxfloor = get_next_filled(h, h.idxfloor)\n return h\nend", "task_id": "DataStructures/50" }
459
494
DataStructures.jl
50
function rh_delete!(h::RobinDict{K, V}, index) where {K, V} @assert index > 0 # this assumes that there is a key/value present in the dictionary at index index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end
rh_delete!(h::RobinDict{K, V}, index) where {K, V}
[ 459, 494 ]
function rh_delete!(h::RobinDict{K, V}, index) where {K, V} @assert index > 0 # this assumes that there is a key/value present in the dictionary at index index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/sorted_multi_dict.jl ##CHUNK 1 function Base.isequal(m1::SortedMultiDict{K, D, Ord}, m2::SortedMultiDict{K, D, Ord}) where {K, D, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) return false end p1 = firstindex(m1) p2 = firstindex(m2) while true if p1 == pastendsemitoken(m1) return p2 == pastendsemitoken(m2) end if p2 == pastendsemitoken(m2) return false end @inbounds k1,d1 = deref((m1,p1)) @inbounds k2,d2 = deref((m2,p2)) (!eq(ord,k1,k2) || !isequal(d1,d2)) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) #CURRENT FILE: DataStructures.jl/src/sorted_set.jl ##CHUNK 1 p1 = state.p1 p2 = state.p2 while true m1end = p1 == pastendsemitoken(m1) m2end = p2 == pastendsemitoken(m2) if m1end return nothing end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end if !lt(ord, k2, k1) @inbounds p1 = advance((m1,p1)) end @inbounds p2 = advance((m2, p2)) ##CHUNK 2 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while true m1end = p1 == pastendsemitoken(m1) m2end = p2 == pastendsemitoken(m2) if m1end && m2end return nothing end if m1end @inbounds return (deref((m2, p2)), TwoSortedSets_State(p1, advance((m2,p2)))) end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) ##CHUNK 3 m1::SortedSet{K,Ord} m2::SortedSet{K,Ord} end function Base.iterate(twoss::SetdiffTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while true m1end = p1 == pastendsemitoken(m1) m2end = p2 == pastendsemitoken(m2) if m1end return nothing end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) ##CHUNK 4 if m1end @inbounds return (deref((m2, p2)), TwoSortedSets_State(p1, advance((m2,p2)))) end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end if lt(ord, k2, k1) @inbounds return (k2, TwoSortedSets_State(p1, advance((m2,p2)))) end @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end ##CHUNK 5 return true end function Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) || length(m1) < length(m2) / log2(length(m2) + 2) return invoke(issubset, Tuple{Any, SortedSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while p1 != pastendsemitoken(m1) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if eq(ord, k1, k2) @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) elseif lt(ord, k1,k2) return false ##CHUNK 6 end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end if !lt(ord, k2, k1) @inbounds p1 = advance((m1,p1)) end @inbounds p2 = advance((m2, p2)) end end """ Base.setdiff(ss1::SortedSet{K,Ord}, ss2::SortedSet{K,Ord}) where {K, Ord<:Ordering} Base.setdiff(ss1::SortedSet, others...) Return the set difference, i.e., a sorted set containing entries in `ss1` but not in `ss2` or successive arguments. Time for the first form: O(*cn*) ##CHUNK 7 p2 = firstindex(m2) while p1 != pastendsemitoken(m1) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if eq(ord, k1, k2) @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) elseif lt(ord, k1,k2) return false else @inbounds p2 = advance((m2,p2)) end end return true end # Standard copy functions use packcopy - that is, they retain elements but not # the identical structure. Base.copymutable(m::SortedSet) = packcopy(m) ##CHUNK 8 struct SymdiffTwoSortedSets{K,Ord <: Ordering} m1::SortedSet{K,Ord} m2::SortedSet{K,Ord} end function Base.iterate(twoss::SymdiffTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while true m1end = p1 == pastendsemitoken(m1) m2end = p2 == pastendsemitoken(m2) if m1end && m2end return nothing end ##CHUNK 9 ord = orderobject(m1) if ord != orderobject(m2) return invoke(issetequal, Tuple{AbstractSet, AbstractSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while true p1 == pastendsemitoken(m1) && return p2 == pastendsemitoken(m2) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1,p1)) @inbounds k2 = deref((m2,p2)) !eq(ord,k1,k2) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end Base.issetequal(m1::SortedSet, m2::SortedSet) = isequal(m1, m2) Based on the information above, please generate test code for the following function: function Base.iterate(twoss::IntersectTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2) @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds p1 = advance((m1, p1)) continue end if lt(ord, k2, k1) @inbounds p2 = advance((m2, p2)) continue end @inbounds return (k1, TwoSortedSets_State(advance((m1, p1)), advance((m2, p2)))) end return nothing end
{ "fpath_tuple": [ "DataStructures.jl", "src", "sorted_set.jl" ], "ground_truth": "function Base.iterate(twoss::IntersectTwoSortedSets,\n state = TwoSortedSets_State(firstindex(twoss.m1),\n firstindex(twoss.m2)))\n m1 = twoss.m1\n m2 = twoss.m2\n ord = orderobject(m1)\n p1 = state.p1\n p2 = state.p2\n while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2)\n @inbounds k1 = deref((m1, p1))\n @inbounds k2 = deref((m2, p2))\n if lt(ord, k1, k2)\n @inbounds p1 = advance((m1, p1))\n continue\n end\n if lt(ord, k2, k1)\n @inbounds p2 = advance((m2, p2))\n continue\n end\n @inbounds return (k1, TwoSortedSets_State(advance((m1, p1)),\n advance((m2, p2))))\n end\n return nothing\nend", "task_id": "DataStructures/51" }
395
418
DataStructures.jl
51
function Base.iterate(twoss::IntersectTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2) @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds p1 = advance((m1, p1)) continue end if lt(ord, k2, k1) @inbounds p2 = advance((m2, p2)) continue end @inbounds return (k1, TwoSortedSets_State(advance((m1, p1)), advance((m2, p2)))) end return nothing end
Base.iterate(twoss::IntersectTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2)))
[ 395, 418 ]
function Base.iterate(twoss::IntersectTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2) @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds p1 = advance((m1, p1)) continue end if lt(ord, k2, k1) @inbounds p2 = advance((m2, p2)) continue end @inbounds return (k1, TwoSortedSets_State(advance((m1, p1)), advance((m2, p2)))) end return nothing end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/sorted_dict.jl ##CHUNK 1 Time: O(*cn*) """ function Base.isequal(m1::SortedDict{K, D, Ord}, m2::SortedDict{K, D, Ord}) where {K, D, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) return invoke((==), Tuple{AbstractDict, AbstractDict}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while true p1 == pastendsemitoken(m1) && return p2 == pastendsemitoken(m2) p2 == pastendsemitoken(m2) && return false @inbounds k1,d1 = deref((m1,p1)) @inbounds k2,d2 = deref((m2,p2)) (!eq(ord,k1,k2) || !isequal(d1,d2)) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end ##CHUNK 2 p2 = firstindex(m2) while true p1 == pastendsemitoken(m1) && return p2 == pastendsemitoken(m2) p2 == pastendsemitoken(m2) && return false @inbounds k1,d1 = deref((m1,p1)) @inbounds k2,d2 = deref((m2,p2)) (!eq(ord,k1,k2) || !isequal(d1,d2)) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end function mergetwo!(m::SortedDict{K,D,Ord}, m2) where {K,D,Ord <: Ordering} for (k,v) in m2 m[convert(K,k)] = convert(D,v) end end #FILE: DataStructures.jl/src/sorted_multi_dict.jl ##CHUNK 1 function Base.isequal(m1::SortedMultiDict{K, D, Ord}, m2::SortedMultiDict{K, D, Ord}) where {K, D, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) return false end p1 = firstindex(m1) p2 = firstindex(m2) while true if p1 == pastendsemitoken(m1) return p2 == pastendsemitoken(m2) end if p2 == pastendsemitoken(m2) return false end @inbounds k1,d1 = deref((m1,p1)) @inbounds k2,d2 = deref((m2,p2)) (!eq(ord,k1,k2) || !isequal(d1,d2)) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) ##CHUNK 2 return p2 == pastendsemitoken(m2) end if p2 == pastendsemitoken(m2) return false end @inbounds k1,d1 = deref((m1,p1)) @inbounds k2,d2 = deref((m2,p2)) (!eq(ord,k1,k2) || !isequal(d1,d2)) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end function mergetwo!(m::SortedMultiDict{K,D,Ord}, iterable) where {K,D,Ord <: Ordering} for (k,v) in iterable insert!(m.bt, convert(K,k), convert(D,v), true) end end #CURRENT FILE: DataStructures.jl/src/sorted_set.jl ##CHUNK 1 ord = orderobject(m1) if ord != orderobject(m2) return invoke(issetequal, Tuple{AbstractSet, AbstractSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while true p1 == pastendsemitoken(m1) && return p2 == pastendsemitoken(m2) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1,p1)) @inbounds k2 = deref((m2,p2)) !eq(ord,k1,k2) && return false @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end Base.issetequal(m1::SortedSet, m2::SortedSet) = isequal(m1, m2) ##CHUNK 2 p1 = state.p1 p2 = state.p2 while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2) @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds p1 = advance((m1, p1)) continue end if lt(ord, k2, k1) @inbounds p2 = advance((m2, p2)) continue end @inbounds return (k1, TwoSortedSets_State(advance((m1, p1)), advance((m2, p2)))) end return nothing end ##CHUNK 3 p1::IntSemiToken p2::IntSemiToken end function Base.iterate(twoss::IntersectTwoSortedSets, state = TwoSortedSets_State(firstindex(twoss.m1), firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while p1 != pastendsemitoken(m1) && p2 != pastendsemitoken(m2) @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds p1 = advance((m1, p1)) continue end if lt(ord, k2, k1) ##CHUNK 4 firstindex(twoss.m2))) m1 = twoss.m1 m2 = twoss.m2 ord = orderobject(m1) p1 = state.p1 p2 = state.p2 while true m1end = p1 == pastendsemitoken(m1) m2end = p2 == pastendsemitoken(m2) if m1end return nothing end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end ##CHUNK 5 TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end if lt(ord, k2, k1) @inbounds return (k2, TwoSortedSets_State(p1, advance((m2,p2)))) end @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) end end """ Base.symdiff(ss1::SortedSet, iterable) Compute and return the symmetric difference of `ss1` and `iterable`, i.e., a sorted set ##CHUNK 6 return nothing end if m2end @inbounds return (deref((m1, p1)), TwoSortedSets_State(advance((m1,p1)), p2)) end @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if lt(ord, k1, k2) @inbounds return (k1, TwoSortedSets_State(advance((m1,p1)), p2)) end if !lt(ord, k2, k1) @inbounds p1 = advance((m1,p1)) end @inbounds p2 = advance((m2, p2)) end end """ Base.setdiff(ss1::SortedSet{K,Ord}, ss2::SortedSet{K,Ord}) where {K, Ord<:Ordering} Based on the information above, please generate test code for the following function: function Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) || length(m1) < length(m2) / log2(length(m2) + 2) return invoke(issubset, Tuple{Any, SortedSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while p1 != pastendsemitoken(m1) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if eq(ord, k1, k2) @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) elseif lt(ord, k1,k2) return false else @inbounds p2 = advance((m2,p2)) end end return true end
{ "fpath_tuple": [ "DataStructures.jl", "src", "sorted_set.jl" ], "ground_truth": "function Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering}\n ord = orderobject(m1)\n if ord != orderobject(m2) ||\n length(m1) < length(m2) / log2(length(m2) + 2)\n return invoke(issubset, Tuple{Any, SortedSet}, m1, m2)\n end\n p1 = firstindex(m1)\n p2 = firstindex(m2)\n while p1 != pastendsemitoken(m1)\n p2 == pastendsemitoken(m2) && return false\n @inbounds k1 = deref((m1, p1))\n @inbounds k2 = deref((m2, p2))\n if eq(ord, k1, k2)\n @inbounds p1 = advance((m1,p1))\n @inbounds p2 = advance((m2,p2))\n elseif lt(ord, k1,k2)\n return false\n else\n @inbounds p2 = advance((m2,p2))\n end\n end\n return true\nend", "task_id": "DataStructures/52" }
648
670
DataStructures.jl
52
function Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) || length(m1) < length(m2) / log2(length(m2) + 2) return invoke(issubset, Tuple{Any, SortedSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while p1 != pastendsemitoken(m1) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if eq(ord, k1, k2) @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) elseif lt(ord, k1,k2) return false else @inbounds p2 = advance((m2,p2)) end end return true end
Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering}
[ 648, 670 ]
function Base.issubset(m1::SortedSet{K,Ord}, m2::SortedSet{K,Ord}) where {K, Ord <: Ordering} ord = orderobject(m1) if ord != orderobject(m2) || length(m1) < length(m2) / log2(length(m2) + 2) return invoke(issubset, Tuple{Any, SortedSet}, m1, m2) end p1 = firstindex(m1) p2 = firstindex(m2) while p1 != pastendsemitoken(m1) p2 == pastendsemitoken(m2) && return false @inbounds k1 = deref((m1, p1)) @inbounds k2 = deref((m2, p2)) if eq(ord, k1, k2) @inbounds p1 = advance((m1,p1)) @inbounds p2 = advance((m2,p2)) elseif lt(ord, k1,k2) return false else @inbounds p2 = advance((m2,p2)) end end return true end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) #CURRENT FILE: DataStructures.jl/src/sparse_int_set.jl ##CHUNK 1 pageid, offset = pageid_offset(s, i) pages = s.reverse plen = length(pages) if pageid > plen # Create new null pages up to pageid and fresh (zero-filled) one at pageid sizehint!(pages, pageid) sizehint!(s.counters, pageid) for i in 1:pageid - plen - 1 push!(pages, NULL_INT_PAGE) push!(s.counters, 0) end push!(pages, zeros(Int, INT_PER_PAGE)) push!(s.counters, 0) elseif pages[pageid] === NULL_INT_PAGE #assign a page to previous null page pages[pageid] = zeros(Int, INT_PER_PAGE) end page = pages[pageid] if page[offset] == 0 ##CHUNK 2 push!(s.counters, 0) end push!(pages, zeros(Int, INT_PER_PAGE)) push!(s.counters, 0) elseif pages[pageid] === NULL_INT_PAGE #assign a page to previous null page pages[pageid] = zeros(Int, INT_PER_PAGE) end page = pages[pageid] if page[offset] == 0 @inbounds page[offset] = length(s) + 1 @inbounds s.counters[pageid] += 1 push!(s.packed, i) return s end return s end @inline function Base.push!(s::SparseIntSet, is::Integer...) for i in is ##CHUNK 3 page = @inbounds s.reverse[pageid] return page !== NULL_INT_PAGE && @inbounds page[offset] != 0 end end Base.length(s::SparseIntSet) = length(s.packed) @inline function Base.push!(s::SparseIntSet, i::Integer) i <= 0 && throw(DomainError("Only positive Ints allowed.")) pageid, offset = pageid_offset(s, i) pages = s.reverse plen = length(pages) if pageid > plen # Create new null pages up to pageid and fresh (zero-filled) one at pageid sizehint!(pages, pageid) sizehint!(s.counters, pageid) for i in 1:pageid - plen - 1 push!(pages, NULL_INT_PAGE) ##CHUNK 4 const INT_PER_PAGE = div(ccall(:jl_getpagesize, Clong, ()), sizeof(Int)) # we use this to mark pages not in use, it must never be written to. const NULL_INT_PAGE = Vector{Int}() mutable struct SparseIntSet packed ::Vector{Int} reverse::Vector{Vector{Int}} counters::Vector{Int} # counts the number of real elements in each page of reverse. end ##CHUNK 5 function pageid_offset(s::SparseIntSet, i) pageid = div(i - 1, INT_PER_PAGE) + 1 return pageid, (i - 1) & (INT_PER_PAGE - 1) + 1 end function Base.in(i, s::SparseIntSet) pageid, offset = pageid_offset(s, i) if pageid > length(s.reverse) return false else page = @inbounds s.reverse[pageid] return page !== NULL_INT_PAGE && @inbounds page[offset] != 0 end end Base.length(s::SparseIntSet) = length(s.packed) @inline function Base.push!(s::SparseIntSet, i::Integer) i <= 0 && throw(DomainError("Only positive Ints allowed.")) ##CHUNK 6 const INT_PER_PAGE = div(ccall(:jl_getpagesize, Clong, ()), sizeof(Int)) # we use this to mark pages not in use, it must never be written to. const NULL_INT_PAGE = Vector{Int}() mutable struct SparseIntSet packed ::Vector{Int} reverse::Vector{Vector{Int}} counters::Vector{Int} # counts the number of real elements in each page of reverse. end SparseIntSet() = SparseIntSet(Int[], Vector{Int}[], Int[]) SparseIntSet(indices) = union!(SparseIntSet(), indices) Base.eltype(::Type{SparseIntSet}) = Int Base.empty(::SparseIntSet) = SparseIntSet() function Base.empty!(s::SparseIntSet) empty!(s.packed) ##CHUNK 7 s.reverse[to_page][to_offset] = s.reverse[from_page][from_offset] s.reverse[from_page][from_offset] = 0 s.counters[from_page] -= 1 pop!(s.packed) end cleanup!(s, from_page) return id end @inline function cleanup!(s::SparseIntSet, pageid::Int) if s.counters[pageid] == 0 s.reverse[pageid] = NULL_INT_PAGE end end @inline function Base.pop!(s::SparseIntSet, id::Integer, default) id < 0 && throw(ArgumentError("Int to pop needs to be positive.")) return in(id, s) ? (@inbounds pop!(s, id)) : default end Base.popfirst!(s::SparseIntSet) = pop!(s, first(s)) ##CHUNK 8 if s.counters[pageid] == 0 s.reverse[pageid] = NULL_INT_PAGE end end @inline function Base.pop!(s::SparseIntSet, id::Integer, default) id < 0 && throw(ArgumentError("Int to pop needs to be positive.")) return in(id, s) ? (@inbounds pop!(s, id)) : default end Base.popfirst!(s::SparseIntSet) = pop!(s, first(s)) @inline Base.iterate(set::SparseIntSet, args...) = iterate(set.packed, args...) Base.last(s::SparseIntSet) = isempty(s) ? throw(ArgumentError("Empty set has no last element.")) : last(s.packed) Base.union(s::SparseIntSet, ns) = union!(copy(s), ns) function Base.union!(s::SparseIntSet, ns) for n in ns push!(s, n) end Based on the information above, please generate test code for the following function: function Base.copy!(to::SparseIntSet, from::SparseIntSet) to.packed = copy(from.packed) #we want to keep the null pages === NULL_INT_PAGE resize!(to.reverse, length(from.reverse)) for i in eachindex(from.reverse) page = from.reverse[i] if page === NULL_INT_PAGE to.reverse[i] = NULL_INT_PAGE else to.reverse[i] = copy(from.reverse[i]) end end to.counters = copy(from.counters) return to end
{ "fpath_tuple": [ "DataStructures.jl", "src", "sparse_int_set.jl" ], "ground_truth": "function Base.copy!(to::SparseIntSet, from::SparseIntSet)\n to.packed = copy(from.packed)\n #we want to keep the null pages === NULL_INT_PAGE\n resize!(to.reverse, length(from.reverse))\n for i in eachindex(from.reverse)\n page = from.reverse[i]\n if page === NULL_INT_PAGE\n to.reverse[i] = NULL_INT_PAGE\n else\n to.reverse[i] = copy(from.reverse[i])\n end\n end\n to.counters = copy(from.counters)\n return to\nend", "task_id": "DataStructures/53" }
30
44
DataStructures.jl
53
function Base.copy!(to::SparseIntSet, from::SparseIntSet) to.packed = copy(from.packed) #we want to keep the null pages === NULL_INT_PAGE resize!(to.reverse, length(from.reverse)) for i in eachindex(from.reverse) page = from.reverse[i] if page === NULL_INT_PAGE to.reverse[i] = NULL_INT_PAGE else to.reverse[i] = copy(from.reverse[i]) end end to.counters = copy(from.counters) return to end
Base.copy!(to::SparseIntSet, from::SparseIntSet)
[ 30, 44 ]
function Base.copy!(to::SparseIntSet, from::SparseIntSet) to.packed = copy(from.packed) #we want to keep the null pages === NULL_INT_PAGE resize!(to.reverse, length(from.reverse)) for i in eachindex(from.reverse) page = from.reverse[i] if page === NULL_INT_PAGE to.reverse[i] = NULL_INT_PAGE else to.reverse[i] = copy(from.reverse[i]) end end to.counters = copy(from.counters) return to end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 2 """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data ##CHUNK 3 node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ haskey(tree::AVLTree{K}, k::K) where K Verify if AVL tree `tree` contains the key `k`. Analogous to [`in(key, tree::AVLTree)`](@ref). """ function Base.haskey(tree::AVLTree{K}, k::K) where K (tree.root == nothing) && return false node = search_node(tree, k) return (node.data == k) end ##CHUNK 4 julia> for k in 1:2:20 push!(tree, k) end julia> sorted_rank(tree, 17) 9 ``` """ function sorted_rank(tree::AVLTree{K}, key::K) where K !haskey(tree, key) && throw(KeyError(key)) node = tree.root rank = 0 while node.data != key if (node.data < key) rank += (1 + get_subsize(node.leftChild)) node = node.rightChild else node = node.leftChild end #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild end end return node end """ haskey(tree, key) Returns true if `key` is present in the `tree`, else returns false. """ ##CHUNK 2 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 3 end RBTree() = RBTree{Any}() Base.length(tree::RBTree) = tree.count """ search_node(tree, key) Returns the last visited node, while traversing through in binary-search-tree fashion looking for `key`. """ search_node(tree, key) function search_node(tree::RBTree{K}, d::K) where K node = tree.root while node !== tree.nil && d != node.data if d < node.data node = node.leftChild else node = node.rightChild ##CHUNK 4 node = node.leftChild end return node end """ delete!(tree::RBTree, key) Deletes `key` from `tree`, if present, else returns the unmodified tree. """ function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data ##CHUNK 5 function insert_node!(tree::RBTree, node::RBTreeNode) node_y = nothing node_x = tree.root while node_x !== tree.nil node_y = node_x if node.data < node_x.data node_x = node_x.leftChild else node_x = node_x.rightChild end end node.parent = node_y if node_y == nothing tree.root = node elseif node.data < node_y.data node_y.leftChild = node else node_y.rightChild = node #CURRENT FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing Based on the information above, please generate test code for the following function: function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end
{ "fpath_tuple": [ "DataStructures.jl", "src", "splay_tree.jl" ], "ground_truth": "function search_node(tree::SplayTree{K}, d::K) where K\n node = tree.root\n prev = nothing\n while node != nothing && node.data != d\n prev = node\n if node.data < d\n node = node.rightChild\n else\n node = node.leftChild\n end\n end\n return (node == nothing) ? prev : node\nend", "task_id": "DataStructures/54" }
129
141
DataStructures.jl
54
function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end
search_node(tree::SplayTree{K}, d::K) where K
[ 129, 141 ]
function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ ##CHUNK 2 """ minimum_node(tree::AVLTree, node::AVLTreeNode) Returns the AVLTreeNode with minimum value in subtree of `node`. """ function minimum_node(node::Union{AVLTreeNode, Nothing}) while node != nothing && node.leftChild != nothing node = node.leftChild end return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 function Base.insert!(tree::RBTree{K}, d::K) where K # if the key exists in the tree, no need to insert haskey(tree, d) && return tree # insert, if not present in the tree node = RBTreeNode{K}(d) node.leftChild = node.rightChild = tree.nil insert_node!(tree, node) if node.parent == nothing node.color = false elseif node.parent.parent == nothing ; else fix_insert!(tree, node) end tree.count += 1 return tree end #CURRENT FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 2 is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing ##CHUNK 3 is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing ##CHUNK 4 y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end ##CHUNK 5 # All the items in S are smaller than the items in T. # This is a two-step process. # In the first step, splay the largest node in S. This moves the largest node to the root node. # In the second step, set the right child of the new root of S to T. function _join!(tree::SplayTree, s::Union{SplayTreeNode, Nothing}, t::Union{SplayTreeNode, Nothing}) if s === nothing return t elseif t === nothing return s else x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root ##CHUNK 6 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 7 end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) Based on the information above, please generate test code for the following function: function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 return tree end
{ "fpath_tuple": [ "DataStructures.jl", "src", "splay_tree.jl" ], "ground_truth": "function Base.delete!(tree::SplayTree{K}, d::K) where K\n node = tree.root\n x = search_node(tree, d)\n (x == nothing) && return tree\n t = nothing\n s = nothing\n\n splay!(tree, x)\n\n if x.rightChild !== nothing\n t = x.rightChild\n t.parent = nothing\n end\n\n s = x\n s.rightChild = nothing\n\n if s.leftChild !== nothing\n s.leftChild.parent = nothing\n end\n\n tree.root = _join!(tree, s.leftChild, t)\n tree.count -= 1\n return tree\nend", "task_id": "DataStructures/55" }
158
182
DataStructures.jl
55
function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 return tree end
Base.delete!(tree::SplayTree{K}, d::K) where K
[ 158, 182 ]
function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 return tree end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 function Base.delete!(tree::RBTree{K}, d::K) where K z = tree.nil node = tree.root while node !== tree.nil if node.data == d z = node end if d < node.data node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color ##CHUNK 2 node = node.leftChild else node = node.rightChild end end (z === tree.nil) && return tree y = z y_original_color = y.color x = RBTreeNode{K}() if z.leftChild === tree.nil x = z.rightChild rb_transplant(tree, z, z.rightChild) elseif z.rightChild === tree.nil x = z.leftChild rb_transplant(tree, z, z.leftChild) else y = minimum_node(tree, z.rightChild) y_original_color = y.color ##CHUNK 3 function insert_node!(tree::RBTree, node::RBTreeNode) node_y = nothing node_x = tree.root while node_x !== tree.nil node_y = node_x if node.data < node_x.data node_x = node_x.leftChild else node_x = node_x.rightChild end end node.parent = node_y if node_y == nothing tree.root = node elseif node.data < node_y.data node_y.leftChild = node else node_y.rightChild = node ##CHUNK 4 x = y.rightChild if y.parent == z x.parent = y else rb_transplant(tree, y, y.rightChild) y.rightChild = z.rightChild y.rightChild.parent = y end rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 return node end function search_node(tree::AVLTree{K}, d::K) where K prev = nothing node = tree.root while node != nothing && node.data != nothing && node.data != d prev = node if d < node.data node = node.leftChild else node = node.rightChild end end return (node == nothing) ? prev : node end """ #CURRENT FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end ##CHUNK 2 x = maximum_node(s) splay!(tree, x) x.rightChild = t t.parent = x return x end end function search_node(tree::SplayTree{K}, d::K) where K node = tree.root prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node ##CHUNK 3 end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) is_found && splay!(tree, node) return is_found end end Base.in(key, tree::SplayTree) = haskey(tree, key) function Base.delete!(tree::SplayTree{K}, d::K) where K node = tree.root x = search_node(tree, d) ##CHUNK 4 prev = nothing while node != nothing && node.data != d prev = node if node.data < d node = node.rightChild else node = node.leftChild end end return (node == nothing) ? prev : node end function Base.haskey(tree::SplayTree{K}, d::K) where K node = tree.root if node === nothing return false else node = search_node(tree, d) (node === nothing) && return false is_found = (node.data == d) ##CHUNK 5 (x == nothing) && return tree t = nothing s = nothing splay!(tree, x) if x.rightChild !== nothing t = x.rightChild t.parent = nothing end s = x s.rightChild = nothing if s.leftChild !== nothing s.leftChild.parent = nothing end tree.root = _join!(tree, s.leftChild, t) tree.count -= 1 Based on the information above, please generate test code for the following function: function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end
{ "fpath_tuple": [ "DataStructures.jl", "src", "splay_tree.jl" ], "ground_truth": "function Base.push!(tree::SplayTree{K}, d0) where K\n d = convert(K, d0)\n is_present = search_node(tree, d)\n if (is_present !== nothing) && (is_present.data == d)\n return tree\n end\n # only unique keys are inserted\n node = SplayTreeNode{K}(d)\n y = nothing\n x = tree.root\n\n while x !== nothing\n y = x\n if node.data > x.data\n x = x.rightChild\n else\n x = x.leftChild\n end\n end\n node.parent = y\n\n if y === nothing\n tree.root = node\n elseif node.data < y.data\n y.leftChild = node\n else\n y.rightChild = node\n end\n splay!(tree, node)\n tree.count += 1\n return tree\nend", "task_id": "DataStructures/56" }
184
215
DataStructures.jl
56
function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end
Base.push!(tree::SplayTree{K}, d0) where K
[ 184, 215 ]
function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node end splay!(tree, node) tree.count += 1 return tree end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/red_black_tree.jl ##CHUNK 1 Base.in(key, tree::RBTree) = haskey(tree, key) """ getindex(tree, ind) Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key. """ function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) ##CHUNK 2 function traverse_tree_inorder(node::RBTreeNode{K}) where K if (node !== tree.nil) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end ##CHUNK 3 rb_transplant(tree, z, y) y.leftChild = z.leftChild y.leftChild.parent = y y.color = z.color end !y_original_color && delete_fix(tree, x) tree.count -= 1 return tree end Base.in(key, tree::RBTree) = haskey(tree, key) """ getindex(tree, ind) Gets the key present at index `ind` of the tree. Indexing is done in increasing order of key. """ function Base.getindex(tree::RBTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(ArgumentError("$ind should be in between 1 and $(tree.count)")) #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 julia> tree[4] 7 julia> tree[8] 15 ``` """ function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end ##CHUNK 2 # Examples ```jldoctest julia> tree = AVLTree{Int}() AVLTree{Int64}(nothing, 0) julia> for k in 1:2:20 push!(tree, k) end julia> tree[4] 7 julia> tree[8] 15 ``` """ function Base.getindex(tree::AVLTree{K}, ind::Integer) where K @boundscheck (1 <= ind <= tree.count) || throw(BoundsError("$ind should be in between 1 and $(tree.count)")) ##CHUNK 3 function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end end end value = traverse_tree(tree.root, ind) return value end #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 sum += ft.bi_tree[i] i -= i&(-i) end sum end Base.getindex(ft::FenwickTree{T}, ind::Integer) where T = prefixsum(ft, ind) ##CHUNK 2 """ inc!(ft::FenwickTree{T}, ind::Integer, val) Increases the value of the [`FenwickTree`] by `val` from the index `ind` upto the length of the Fenwick Tree. """ function inc!(ft::FenwickTree{T}, ind::Integer, val = 1) where T val0 = convert(T, val) i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i <= n ft.bi_tree[i] += val0 i += i&(-i) end end """ dec!(ft::FenwickTree, ind::Integer, val) ##CHUNK 3 Return the cumulative sum from index 1 upto `ind` of the [`FenwickTree`](@ref) # Examples ``` julia> f = FenwickTree{Int}(6) julia> inc!(f, 2, 5) julia> prefixsum(f, 1) 0 julia> prefixsum(f, 3) 5 ``` """ function prefixsum(ft::FenwickTree{T}, ind::Integer) where T sum = zero(T) ind < 1 && return sum i = ind n = ft.n @boundscheck 1 <= i <= n || throw(ArgumentError("$i should be in between 1 and $n")) @inbounds while i > 0 #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.delete!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) if index > 0 rh_delete!(h, index) end return h end function get_next_filled(h::RobinDict, i) L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end #CURRENT FILE: DataStructures.jl/src/splay_tree.jl Based on the information above, please generate test code for the following function: function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
{ "fpath_tuple": [ "DataStructures.jl", "src", "splay_tree.jl" ], "ground_truth": "function Base.getindex(tree::SplayTree{K}, ind) where K\n @boundscheck (1 <= ind <= tree.count) || throw(KeyError(\"$ind should be in between 1 and $(tree.count)\"))\n function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing})\n if (node != nothing)\n left = traverse_tree_inorder(node.leftChild)\n right = traverse_tree_inorder(node.rightChild)\n append!(push!(left, node.data), right)\n else\n return K[]\n end\n end\n arr = traverse_tree_inorder(tree.root)\n return @inbounds arr[ind]\nend", "task_id": "DataStructures/57" }
217
230
DataStructures.jl
57
function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
Base.getindex(tree::SplayTree{K}, ind) where K
[ 217, 230 ]
function Base.getindex(tree::SplayTree{K}, ind) where K @boundscheck (1 <= ind <= tree.count) || throw(KeyError("$ind should be in between 1 and $(tree.count)")) function traverse_tree_inorder(node::Union{SplayTreeNode, Nothing}) if (node != nothing) left = traverse_tree_inorder(node.leftChild) right = traverse_tree_inorder(node.rightChild) append!(push!(left, node.data), right) else return K[] end end arr = traverse_tree_inorder(tree.root) return @inbounds arr[ind] end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 # this assumes that there is a key/value present in the dictionary at index index0 = index sz = length(h.keys) @inbounds while true index0 = (index0 & (sz - 1)) + 1 if isslotempty(h, index0) || calculate_distance(h, index0) == 0 break end end #index0 represents the position before which we have to shift backwards # the backwards shifting algorithm curr = index next = (index & (sz - 1)) + 1 @inbounds while next != index0 h.vals[curr] = h.vals[next] h.keys[curr] = h.keys[next] h.hashes[curr] = h.hashes[next] #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx, tag cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 ##CHUNK 2 # and the key would be inserted at pos # This version is for use by setindex! and get!. It never rehashes. ht_keyindex2!(h::SwissDict, key) = ht_keyindex2!(h, key, _hashtag(hash(key))...) @inline function ht_keyindex2!(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchw(pointer(h.keys, i*16+1)) _prefetchw(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx, tag cands = _blsr(cands) end ##CHUNK 3 done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 ##CHUNK 4 i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) ##CHUNK 5 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull ##CHUNK 6 end @inline _find_free(v::_u8x16) = _vcmp_le(v, _expand16(UInt8(1))) # Basic operations # get the index where a key is stored, or -1 if not present ht_keyindex(h::SwissDict, key) = ht_keyindex(h::SwissDict, key, _hashtag(hash(key))...) # get the index where a key is stored, or -pos if not present # and the key would be inserted at pos # This version is for use by setindex! and get!. It never rehashes. ht_keyindex2!(h::SwissDict, key) = ht_keyindex2!(h, key, _hashtag(hash(key))...) @inline function ht_keyindex2!(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchw(pointer(h.keys, i*16+1)) _prefetchw(pointer(h.vals, i*16+1)) ##CHUNK 7 end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 ##CHUNK 8 # fast iteration over active slots. function _iterslots(h::SwissDict, start::Int) i0 = ((start-1) & (length(h.keys)-1))>>4 + 1 off = (start-1) & 0x0f @inbounds sl = _find_free(h.slots[i0>>4 + 1]) sl = ((~sl & 0xffff)>>off) << off return _iterslots(h, (i0, sl)) end function _iterslots(h::SwissDict, state) i, sl = state while iszero(sl) i += 1 i <= length(h.slots) || return nothing @inbounds msk = h.slots[i] sl = _find_free(msk) sl = (~sl & 0xffff) end ##CHUNK 9 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) end Based on the information above, please generate test code for the following function: function ht_keyindex(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function ht_keyindex(h::SwissDict, key, i0, tag)\n slots = h.slots\n keys = h.keys\n sz = length(slots)\n i = i0 & (sz-1)\n _prefetchr(pointer(h.keys, i*16+1))\n _prefetchr(pointer(h.vals, i*16+1))\n #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))?\n @inbounds while true\n msk = slots[i+1]\n cands, done = _find_candidates(msk, tag)\n while cands != 0\n off = trailing_zeros(cands)\n idx = i*16 + off + 1\n isequal(keys[idx], key) && return idx\n cands = _blsr(cands)\n end\n done && break\n i = (i+1) & (sz-1)\n end\n return -1\nend", "task_id": "DataStructures/58" }
149
170
DataStructures.jl
58
function ht_keyindex(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end
ht_keyindex(h::SwissDict, key, i0, tag)
[ 149, 170 ]
function ht_keyindex(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/sparse_int_set.jl ##CHUNK 1 iterator_length = length(it) if state > iterator_length return nothing end for i in state:iterator_length @inbounds id = it.shortest_set.packed[i] if in_valid(id, it) && !in_excluded(id, it) return map(x->findfirst_packed_id(id, x), it.valid_sets), i + 1 end end return nothing end #FILE: DataStructures.jl/src/circ_deque.jl ##CHUNK 1 # getindex sans bounds checking @inline function _unsafe_getindex(D::CircularDeque, i::Integer) j = D.first + i - 1 if j > D.capacity j -= D.capacity end @inbounds ret = D.buffer[j] return ret end @inline function Base.getindex(D::CircularDeque, i::Integer) @boundscheck 1 <= i <= D.n || throw(BoundsError()) return _unsafe_getindex(D, i) end # Iteration via getindex @inline function Base.iterate(d::CircularDeque, i = 1) i == d.n + 1 ? nothing : (_unsafe_getindex(d, i), i+1) end #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 end function _delete!(h::SwissDict{K,V}, index) where {K,V} # Caller is responsible for maybe shrinking the SwissDict after the deletion. isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, index-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, index-1) isboundary = iszero(index & 0x0f) #boundaries: 16, 32, ... @inbounds _slotset!(h.slots, ifelse(isboundary, 0x01, 0x00), index) h.count -= 1 h.age += 1 maybe_rehash_shrink!(h) end # fast iteration over active slots. function _iterslots(h::SwissDict, start::Int) i0 = ((start-1) & (length(h.keys)-1))>>4 + 1 off = (start-1) & 0x0f @inbounds sl = _find_free(h.slots[i0>>4 + 1]) sl = ((~sl & 0xffff)>>off) << off ##CHUNK 2 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v ##CHUNK 3 cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key ##CHUNK 4 _prefetchw(pointer(h.keys, i*16+1)) _prefetchw(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx, tag cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 ##CHUNK 5 maybe_rehash_shrink!(h) end # fast iteration over active slots. function _iterslots(h::SwissDict, start::Int) i0 = ((start-1) & (length(h.keys)-1))>>4 + 1 off = (start-1) & 0x0f @inbounds sl = _find_free(h.slots[i0>>4 + 1]) sl = ((~sl & 0xffff)>>off) << off return _iterslots(h, (i0, sl)) end # Dictionary resize logic: # Guarantee 40% of buckets and 15% of entries free, and at least 25% of entries filled # growth when > 85% entries full or > 60% buckets full, shrink when <25% entries full. # >60% bucket full should be super rare outside of very bad hash collisions or # super long-lived Dictionaries (expected 0.85^16 = 7% buckets full at 85% entries full). # worst-case hysteresis: shrink at 25% vs grow at 30% if all hashes collide. ##CHUNK 6 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) ##CHUNK 7 keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end ##CHUNK 8 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) Based on the information above, please generate test code for the following function: function _iterslots(h::SwissDict, state) i, sl = state while iszero(sl) i += 1 i <= length(h.slots) || return nothing @inbounds msk = h.slots[i] sl = _find_free(msk) sl = (~sl & 0xffff) end return ((i-1)*16 + trailing_zeros(sl) + 1, (i, _blsr(sl))) end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function _iterslots(h::SwissDict, state)\n i, sl = state\n while iszero(sl)\n i += 1\n i <= length(h.slots) || return nothing\n @inbounds msk = h.slots[i]\n sl = _find_free(msk)\n sl = (~sl & 0xffff)\n end\n return ((i-1)*16 + trailing_zeros(sl) + 1, (i, _blsr(sl)))\nend", "task_id": "DataStructures/59" }
244
254
DataStructures.jl
59
function _iterslots(h::SwissDict, state) i, sl = state while iszero(sl) i += 1 i <= length(h.slots) || return nothing @inbounds msk = h.slots[i] sl = _find_free(msk) sl = (~sl & 0xffff) end return ((i-1)*16 + trailing_zeros(sl) + 1, (i, _blsr(sl))) end
_iterslots(h::SwissDict, state)
[ 244, 254 ]
function _iterslots(h::SwissDict, state) i, sl = state while iszero(sl) i += 1 i <= length(h.slots) || return nothing @inbounds msk = h.slots[i] sl = _find_free(msk) sl = (~sl & 0xffff) end return ((i-1)*16 + trailing_zeros(sl) + 1, (i, _blsr(sl))) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end ##CHUNK 2 newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] ##CHUNK 3 h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] v = oldv[i] rh_insert_for_rehash!(h, k, v, oldh[i]) end end return h end function Base.sizehint!(d::RobinDict, newsz::Integer) newsz = _tablesz(newsz*2) # *2 for keys and values in same array oldsz = length(d.keys) #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) ##CHUNK 2 keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchr(pointer(h.keys, i*16+1)) _prefetchr(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end ##CHUNK 3 cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key ##CHUNK 4 _prefetchw(pointer(h.keys, i*16+1)) _prefetchw(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx, tag cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 ##CHUNK 5 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end return -1 end # get the index where a key is stored, or -pos if not present # and the key would be inserted at pos # This version is for use by setindex! and get!. It never rehashes. ht_keyindex2!(h::SwissDict, key) = ht_keyindex2!(h, key, _hashtag(hash(key))...) @inline function ht_keyindex2!(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) ##CHUNK 6 fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) ##CHUNK 7 # get the index where a key is stored, or -pos if not present # and the key would be inserted at pos # This version is for use by setindex! and get!. It never rehashes. ht_keyindex2!(h::SwissDict, key) = ht_keyindex2!(h, key, _hashtag(hash(key))...) @inline function ht_keyindex2!(h::SwissDict, key, i0, tag) slots = h.slots keys = h.keys sz = length(slots) i = i0 & (sz-1) _prefetchw(pointer(h.keys, i*16+1)) _prefetchw(pointer(h.vals, i*16+1)) #Todo/discuss: _prefetchr(pointer(h.keys, i*16+9))? @inbounds while true msk = slots[i+1] cands, done = _find_candidates(msk, tag) while cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 isequal(keys[idx], key) && return idx, tag Based on the information above, please generate test code for the following function: function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull @assert h.age == age0 @assert h.count == count return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V}\n olds = h.slots\n oldk = h.keys\n oldv = h.vals\n sz = length(oldk)\n newsz = _tablesz(newsz)\n (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1)\n h.age += 1\n h.idxfloor = 1\n if h.count == 0\n resize!(h.slots, newsz>>4)\n fill!(h.slots, _expand16(0x00))\n resize!(h.keys, newsz)\n resize!(h.vals, newsz)\n h.nbfull = 0\n return h\n end\n nssz = newsz>>4\n slots = fill(_expand16(0x00), nssz)\n keys = Vector{K}(undef, newsz)\n vals = Vector{V}(undef, newsz)\n age0 = h.age\n nbfull = 0\n is = _iterslots(h, 1)\n count = 0\n @inbounds while is !== nothing\n i, s = is\n k = oldk[i]\n v = oldv[i]\n i0, t = _hashtag(hash(k))\n i = i0 & (nssz-1)\n idx = 0\n while true\n msk = slots[i + 1]\n cands = _find_free(msk)\n if cands != 0\n off = trailing_zeros(cands)\n idx = i*16 + off + 1\n break\n end\n i = (i+1) & (nssz-1)\n end\n _slotset!(slots, t, idx)\n keys[idx] = k\n vals[idx] = v\n nbfull += iszero(idx & 0x0f)\n count += 1\n if h.age != age0\n return rehash!(h, newsz)\n end\n is = _iterslots(h, s)\n end\n h.slots = slots\n h.keys = keys\n h.vals = vals\n h.nbfull = nbfull\n @assert h.age == age0\n @assert h.count == count\n return h\nend", "task_id": "DataStructures/60" }
287
346
DataStructures.jl
60
function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull @assert h.age == age0 @assert h.count == count return h end
rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V}
[ 287, 346 ]
function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k vals[idx] = v nbfull += iszero(idx & 0x0f) count += 1 if h.age != age0 return rehash!(h, newsz) end is = _iterslots(h, s) end h.slots = slots h.keys = keys h.vals = vals h.nbfull = nbfull @assert h.age == age0 @assert h.count == count return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 RobinDict{String, Int64}() ``` """ function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) ##CHUNK 2 ```jldoctest julia> A = RobinDict("a" => 1, "b" => 2) RobinDict{String, Int64} with 2 entries: "b" => 2 "a" => 1 julia> empty!(A); julia> A RobinDict{String, Int64}() ``` """ function Base.empty!(h::RobinDict{K,V}) where {K, V} sz = length(h.keys) empty!(h.hashes) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) ##CHUNK 3 resize!(h.hashes, sz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end function rh_search(h::RobinDict{K, V}, key) where {K, V} sz = length(h.keys) chash = hash_key(key) index = desired_index(chash, sz) cdibs = 0 @inbounds while true if isslotempty(h, index) return -1 elseif cdibs > calculate_distance(h, index) return -1 elseif h.hashes[index] == chash && (h.keys[index] === key || isequal(h.keys[index], key)) return index end ##CHUNK 4 end return index_curr end #rehash! algorithm function rehash!(h::RobinDict{K,V}, newsz = length(h.keys)) where {K, V} oldk = h.keys oldv = h.vals oldh = h.hashes sz = length(oldk) newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end ##CHUNK 5 sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) # table full @assert h.count != length(h.keys) ckey, cval, chash = key, val, hash_key(key) sz = length(h.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 ##CHUNK 6 rethrow(e) end end end hash_key(key) = (hash(key)%UInt32) | 0x80000000 desired_index(hash, sz) = (hash & (sz - 1)) + 1 function calculate_distance(h::RobinDict{K, V}, index) where {K, V} @assert isslotfilled(h, index) sz = length(h.keys) @inbounds index_init = desired_index(h.hashes[index], sz) return (index - index_init + sz) & (sz - 1) end # insert algorithm function rh_insert!(h::RobinDict{K, V}, key::K, val::V) where {K, V} sz = length(h.keys) (h.count > ROBIN_DICT_LOAD_FACTOR * sz) && rehash!(h, sz<<2) ##CHUNK 7 if h.idxfloor == 0 h.idxfloor = index_curr else h.idxfloor = min(h.idxfloor, index_curr) end return index_curr end function rh_insert_for_rehash!(h_new::RobinDict{K, V}, key::K, val::V, hash::UInt32) where {K, V} # table full @assert h_new.count != length(h_new.keys) ckey, cval, chash = key, val, hash sz = length(h_new.keys) index_init = desired_index(chash, sz) index_curr = index_init probe_distance = 0 probe_current = 0 ##CHUNK 8 newsz = _tablesz(newsz) if h.count == 0 resize!(h.keys, newsz) resize!(h.vals, newsz) resize!(h.hashes, newsz) fill!(h.hashes, 0) h.count = 0 h.idxfloor = 0 return h end h.keys = Vector{K}(undef, newsz) h.vals = Vector{V}(undef, newsz) h.hashes = zeros(UInt32,newsz) h.count = 0 h.idxfloor = 0 for i = 1:sz @inbounds if oldh[i] != 0 k = oldk[i] #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) ##CHUNK 2 if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end function rehash!(h::SwissDict{K,V}, newsz = length(h.keys)) where {K, V} olds = h.slots oldk = h.keys oldv = h.vals sz = length(oldk) newsz = _tablesz(newsz) (newsz*SWISS_DICT_LOAD_FACTOR) > h.count || (newsz <<= 1) h.age += 1 h.idxfloor = 1 if h.count == 0 resize!(h.slots, newsz>>4) fill!(h.slots, _expand16(0x00)) resize!(h.keys, newsz) resize!(h.vals, newsz) Based on the information above, please generate test code for the following function: function Base.empty!(h::SwissDict{K,V}) where {K, V} fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function Base.empty!(h::SwissDict{K,V}) where {K, V}\n fill!(h.slots, _expand16(0x00))\n sz = length(h.keys)\n empty!(h.keys)\n empty!(h.vals)\n resize!(h.keys, sz)\n resize!(h.vals, sz)\n h.nbfull = 0\n h.count = 0\n h.age += 1\n h.idxfloor = 1\n return h\nend", "task_id": "DataStructures/61" }
370
382
DataStructures.jl
61
function Base.empty!(h::SwissDict{K,V}) where {K, V} fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end
Base.empty!(h::SwissDict{K,V}) where {K, V}
[ 370, 382 ]
function Base.empty!(h::SwissDict{K,V}) where {K, V} fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 @inbounds h.dict[key] = Int32(nk) h.count += 1 end function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h ##CHUNK 2 empty!(h.vals) h.count = 0 return h end function _setindex!(h::OrderedRobinDict, v, key) hk, hv = h.keys, h.vals push!(hk, key) push!(hv, v) nk = length(hk) @inbounds h.dict[key] = Int32(nk) h.count += 1 end function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.setindex!(h::RobinDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) isequal(key, key0) || throw(ArgumentError("$key0 is not a valid key for type $K")) _setindex!(h, key, v0) end function _setindex!(h::RobinDict{K,V}, key::K, v0) where {K, V} v = convert(V, v0) index = rh_insert!(h, key, v) @assert index > 0 return h end """ empty!(collection) -> collection Remove all elements from a `collection`. # Examples ##CHUNK 2 return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) return v end function Base.getindex(h::RobinDict{K, V}, key) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index] end """ get(collection, key, default) ##CHUNK 3 # grow at least 25% if newsz < (oldsz*5)>>2 return d end rehash!(d, newsz) end Base.@propagate_inbounds isslotfilled(h::RobinDict, index) = (h.hashes[index] != 0) Base.@propagate_inbounds isslotempty(h::RobinDict, index) = (h.hashes[index] == 0) function Base.setindex!(h::RobinDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) isequal(key, key0) || throw(ArgumentError("$key0 is not a valid key for type $K")) _setindex!(h, key, v0) end function _setindex!(h::RobinDict{K,V}, key::K, v0) where {K, V} v = convert(V, v0) index = rh_insert!(h, key, v) ##CHUNK 4 get!(dict, key) do # default value calculated here time() end ``` """ Base.get!(f::Function, collection, key) function Base.get!(default::Callable, h::RobinDict{K,V}, key0::K) where {K, V} key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) ##CHUNK 2 v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end function Base.getindex(h::SwissDict{K,V}, key) where {K, V} index = ht_keyindex(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index]::V end """ ##CHUNK 3 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) ##CHUNK 4 This is intended to be called using `do` block syntax: ```julia get!(dict, key) do # default value calculated here time() end ``` """ function Base.get!(default::Callable, h::SwissDict{K,V}, key0) where {K, V} key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age Based on the information above, please generate test code for the following function: function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return h end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V}\n v = convert(V, v0)\n index, tag = ht_keyindex2!(h, key)\n\n if index > 0\n h.age += 1\n @inbounds h.keys[index] = key\n @inbounds h.vals[index] = v\n else\n _setindex!(h, v, key, -index, tag)\n end\n\n return h\nend", "task_id": "DataStructures/62" }
389
402
DataStructures.jl
62
function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return h end
_setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V}
[ 389, 402 ]
function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return h end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) return v end function Base.getindex(h::RobinDict{K, V}, key) where {K, V} index = rh_search(h, key) @inbounds return (index < 0) ? throw(KeyError(key)) : h.vals[index] end """ get(collection, key, default) ##CHUNK 2 get!(dict, key) do # default value calculated here time() end ``` """ Base.get!(f::Function, collection, key) function Base.get!(default::Callable, h::RobinDict{K,V}, key0::K) where {K, V} key = convert(K, key0) return _get!(default, h, key) end function _get!(default::Callable, h::RobinDict{K,V}, key::K) where V where K index = rh_search(h, key) index > 0 && return h.vals[index] v = convert(V, default()) rh_insert!(h, key, v) #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 """ function Base.get!(default::Base.Callable, h::OrderedRobinDict{K,V}, key0) where {K,V} index = get(h.dict, key0, -2) index > 0 && return @inbounds h.vals[index] v = convert(V, default()) setindex!(h, v, key0) return v end function Base.getindex(h::OrderedRobinDict{K,V}, key) where {K,V} index = get(h.dict, key, -1) return (index < 0) ? throw(KeyError(key)) : @inbounds h.vals[index]::V end """ get(collection, key, default) Return the value stored for the given key, or the given default value if no mapping for the key is present. ##CHUNK 2 @inbounds h.dict[key] = Int32(nk) h.count += 1 end function Base.setindex!(h::OrderedRobinDict{K, V}, v0, key0) where {K,V} key = convert(K, key0) v = convert(V, v0) index = get(h.dict, key, -2) if index < 0 _setindex!(h, v0, key0) else @assert haskey(h, key0) @inbounds orig_v = h.vals[index] !isequal(orig_v, v0) && (@inbounds h.vals[index] = v0) end check_for_rehash(h) && rehash!(h) return h ##CHUNK 3 Return the value stored for the given key, or if no mapping for the key is present, store `key => f()`, and return `f()`. This is intended to be called using `do` block syntax: ```julia get!(dict, key) do # default value calculated here time() end ``` """ function Base.get!(default::Base.Callable, h::OrderedRobinDict{K,V}, key0) where {K,V} index = get(h.dict, key0, -2) index > 0 && return @inbounds h.vals[index] v = convert(V, default()) setindex!(h, v, key0) return v end #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end ##CHUNK 2 index, tag = ht_keyindex2!(h, key) if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return h end """ get!(collection, key, default) Return the value stored for the given key, or if no mapping for the key is present, store `key => default`, and return `default`. # Examples ##CHUNK 3 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key @inbounds h.vals[index] = v h.count += 1 h.age += 1 so = _slotget(h.slots, index) h.nbfull += (iszero(index & 0x0f) & (so==0x00)) _slotset!(h.slots, tag, index) if index < h.idxfloor h.idxfloor = index end maybe_rehash_grow!(h) ##CHUNK 4 fill!(h.slots, _expand16(0x00)) sz = length(h.keys) empty!(h.keys) empty!(h.vals) resize!(h.keys, sz) resize!(h.vals, sz) h.nbfull = 0 h.count = 0 h.age += 1 h.idxfloor = 1 return h end function Base.setindex!(h::SwissDict{K,V}, v0, key0) where {K, V} key = convert(K, key0) _setindex!(h, v0, key) end function _setindex!(h::SwissDict{K,V}, v0, key::K) where {K, V} v = convert(V, v0) ##CHUNK 5 cands = _blsr(cands) end done && break i = (i+1) & (sz-1) end i = i0 & (sz-1) @inbounds while true msk = slots[i+1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 return -idx, tag end i = (i+1) & (sz-1) end end function _setindex!(h::SwissDict, v, key, index, tag) @inbounds h.keys[index] = key Based on the information above, please generate test code for the following function: function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V}\n index, tag = ht_keyindex2!(h, key)\n\n index > 0 && return @inbounds h.vals[index]\n\n age0 = h.age\n v = convert(V, default())\n if h.age != age0\n index, tag = ht_keyindex2!(h, key)\n end\n if index > 0\n h.age += 1\n @inbounds h.keys[index] = key\n @inbounds h.vals[index] = v\n else\n _setindex!(h, v, key, -index, tag)\n end\n return v\nend", "task_id": "DataStructures/63" }
449
467
DataStructures.jl
63
function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end
_get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V}
[ 449, 467 ]
function _get!(default::Callable, h::SwissDict{K,V}, key::K) where {K, V} index, tag = ht_keyindex2!(h, key) index > 0 && return @inbounds h.vals[index] age0 = h.age v = convert(V, default()) if h.age != age0 index, tag = ht_keyindex2!(h, key) end if index > 0 h.age += 1 @inbounds h.keys[index] = key @inbounds h.vals[index] = v else _setindex!(h, v, key, -index, tag) end return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 index = rh_search(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::RobinDict) isempty(h) && throw(ArgumentError("dict must be non-empty")) idx = h.idxfloor @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] rh_delete!(h, idx) return key => val end """ delete!(collection, key) Delete the mapping for the given key in a collection, and return the collection. # Examples ```jldoctest ##CHUNK 2 julia> pop!(d, "d") ERROR: KeyError: key "d" not found [...] julia> pop!(d, "e", 4) 4 ``` """ function Base.pop!(h::RobinDict{K, V}, key0, default) where {K, V} key = convert(K, key0) index = rh_search(h, key) return index > 0 ? _pop!(h, index) : default end function Base.pop!(h::RobinDict) isempty(h) && throw(ArgumentError("dict must be non-empty")) idx = h.idxfloor @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] rh_delete!(h, idx) ##CHUNK 3 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end function _pop!(h::RobinDict, index) @inbounds val = h.vals[index] rh_delete!(h, index) return val end function Base.pop!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) return index > 0 ? _pop!(h, index) : throw(KeyError(key)) end """ pop!(collection, key[, default]) ##CHUNK 4 curr = next next = (next & (sz-1)) + 1 end #curr is at the last position, reset back to normal isbitstype(K) || isbitsunion(K) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.keys, curr-1) isbitstype(V) || isbitsunion(V) || ccall(:jl_arrayunset, Cvoid, (Any, UInt), h.vals, curr-1) @inbounds h.hashes[curr] = 0x0 h.count -= 1 # this is necessary because key at idxfloor might get deleted h.idxfloor = get_next_filled(h, h.idxfloor) return h end function _pop!(h::RobinDict, index) @inbounds val = h.vals[index] rh_delete!(h, index) return val end #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 index = get(h.dict, key, -1) return (index < 0) ? default : h.keys[index]::K end Base.@propagate_inbounds isslotfilled(h::OrderedRobinDict, index) = (h.dict[h.keys[index]] == index) function _pop!(h::OrderedRobinDict, index) @inbounds val = h.vals[index] _delete!(h, index) return val end function Base.pop!(h::OrderedRobinDict) check_for_rehash(h) && rehash!(h) index = length(h.keys) while (index > 0) isslotfilled(h, index) && break index -= 1 end index == 0 && rehash!(h) #CURRENT FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 if index > 0 _delete!(h, index) end maybe_rehash_shrink!(h) return h end Base.@propagate_inbounds function Base.iterate(h::SwissDict, state = h.idxfloor) is = _iterslots(h, state) is === nothing && return nothing i, s = is @inbounds p = h.keys[i] => h.vals[i] return (p, s) end Base.@propagate_inbounds function Base.iterate(v::Union{KeySet{<:Any, <:SwissDict}, Base.ValueIterator{<:SwissDict}}, state=v.dict.idxfloor) is = _iterslots(v.dict, state) is === nothing && return nothing i, s = is return (v isa KeySet ? v.dict.keys[i] : v.dict.vals[i], s) ##CHUNK 2 "a" => 1 "b" => 2 julia> delete!(d, "b") SwissDict{String, Int64} with 1 entry: "a" => 1 ``` """ function Base.delete!(h::SwissDict, key) index = ht_keyindex(h, key) if index > 0 _delete!(h, index) end maybe_rehash_shrink!(h) return h end Base.@propagate_inbounds function Base.iterate(h::SwissDict, state = h.idxfloor) is = _iterslots(h, state) is === nothing && return nothing ##CHUNK 3 h.nbfull = 0 return h end nssz = newsz>>4 slots = fill(_expand16(0x00), nssz) keys = Vector{K}(undef, newsz) vals = Vector{V}(undef, newsz) age0 = h.age nbfull = 0 is = _iterslots(h, 1) count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] ##CHUNK 4 count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k ##CHUNK 5 end function _pop!(h::SwissDict, index) @inbounds val = h.vals[index] _delete!(h, index) maybe_rehash_shrink!(h) return val end """ pop!(collection, key[, default]) Delete and return the mapping for `key` if it exists in `collection`, otherwise return `default`, or throw an error if `default` is not specified. # Examples ```jldoctest julia> d = SwissDict("a"=>1, "b"=>2, "c"=>3); julia> pop!(d, "a") Based on the information above, please generate test code for the following function: function Base.pop!(h::SwissDict) isempty(h) && throw(ArgumentError("SwissDict must be non-empty")) is = _iterslots(h, h.idxfloor) @assert is !== nothing idx, s = is @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] _delete!(h, idx) h.idxfloor = idx return key => val end
{ "fpath_tuple": [ "DataStructures.jl", "src", "swiss_dict.jl" ], "ground_truth": "function Base.pop!(h::SwissDict)\n isempty(h) && throw(ArgumentError(\"SwissDict must be non-empty\"))\n is = _iterslots(h, h.idxfloor)\n @assert is !== nothing\n idx, s = is\n @inbounds key = h.keys[idx]\n @inbounds val = h.vals[idx]\n _delete!(h, idx)\n h.idxfloor = idx\n return key => val\nend", "task_id": "DataStructures/64" }
601
611
DataStructures.jl
64
function Base.pop!(h::SwissDict) isempty(h) && throw(ArgumentError("SwissDict must be non-empty")) is = _iterslots(h, h.idxfloor) @assert is !== nothing idx, s = is @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] _delete!(h, idx) h.idxfloor = idx return key => val end
Base.pop!(h::SwissDict)
[ 601, 611 ]
function Base.pop!(h::SwissDict) isempty(h) && throw(ArgumentError("SwissDict must be non-empty")) is = _iterslots(h, h.idxfloor) @assert is !== nothing idx, s = is @inbounds key = h.keys[idx] @inbounds val = h.vals[idx] _delete!(h, idx) h.idxfloor = idx return key => val end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/ordered_robin_dict.jl ##CHUNK 1 end function OrderedRobinDict{K,V}(kv) where {K, V} h = OrderedRobinDict{K,V}() for (k,v) in kv h[k] = v end return h end OrderedRobinDict{K,V}(p::Pair) where {K,V} = setindex!(OrderedRobinDict{K,V}(), p.second, p.first) function OrderedRobinDict{K,V}(ps::Pair...) where V where K h = OrderedRobinDict{K,V}() sizehint!(h, length(ps)) for p in ps h[p.first] = p.second end return h end end #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 for (k,v) in kv h[k] = v end return h end SwissDict{K,V}(p::Pair) where {K,V} = setindex!(SwissDict{K,V}(), p.second, p.first) function SwissDict{K,V}(ps::Pair...) where {K, V} h = SwissDict{K,V}() sizehint!(h, length(ps)) for p in ps h[p.first] = p.second end return h end SwissDict() = SwissDict{Any,Any}() SwissDict(kv::Tuple{}) = SwissDict() Base.copy(d::SwissDict) = SwissDict(d) Base.empty(d::SwissDict, ::Type{K}, ::Type{V}) where {K, V} = SwissDict{K, V}() SwissDict(ps::Pair{K,V}...) where {K,V} = SwissDict{K,V}(ps) #FILE: DataStructures.jl/src/multi_dict.jl ##CHUNK 1 MultiDict() = MultiDict{Any,Any}() MultiDict(kv::Tuple{}) = MultiDict() MultiDict(kvs) = multi_dict_with_eltype(kvs, eltype(kvs)) multi_dict_with_eltype(kvs, ::Type{Tuple{K,Vector{V}}}) where {K,V} = MultiDict{K,V}(kvs) function multi_dict_with_eltype(kvs, ::Type{Tuple{K,V}}) where {K,V} md = MultiDict{K,V}() for (k,v) in kvs insert!(md, k, v) end return md end multi_dict_with_eltype(kvs, t) = MultiDict{Any,Any}(kvs) MultiDict(kv::AbstractArray{Pair{K,V}}) where {K,V} = MultiDict(kv...) function MultiDict(ps::Pair{K,V}...) where {K,V} md = MultiDict{K,V}() for (k,v) in ps insert!(md, k, v) #CURRENT FILE: DataStructures.jl/src/trie.jl ##CHUNK 1 node != nothing && node.is_key end function Base.get(t::Trie, key, notfound) node = subtrie(t, key) if node != nothing && node.is_key return node.value end return notfound end _concat(prefix::String, char::Char) = string(prefix, char) _concat(prefix::Vector{T}, char::T) where {T} = vcat(prefix, char) _empty_prefix(::Trie{Char,V}) where {V} = "" _empty_prefix(::Trie{K,V}) where {K,V} = K[] function keys_with_prefix(t::Trie, prefix) st = subtrie(t, prefix) ##CHUNK 2 ``` """ function find_prefixes(t::Trie, str::T) where {T} prefixes = T[] it = partial_path(t, str) idx = 0 for t in it if t.is_key push!(prefixes, str[firstindex(str):idx]) end idx = nextind(str, idx) end return prefixes end ##CHUNK 3 function Base.setindex!(t::Trie{K,V}, val, key) where {K,V} value = convert(V, val) # we don't want to iterate before finding out it fails node = t for char in key node = get!(Trie{K,V}, node.children, char) end node.is_key = true node.value = value end function Base.getindex(t::Trie, key) node = subtrie(t, key) if node != nothing && node.is_key return node.value end throw(KeyError("key not found: $key")) end function subtrie(t::Trie, prefix) ##CHUNK 4 end function Trie{K,V}(ks, vs) where {K,V} return Trie{K,V}(zip(ks, vs)) end function Trie{K,V}(kv) where {K,V} t = Trie{K,V}() for (k,v) in kv t[k] = v end return t end end Trie() = Trie{Any,Any}() Trie(ks::AbstractVector{K}, vs::AbstractVector{V}) where {K,V} = Trie{eltype(K),V}(ks, vs) Trie(kv::AbstractVector{Tuple{K,V}}) where {K,V} = Trie{eltype(K),V}(kv) Trie(kv::AbstractDict{K,V}) where {K,V} = Trie{eltype(K),V}(kv) Trie(ks::AbstractVector{K}) where {K} = Trie{eltype(K),Nothing}(ks, similar(ks, Nothing)) ##CHUNK 5 function Base.getindex(t::Trie, key) node = subtrie(t, key) if node != nothing && node.is_key return node.value end throw(KeyError("key not found: $key")) end function subtrie(t::Trie, prefix) node = t for char in prefix node = get(node.children, char, nothing) isnothing(node) && return nothing end return node end function Base.haskey(t::Trie, key) node = subtrie(t, key) ##CHUNK 6 end return t end end Trie() = Trie{Any,Any}() Trie(ks::AbstractVector{K}, vs::AbstractVector{V}) where {K,V} = Trie{eltype(K),V}(ks, vs) Trie(kv::AbstractVector{Tuple{K,V}}) where {K,V} = Trie{eltype(K),V}(kv) Trie(kv::AbstractDict{K,V}) where {K,V} = Trie{eltype(K),V}(kv) Trie(ks::AbstractVector{K}) where {K} = Trie{eltype(K),Nothing}(ks, similar(ks, Nothing)) function Base.setindex!(t::Trie{K,V}, val, key) where {K,V} value = convert(V, val) # we don't want to iterate before finding out it fails node = t for char in key node = get!(Trie{K,V}, node.children, char) end node.is_key = true node.value = value end ##CHUNK 7 mutable struct Trie{K,V} value::V children::Dict{K,Trie{K,V}} is_key::Bool function Trie{K,V}() where {K,V} self = new{K,V}() self.children = Dict{K,Trie{K,V}}() self.is_key = false return self end function Trie{K,V}(ks, vs) where {K,V} return Trie{K,V}(zip(ks, vs)) end function Trie{K,V}(kv) where {K,V} t = Trie{K,V}() for (k,v) in kv t[k] = v Based on the information above, please generate test code for the following function: function Base.keys(t::Trie{K,V}, prefix=_empty_prefix(t), found=Vector{typeof(prefix)}()) where {K,V} if t.is_key push!(found, prefix) end for (char,child) in t.children keys(child, _concat(prefix, char), found) end return found end
{ "fpath_tuple": [ "DataStructures.jl", "src", "trie.jl" ], "ground_truth": "function Base.keys(t::Trie{K,V},\n prefix=_empty_prefix(t),\n found=Vector{typeof(prefix)}()) where {K,V}\n if t.is_key\n push!(found, prefix)\n end\n for (char,child) in t.children\n keys(child, _concat(prefix, char), found)\n end\n return found\nend", "task_id": "DataStructures/65" }
78
88
DataStructures.jl
65
function Base.keys(t::Trie{K,V}, prefix=_empty_prefix(t), found=Vector{typeof(prefix)}()) where {K,V} if t.is_key push!(found, prefix) end for (char,child) in t.children keys(child, _concat(prefix, char), found) end return found end
Base.keys(t::Trie{K,V}, prefix=_empty_prefix(t), found=Vector{typeof(prefix)}()) where {K,V}
[ 78, 88 ]
function Base.keys(t::Trie{K,V}, prefix=_empty_prefix(t), found=Vector{typeof(prefix)}()) where {K,V} if t.is_key push!(found, prefix) end for (char,child) in t.children keys(child, _concat(prefix, char), found) end return found end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_trie.jl ##CHUNK 1 @test collect(partial_path(t, "東京都")) == [t0, t1, t2, t3] @test collect(partial_path(t, "東京都渋谷区")) == [t0, t1, t2, t3] @test collect(partial_path(t, "東京")) == [t0, t1, t2] @test collect(partial_path(t, "東京スカイツリー")) == [t0, t1, t2] end @testset "find_prefixes" begin t = Trie(["A", "ABC", "ABD", "BCD"]) prefixes = find_prefixes(t, "ABCDE") @test prefixes == ["A", "ABC"] end @testset "find_prefixes non-ascii" begin t = Trie(["東京都", "東京都渋谷区", "東京都新宿区"]) prefixes = find_prefixes(t, "東京都渋谷区東") @test prefixes == ["東京都", "東京都渋谷区"] end @testset "non-string indexing" begin t = Trie{Int,Int}() ##CHUNK 2 end @testset "find_prefixes non-ascii" begin t = Trie(["東京都", "東京都渋谷区", "東京都新宿区"]) prefixes = find_prefixes(t, "東京都渋谷区東") @test prefixes == ["東京都", "東京都渋谷区"] end @testset "non-string indexing" begin t = Trie{Int,Int}() t[[1,2,3,4]] = 1 t[[1,2]] = 2 @test haskey(t, [1,2]) @test get(t, [1,2], nothing) == 2 st = subtrie(t, [1,2,3]) @test keys(st) == [[4]] @test st[[4]] == 1 @test find_prefixes(t, [1,2,3,5]) == [[1,2]] @test find_prefixes(t, 1:3) == [1:2] end ##CHUNK 3 @test collect(partial_path(t, "roa")) == [t0, t1, t2] end @testset "partial_path iterator non-ascii" begin t = Trie(["東京都"]) t0 = t t1 = t0.children['東'] t2 = t1.children['京'] t3 = t2.children['都'] @test collect(partial_path(t, "西")) == [t0] @test collect(partial_path(t, "東京都")) == [t0, t1, t2, t3] @test collect(partial_path(t, "東京都渋谷区")) == [t0, t1, t2, t3] @test collect(partial_path(t, "東京")) == [t0, t1, t2] @test collect(partial_path(t, "東京スカイツリー")) == [t0, t1, t2] end @testset "find_prefixes" begin t = Trie(["A", "ABC", "ABD", "BCD"]) prefixes = find_prefixes(t, "ABCDE") @test prefixes == ["A", "ABC"] #FILE: DataStructures.jl/src/avl_tree.jl ##CHUNK 1 function traverse_tree(node::AVLTreeNode_or_null, idx) if (node != nothing) L = get_subsize(node.leftChild) if idx <= L return traverse_tree(node.leftChild, idx) elseif idx == L + 1 return node.data else return traverse_tree(node.rightChild, idx - L - 1) end end end value = traverse_tree(tree.root, ind) return value end #FILE: DataStructures.jl/src/swiss_dict.jl ##CHUNK 1 count = 0 @inbounds while is !== nothing i, s = is k = oldk[i] v = oldv[i] i0, t = _hashtag(hash(k)) i = i0 & (nssz-1) idx = 0 while true msk = slots[i + 1] cands = _find_free(msk) if cands != 0 off = trailing_zeros(cands) idx = i*16 + off + 1 break end i = (i+1) & (nssz-1) end _slotset!(slots, t, idx) keys[idx] = k #FILE: DataStructures.jl/src/int_set.jl ##CHUNK 1 idx = n+1 if 1 <= idx <= length(s.bits) unsafe_getindex(s.bits, idx) != s.inverse else ifelse((idx <= 0) | (idx > typemax(Int)), false, s.inverse) end end function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert # i+1 could rollover causing a BoundsError in findnext/findnextnot nextidx = i == typemax(Int) ? 0 : something(findnextnot(s.bits, i+1), 0) # Extend indices beyond the length of the bits since it is inverted nextidx = nextidx == 0 ? max(i, length(s.bits))+1 : nextidx else nextidx = i == typemax(Int) ? 0 : something(findnext(s.bits, i+1), 0) end return nextidx end ##CHUNK 2 end function Base.symdiff!(s1::IntSet, s2::IntSet) e = _matchlength!(s1.bits, length(s2.bits)) map!(⊻, s1.bits, s1.bits, s2.bits) s2.inverse && (s1.inverse = !s1.inverse) append!(s1.bits, e) return s1 end function Base.in(n::Integer, s::IntSet) idx = n+1 if 1 <= idx <= length(s.bits) unsafe_getindex(s.bits, idx) != s.inverse else ifelse((idx <= 0) | (idx > typemax(Int)), false, s.inverse) end end function findnextidx(s::IntSet, i::Int, invert=false) if s.inverse ⊻ invert #FILE: DataStructures.jl/src/circular_buffer.jl ##CHUNK 1 cb.length = 0 return cb end Base.@propagate_inbounds function _buffer_index_checked(cb::CircularBuffer, i::Int) @boundscheck if i < 1 || i > cb.length throw(BoundsError(cb, i)) end _buffer_index(cb, i) end @inline function _buffer_index(cb::CircularBuffer, i::Int) n = cb.capacity idx = cb.first + i - 1 return ifelse(idx > n, idx - n, idx) end """ cb[i] #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 "b" => 3 ``` """ function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end function Base.popat!(pq::PriorityQueue, key) idx = pq.index[key] force_up!(pq, idx) popfirst!(pq) end #CURRENT FILE: DataStructures.jl/src/trie.jl ##CHUNK 1 if i == 0 return it.t, (it.t, firstindex(it.str)) elseif i > lastindex(it.str) || !(it.str[i] in keys(t.children)) return nothing else t = t.children[it.str[i]] return (t, (t, nextind(it.str, i))) end end partial_path(t::Trie, str) = TrieIterator(t, str) Base.IteratorSize(::Type{TrieIterator}) = Base.SizeUnknown() """ find_prefixes(t::Trie, str) Find all keys from the `Trie` that are prefix of the given string # Examples ```julia-repl Based on the information above, please generate test code for the following function: function find_prefixes(t::Trie, str::T) where {T} prefixes = T[] it = partial_path(t, str) idx = 0 for t in it if t.is_key push!(prefixes, str[firstindex(str):idx]) end idx = nextind(str, idx) end return prefixes end
{ "fpath_tuple": [ "DataStructures.jl", "src", "trie.jl" ], "ground_truth": "function find_prefixes(t::Trie, str::T) where {T}\n prefixes = T[]\n it = partial_path(t, str)\n idx = 0\n for t in it\n if t.is_key\n push!(prefixes, str[firstindex(str):idx])\n end\n idx = nextind(str, idx)\n end\n return prefixes\nend", "task_id": "DataStructures/66" }
154
165
DataStructures.jl
66
function find_prefixes(t::Trie, str::T) where {T} prefixes = T[] it = partial_path(t, str) idx = 0 for t in it if t.is_key push!(prefixes, str[firstindex(str):idx]) end idx = nextind(str, idx) end return prefixes end
find_prefixes(t::Trie, str::T) where {T}
[ 154, 165 ]
function find_prefixes(t::Trie, str::T) where {T} prefixes = T[] it = partial_path(t, str) idx = 0 for t in it if t.is_key push!(prefixes, str[firstindex(str):idx]) end idx = nextind(str, idx) end return prefixes end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/mutable_list.jl ##CHUNK 1 return l.node.next.data end function Base.last(l::MutableLinkedList) isempty(l) && throw(ArgumentError("List is empty")) return l.node.prev.data end Base.:(==)(l1::MutableLinkedList{T}, l2::MutableLinkedList{S}) where {T,S} = false function Base.:(==)(l1::MutableLinkedList{T}, l2::MutableLinkedList{T}) where T length(l1) == length(l2) || return false for (i, j) in zip(l1, l2) i == j || return false end return true end function Base.map(f::Base.Callable, l::MutableLinkedList{T}) where T if isempty(l) && f isa Function #CURRENT FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 return valtree end Base.@propagate_inbounds function _minmax_heap_bubble_up!(A::AbstractVector, i::Integer) if on_minlevel(i) if i > 1 && A[i] > A[hparent(i)] # swap to parent and bubble up max tmp = A[i] A[i] = A[hparent(i)] A[hparent(i)] = tmp _minmax_heap_bubble_up!(A, hparent(i), Reverse) else # bubble up min _minmax_heap_bubble_up!(A, i, Forward) end else # max level if i > 1 && A[i] < A[hparent(i)] # swap to parent and bubble up min ##CHUNK 2 # # core implementation # ################################################ function _make_binary_minmax_heap(xs) valtree = copy(xs) for i in length(xs):-1:1 @inbounds _minmax_heap_trickle_down!(valtree, i) end return valtree end Base.@propagate_inbounds function _minmax_heap_bubble_up!(A::AbstractVector, i::Integer) if on_minlevel(i) if i > 1 && A[i] > A[hparent(i)] # swap to parent and bubble up max tmp = A[i] A[i] = A[hparent(i)] A[hparent(i)] = tmp ##CHUNK 3 _minmax_heap_bubble_up!(A, hparent(i), Reverse) else # bubble up min _minmax_heap_bubble_up!(A, i, Forward) end else # max level if i > 1 && A[i] < A[hparent(i)] # swap to parent and bubble up min tmp = A[i] A[i] = A[hparent(i)] A[hparent(i)] = tmp _minmax_heap_bubble_up!(A, hparent(i), Forward) else # bubble up max _minmax_heap_bubble_up!(A, i, Reverse) end end end ##CHUNK 4 end Base.@propagate_inbounds function _minmax_heap_trickle_down!(A::AbstractVector, i::Integer) if on_minlevel(i) _minmax_heap_trickle_down!(A, i, Forward) else _minmax_heap_trickle_down!(A, i, Reverse) end end Base.@propagate_inbounds function _minmax_heap_trickle_down!(A::AbstractVector, i::Integer, o::Ordering, x=A[i]) if haschildren(i, A) # get the index of the extremum (min or max) descendant extremum = o === Forward ? minimum : maximum _, m = extremum((A[j], j) for j in children_and_grandchildren(length(A), i)) if isgrandchild(m, i) if lt(o, A[m], A[i]) A[i] = A[m] ##CHUNK 5 tmp = A[i] A[i] = A[hparent(i)] A[hparent(i)] = tmp _minmax_heap_bubble_up!(A, hparent(i), Forward) else # bubble up max _minmax_heap_bubble_up!(A, i, Reverse) end end end Base.@propagate_inbounds function _minmax_heap_bubble_up!(A::AbstractVector, i::Integer, o::Ordering, x=A[i]) if hasgrandparent(i) gparent = hparent(hparent(i)) if lt(o, x, A[gparent]) A[i] = A[gparent] A[gparent] = x _minmax_heap_bubble_up!(A, gparent, o) end end ##CHUNK 6 Base.@propagate_inbounds function _minmax_heap_trickle_down!(A::AbstractVector, i::Integer, o::Ordering, x=A[i]) if haschildren(i, A) # get the index of the extremum (min or max) descendant extremum = o === Forward ? minimum : maximum _, m = extremum((A[j], j) for j in children_and_grandchildren(length(A), i)) if isgrandchild(m, i) if lt(o, A[m], A[i]) A[i] = A[m] A[m] = x if lt(o, A[hparent(m)], A[m]) t = A[m] A[m] = A[hparent(m)] A[hparent(m)] = t end _minmax_heap_trickle_down!(A, m, o) end else if lt(o, A[m], A[i]) ##CHUNK 7 A[i] = A[m] A[m] = x end end end end ################################################ # # utilities # ################################################ @inline level(i) = floor(Int, log2(i)) @inline lchild(i) = 2*i @inline rchild(i) = 2*i+1 @inline children(i) = (lchild(i), rchild(i)) @inline hparent(i) = i ÷ 2 @inline on_minlevel(i) = level(i) % 2 == 0 @inline haschildren(i, A) = lchild(i) ≤ length(A) ##CHUNK 8 Base.@propagate_inbounds function _minmax_heap_bubble_up!(A::AbstractVector, i::Integer, o::Ordering, x=A[i]) if hasgrandparent(i) gparent = hparent(hparent(i)) if lt(o, x, A[gparent]) A[i] = A[gparent] A[gparent] = x _minmax_heap_bubble_up!(A, gparent, o) end end end Base.@propagate_inbounds function _minmax_heap_trickle_down!(A::AbstractVector, i::Integer) if on_minlevel(i) _minmax_heap_trickle_down!(A, i, Forward) else _minmax_heap_trickle_down!(A, i, Reverse) end end ##CHUNK 9 A[m] = x if lt(o, A[hparent(m)], A[m]) t = A[m] A[m] = A[hparent(m)] A[hparent(m)] = t end _minmax_heap_trickle_down!(A, m, o) end else if lt(o, A[m], A[i]) A[i] = A[m] A[m] = x end end end end ################################################ # # utilities Based on the information above, please generate test code for the following function: function is_minmax_heap(A::AbstractVector) for i in 1:length(A) if on_minlevel(i) # check that A[i] < children A[i] # and grandchildren A[i] for j in children_and_grandchildren(length(A), i) A[i] ≤ A[j] || return false end else # max layer for j in children_and_grandchildren(length(A), i) A[i] ≥ A[j] || return false end end end return true end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps", "minmax_heap.jl" ], "ground_truth": "function is_minmax_heap(A::AbstractVector)\n\n for i in 1:length(A)\n if on_minlevel(i)\n # check that A[i] < children A[i]\n # and grandchildren A[i]\n for j in children_and_grandchildren(length(A), i)\n A[i] ≤ A[j] || return false\n end\n else\n # max layer\n for j in children_and_grandchildren(length(A), i)\n A[i] ≥ A[j] || return false\n end\n end\n end\n return true\nend", "task_id": "DataStructures/67" }
143
160
DataStructures.jl
67
function is_minmax_heap(A::AbstractVector) for i in 1:length(A) if on_minlevel(i) # check that A[i] < children A[i] # and grandchildren A[i] for j in children_and_grandchildren(length(A), i) A[i] ≤ A[j] || return false end else # max layer for j in children_and_grandchildren(length(A), i) A[i] ≥ A[j] || return false end end end return true end
is_minmax_heap(A::AbstractVector)
[ 143, 160 ]
function is_minmax_heap(A::AbstractVector) for i in 1:length(A) if on_minlevel(i) # check that A[i] < children A[i] # and grandchildren A[i] for j in children_and_grandchildren(length(A), i) A[i] ≤ A[j] || return false end else # max layer for j in children_and_grandchildren(length(A), i) A[i] ≥ A[j] || return false end end end return true end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/priorityqueue.jl ##CHUNK 1 "b" => 3 ``` """ function Base.popfirst!(pq::PriorityQueue) x = pq.xs[1] y = pop!(pq.xs) if !isempty(pq) @inbounds pq.xs[1] = y pq.index[y.first] = 1 percolate_down!(pq, 1) end delete!(pq.index, x.first) return x end function Base.popat!(pq::PriorityQueue, key) idx = pq.index[key] force_up!(pq, idx) popfirst!(pq) end #FILE: DataStructures.jl/src/disjoint_set.jl ##CHUNK 1 Assume `x ≠ y` (unsafe). """ function root_union!(s::IntDisjointSet{T}, x::T, y::T) where {T<:Integer} parents = s.parents rks = s.ranks @inbounds xrank = rks[x] @inbounds yrank = rks[y] if xrank < yrank x, y = y, x elseif xrank == yrank rks[x] += one(T) end @inbounds parents[y] = x s.ngroups -= one(T) return x end """ push!(s::IntDisjointSet{T}) #FILE: DataStructures.jl/src/splay_tree.jl ##CHUNK 1 node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild end end node.parent = y if y === nothing tree.root = node elseif node.data < y.data y.leftChild = node else y.rightChild = node ##CHUNK 2 return tree end function Base.push!(tree::SplayTree{K}, d0) where K d = convert(K, d0) is_present = search_node(tree, d) if (is_present !== nothing) && (is_present.data == d) return tree end # only unique keys are inserted node = SplayTreeNode{K}(d) y = nothing x = tree.root while x !== nothing y = x if node.data > x.data x = x.rightChild else x = x.leftChild #FILE: DataStructures.jl/src/deque.jl ##CHUNK 1 isempty(d) && throw(ArgumentError("Deque must be non-empty")) head = d.head @assert head.back >= head.front @inbounds x = head.data[head.front] Base._unsetindex!(head.data, head.front) # see issue/884 head.front += 1 if head.back < head.front if d.nblocks > 1 # release and detach the head block empty!(head.data) d.head = head.next::DequeBlock{T} d.head.prev = d.head d.nblocks -= 1 end end d.len -= 1 return x end #CURRENT FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 Remove the maximum value from the heap. """ function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) end return x end """ popmax!(h::BinaryMinMaxHeap, k::Integer) -> vals Remove up to the `k` largest values from the heap. """ @inline function popmax!(h::BinaryMinMaxHeap, k::Integer) ##CHUNK 2 Remove up to the `k` smallest values from the heap. """ @inline function popmin!(h::BinaryMinMaxHeap, k::Integer) return [popmin!(h) for _ in 1:min(length(h), k)] end """ popmax!(h::BinaryMinMaxHeap) -> max Remove the maximum value from the heap. """ function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) ##CHUNK 3 """ first(h::BinaryMinMaxHeap) Get the first (minimum) of the heap. """ @inline Base.first(h::BinaryMinMaxHeap) = minimum(h) @inline function Base.minimum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end Base.empty!(h::BinaryMinMaxHeap) = (empty!(h.valtree); h) ##CHUNK 4 return [popmax!(h) for _ in 1:min(length(h), k)] end function Base.push!(h::BinaryMinMaxHeap, v) valtree = h.valtree push!(valtree, v) @inbounds _minmax_heap_bubble_up!(valtree, length(valtree)) end """ first(h::BinaryMinMaxHeap) Get the first (minimum) of the heap. """ @inline Base.first(h::BinaryMinMaxHeap) = minimum(h) @inline function Base.minimum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) ##CHUNK 5 return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end Base.empty!(h::BinaryMinMaxHeap) = (empty!(h.valtree); h) """ popall!(h::BinaryMinMaxHeap, ::Ordering = Forward) Remove and return all the elements of `h` according to the given ordering. Default is `Forward` (smallest to largest). """ popall!(h::BinaryMinMaxHeap) = popall!(h, Forward) Based on the information above, please generate test code for the following function: function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps", "minmax_heap.jl" ], "ground_truth": "function popmin!(h::BinaryMinMaxHeap)\n valtree = h.valtree\n !isempty(valtree) || throw(ArgumentError(\"heap must be non-empty\"))\n @inbounds x = valtree[1]\n y = pop!(valtree)\n if !isempty(valtree)\n @inbounds valtree[1] = y\n @inbounds _minmax_heap_trickle_down!(valtree, 1)\n end\n return x\nend", "task_id": "DataStructures/68" }
187
197
DataStructures.jl
68
function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end
popmin!(h::BinaryMinMaxHeap)
[ 187, 197 ]
function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/src/robin_dict.jl ##CHUNK 1 function Base.delete!(h::RobinDict{K, V}, key0) where {K, V} key = convert(K, key0) index = rh_search(h, key) if index > 0 rh_delete!(h, index) end return h end function get_next_filled(h::RobinDict, i) L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end ##CHUNK 2 L = length(h.keys) (1 <= i <= L) || return 0 for j = i:L @inbounds if isslotfilled(h, j) return j end end return 0 end Base.@propagate_inbounds _iterate(t::RobinDict{K,V}, i) where {K,V} = i == 0 ? nothing : (Pair{K,V}(t.keys[i],t.vals[i]), i == typemax(Int) ? 0 : get_next_filled(t, i+1)) Base.@propagate_inbounds function Base.iterate(t::RobinDict) _iterate(t, t.idxfloor) end Base.@propagate_inbounds Base.iterate(t::RobinDict, i) = _iterate(t, get_next_filled(t, i)) function _merge_kvtypes(d, others...) K, V = keytype(d), valtype(d) for other in others K = promote_type(K, keytype(other)) #CURRENT FILE: DataStructures.jl/src/heaps/minmax_heap.jl ##CHUNK 1 """ popmin!(h::BinaryMinMaxHeap) -> min Remove the minimum value from the heap. """ function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end """ ##CHUNK 2 y = pop!(valtree) if !isempty(valtree) @inbounds valtree[1] = y @inbounds _minmax_heap_trickle_down!(valtree, 1) end return x end """ popmin!(h::BinaryMinMaxHeap, k::Integer) -> vals Remove up to the `k` smallest values from the heap. """ @inline function popmin!(h::BinaryMinMaxHeap, k::Integer) return [popmin!(h) for _ in 1:min(length(h), k)] end """ popmax!(h::BinaryMinMaxHeap) -> max ##CHUNK 3 """ pop!(h::BinaryMinMaxHeap) = popmin!(h) """ @inline Base.pop!(h::BinaryMinMaxHeap) = popmin!(h) function Base.sizehint!(h::BinaryMinMaxHeap, s::Integer) sizehint!(h.valtree, s) return h end """ popmin!(h::BinaryMinMaxHeap) -> min Remove the minimum value from the heap. """ function popmin!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x = valtree[1] ##CHUNK 4 """ first(h::BinaryMinMaxHeap) Get the first (minimum) of the heap. """ @inline Base.first(h::BinaryMinMaxHeap) = minimum(h) @inline function Base.minimum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end Base.empty!(h::BinaryMinMaxHeap) = (empty!(h.valtree); h) ##CHUNK 5 return [popmax!(h) for _ in 1:min(length(h), k)] end function Base.push!(h::BinaryMinMaxHeap, v) valtree = h.valtree push!(valtree, v) @inbounds _minmax_heap_bubble_up!(valtree, length(valtree)) end """ first(h::BinaryMinMaxHeap) Get the first (minimum) of the heap. """ @inline Base.first(h::BinaryMinMaxHeap) = minimum(h) @inline function Base.minimum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) ##CHUNK 6 return @inbounds h.valtree[1] end @inline function Base.maximum(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(h) || throw(ArgumentError("heap must be non-empty")) return @inbounds maximum(@views(valtree[1:min(end, 3)])) end Base.empty!(h::BinaryMinMaxHeap) = (empty!(h.valtree); h) """ popall!(h::BinaryMinMaxHeap, ::Ordering = Forward) Remove and return all the elements of `h` according to the given ordering. Default is `Forward` (smallest to largest). """ popall!(h::BinaryMinMaxHeap) = popall!(h, Forward) ##CHUNK 7 function BinaryMinMaxHeap{T}(xs::AbstractVector{T}) where {T} valtree = _make_binary_minmax_heap(xs) new{T}(valtree) end end BinaryMinMaxHeap(xs::AbstractVector{T}) where T = BinaryMinMaxHeap{T}(xs) ################################################ # # core implementation # ################################################ function _make_binary_minmax_heap(xs) valtree = copy(xs) for i in length(xs):-1:1 @inbounds _minmax_heap_trickle_down!(valtree, i) end ##CHUNK 8 # # core implementation # ################################################ function _make_binary_minmax_heap(xs) valtree = copy(xs) for i in length(xs):-1:1 @inbounds _minmax_heap_trickle_down!(valtree, i) end return valtree end Base.@propagate_inbounds function _minmax_heap_bubble_up!(A::AbstractVector, i::Integer) if on_minlevel(i) if i > 1 && A[i] > A[hparent(i)] # swap to parent and bubble up max tmp = A[i] A[i] = A[hparent(i)] A[hparent(i)] = tmp Based on the information above, please generate test code for the following function: function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) end return x end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps", "minmax_heap.jl" ], "ground_truth": "function popmax!(h::BinaryMinMaxHeap)\n valtree = h.valtree\n !isempty(valtree) || throw(ArgumentError(\"heap must be non-empty\"))\n @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3)))\n y = pop!(valtree)\n if !isempty(valtree) && i <= length(valtree)\n @inbounds valtree[i] = y\n @inbounds _minmax_heap_trickle_down!(valtree, i)\n end\n return x\nend", "task_id": "DataStructures/69" }
214
224
DataStructures.jl
69
function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) end return x end
popmax!(h::BinaryMinMaxHeap)
[ 214, 224 ]
function popmax!(h::BinaryMinMaxHeap) valtree = h.valtree !isempty(valtree) || throw(ArgumentError("heap must be non-empty")) @inbounds x, i = maximum(((valtree[j], j) for j in 1:min(length(valtree), 3))) y = pop!(valtree) if !isempty(valtree) && i <= length(valtree) @inbounds valtree[i] = y @inbounds _minmax_heap_trickle_down!(valtree, i) end return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 nodes[nd_id] = MutableBinaryHeapNode(x, i) if Base.lt(ordering, x, v0) _heap_bubble_up!(ordering, nodes, nodemap, nd_id) else _heap_bubble_down!(ordering, nodes, nodemap, nd_id) end end """ delete!{T}(h::MutableBinaryHeap{T}, i::Int) Deletes the element with handle `i` from heap `h` . """ function Base.delete!(h::MutableBinaryHeap{T}, i::Int) where T nd_id = h.node_map[i] _binary_heap_pop!(h.ordering, h.nodes, h.node_map, nd_id) return h end Base.setindex!(h::MutableBinaryHeap, v, i::Int) = update!(h, i, v) ##CHUNK 2 This is equivalent to `h[i]=v`. """ function update!(h::MutableBinaryHeap{T}, i::Int, v) where T nodes = h.nodes nodemap = h.node_map ordering = h.ordering nd_id = nodemap[i] v0 = nodes[nd_id].value x = convert(T, v) nodes[nd_id] = MutableBinaryHeapNode(x, i) if Base.lt(ordering, x, v0) _heap_bubble_up!(ordering, nodes, nodemap, nd_id) else _heap_bubble_down!(ordering, nodes, nodemap, nd_id) end end """ delete!{T}(h::MutableBinaryHeap{T}, i::Int) ##CHUNK 3 # ################################################# function _heap_bubble_up!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value swapped = true # whether swap happens at last step i = nd_id while swapped && i > 1 # nd is not root p = i >> 1 @inbounds nd_p = nodes[p] if Base.lt(ord, v, nd_p.value) # move parent downward @inbounds nodes[i] = nd_p @inbounds nodemap[nd_p.handle] = i ##CHUNK 4 # # interfaces # ################################################# Base.length(h::MutableBinaryHeap) = length(h.nodes) Base.isempty(h::MutableBinaryHeap) = isempty(h.nodes) function Base.push!(h::MutableBinaryHeap{T}, v) where T nodes = h.nodes nodemap = h.node_map i = length(nodemap) + 1 nd_id = length(nodes) + 1 push!(nodes, MutableBinaryHeapNode(convert(T, v), i)) push!(nodemap, nd_id) _heap_bubble_up!(h.ordering, nodes, nodemap, nd_id) return i end ##CHUNK 5 i = p else swapped = false end end if i != nd_id nodes[i] = nd nodemap[nd.handle] = i end end function _heap_bubble_down!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value n = length(nodes) last_parent = n >> 1 ##CHUNK 6 nodes = h.nodes nodemap = h.node_map i = length(nodemap) + 1 nd_id = length(nodes) + 1 push!(nodes, MutableBinaryHeapNode(convert(T, v), i)) push!(nodemap, nd_id) _heap_bubble_up!(h.ordering, nodes, nodemap, nd_id) return i end function Base.empty!(h::MutableBinaryHeap) empty!(h.nodes) empty!(h.node_map) return h end function Base.sizehint!(h::MutableBinaryHeap, s::Integer) sizehint!(h.nodes, s) sizehint!(h.node_map, s) return h ##CHUNK 7 i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end ################################################# # # Binary Heap type and constructors # ################################################# ##CHUNK 8 end function _heap_bubble_down!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value n = length(nodes) last_parent = n >> 1 swapped = true i = nd_id while swapped && i <= last_parent il = i << 1 if il < n # contains both left and right children ir = il + 1 ##CHUNK 9 i = nd_id while swapped && i > 1 # nd is not root p = i >> 1 @inbounds nd_p = nodes[p] if Base.lt(ord, v, nd_p.value) # move parent downward @inbounds nodes[i] = nd_p @inbounds nodemap[nd_p.handle] = i i = p else swapped = false end end if i != nd_id nodes[i] = nd nodemap[nd.handle] = i end ##CHUNK 10 # Binary heap struct MutableBinaryHeapNode{T} value::T handle::Int end ################################################# # # core implementation # ################################################# function _heap_bubble_up!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value swapped = true # whether swap happens at last step Based on the information above, please generate test code for the following function: function _binary_heap_pop!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T # extract node rt = nodes[nd_id] v = rt.value @inbounds nodemap[rt.handle] = 0 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps", "mutable_binary_heap.jl" ], "ground_truth": "function _binary_heap_pop!(ord::Ordering,\n nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T\n\n # extract node\n rt = nodes[nd_id]\n v = rt.value\n @inbounds nodemap[rt.handle] = 0\n\n # if node-to-remove is at end, we can just pop it\n # the same applies to 1-element heaps that are empty after removing the last element\n if nd_id == lastindex(nodes)\n pop!(nodes)\n else\n # move the last node to the position of the node-to-remove\n @inbounds nodes[nd_id] = new_rt = nodes[end]\n pop!(nodes)\n @inbounds nodemap[new_rt.handle] = nd_id\n\n if length(nodes) > 1\n if Base.lt(ord, new_rt.value, v)\n _heap_bubble_up!(ord, nodes, nodemap, nd_id)\n else\n _heap_bubble_down!(ord, nodes, nodemap, nd_id)\n end\n end\n end\n return v\nend", "task_id": "DataStructures/70" }
103
130
DataStructures.jl
70
function _binary_heap_pop!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T # extract node rt = nodes[nd_id] v = rt.value @inbounds nodemap[rt.handle] = 0 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end
_binary_heap_pop!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T
[ 103, 130 ]
function _binary_heap_pop!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int=1) where T # extract node rt = nodes[nd_id] v = rt.value @inbounds nodemap[rt.handle] = 0 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: DataStructures.jl/test/test_mutable_binheap.jl ##CHUNK 1 # Test of binary heaps # auxiliary functions function heap_values(h::MutableBinaryHeap{VT,O}) where {VT,O} n = length(h) nodes = h.nodes @assert length(nodes) == n vs = Vector{VT}(undef, n) for i = 1 : n vs[i] = nodes[i].value end vs end function list_values(h::MutableBinaryHeap{VT,O}) where {VT,O} n = length(h) nodes = h.nodes nodemap = h.node_map vs = Vector{VT}() ##CHUNK 2 vs[i] = nodes[i].value end vs end function list_values(h::MutableBinaryHeap{VT,O}) where {VT,O} n = length(h) nodes = h.nodes nodemap = h.node_map vs = Vector{VT}() for i = 1 : length(nodemap) id = nodemap[i] if id > 0 push!(vs, nodes[id].value) end end vs end function verify_heap(h::MutableBinaryHeap{VT,O}) where {VT,O} ##CHUNK 3 for i = 1 : length(nodemap) id = nodemap[i] if id > 0 push!(vs, nodes[id].value) end end vs end function verify_heap(h::MutableBinaryHeap{VT,O}) where {VT,O} ord = h.ordering nodes = h.nodes n = length(h) m = div(n,2) for i = 1 : m v = nodes[i].value lc = i * 2 if lc <= n if Base.lt(ord, nodes[lc].value, v) return false ##CHUNK 4 # Test of binary heaps # auxiliary functions function heap_values(h::MutableBinaryHeap{VT,O}) where {VT,O} n = length(h) nodes = h.nodes @assert length(nodes) == n vs = Vector{VT}(undef, n) for i = 1 : n #FILE: DataStructures.jl/src/fenwick.jl ##CHUNK 1 """ FenwickTree{T}(n::Integer) where T = FenwickTree{T}(zeros(T, n), n) """ FenwickTree(counts::AbstractArray) Constructs a [`FenwickTree`](https://en.wikipedia.org/wiki/Fenwick_tree) from an array of `counts` """ function FenwickTree(a::AbstractVector{U}) where U n = length(a) tree = FenwickTree{U}(n) @inbounds for i = 1:n inc!(tree, i, a[i]) end tree end Base.length(ft::FenwickTree) = ft.n Base.eltype(::Type{FenwickTree{T}}) where T = T #CURRENT FILE: DataStructures.jl/src/heaps/mutable_binary_heap.jl ##CHUNK 1 """ function update!(h::MutableBinaryHeap{T}, i::Int, v) where T nodes = h.nodes nodemap = h.node_map ordering = h.ordering nd_id = nodemap[i] v0 = nodes[nd_id].value x = convert(T, v) nodes[nd_id] = MutableBinaryHeapNode(x, i) if Base.lt(ordering, x, v0) _heap_bubble_up!(ordering, nodes, nodemap, nd_id) else _heap_bubble_down!(ordering, nodes, nodemap, nd_id) end end """ delete!{T}(h::MutableBinaryHeap{T}, i::Int) ##CHUNK 2 # interfaces # ################################################# Base.length(h::MutableBinaryHeap) = length(h.nodes) Base.isempty(h::MutableBinaryHeap) = isempty(h.nodes) function Base.push!(h::MutableBinaryHeap{T}, v) where T nodes = h.nodes nodemap = h.node_map i = length(nodemap) + 1 nd_id = length(nodes) + 1 push!(nodes, MutableBinaryHeapNode(convert(T, v), i)) push!(nodemap, nd_id) _heap_bubble_up!(h.ordering, nodes, nodemap, nd_id) return i end function Base.empty!(h::MutableBinaryHeap) ##CHUNK 3 nodemap = h.node_map i = length(nodemap) + 1 nd_id = length(nodes) + 1 push!(nodes, MutableBinaryHeapNode(convert(T, v), i)) push!(nodemap, nd_id) _heap_bubble_up!(h.ordering, nodes, nodemap, nd_id) return i end function Base.empty!(h::MutableBinaryHeap) empty!(h.nodes) empty!(h.node_map) return h end function Base.sizehint!(h::MutableBinaryHeap, s::Integer) sizehint!(h.nodes, s) sizehint!(h.node_map, s) return h end ##CHUNK 4 i = p else swapped = false end end if i != nd_id nodes[i] = nd nodemap[nd.handle] = i end end function _heap_bubble_down!(ord::Ordering, nodes::Vector{MutableBinaryHeapNode{T}}, nodemap::Vector{Int}, nd_id::Int) where T @inbounds nd = nodes[nd_id] v::T = nd.value n = length(nodes) last_parent = n >> 1 ##CHUNK 5 # if node-to-remove is at end, we can just pop it # the same applies to 1-element heaps that are empty after removing the last element if nd_id == lastindex(nodes) pop!(nodes) else # move the last node to the position of the node-to-remove @inbounds nodes[nd_id] = new_rt = nodes[end] pop!(nodes) @inbounds nodemap[new_rt.handle] = nd_id if length(nodes) > 1 if Base.lt(ord, new_rt.value, v) _heap_bubble_up!(ord, nodes, nodemap, nd_id) else _heap_bubble_down!(ord, nodes, nodemap, nd_id) end end end return v end Based on the information above, please generate test code for the following function: function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end
{ "fpath_tuple": [ "DataStructures.jl", "src", "heaps", "mutable_binary_heap.jl" ], "ground_truth": "function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T\n # make a static binary index tree from a list of values\n\n n = length(values)\n nodes = Vector{MutableBinaryHeapNode{T}}(undef, n)\n nodemap = Vector{Int}(undef, n)\n\n i::Int = 0\n for v in values\n i += 1\n @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i)\n @inbounds nodemap[i] = i\n end\n\n for i = 1 : n\n _heap_bubble_up!(ord, nodes, nodemap, i)\n end\n return nodes, nodemap\nend", "task_id": "DataStructures/71" }
132
150
DataStructures.jl
71
function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end
_make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T
[ 132, 150 ]
function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) i::Int = 0 for v in values i += 1 @inbounds nodes[i] = MutableBinaryHeapNode{T}(v, i) @inbounds nodemap[i] = i end for i = 1 : n _heap_bubble_up!(ord, nodes, nodemap, i) end return nodes, nodemap end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) ##CHUNK 2 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) ##CHUNK 3 d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) ##CHUNK 4 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper ##CHUNK 5 d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) ##CHUNK 6 log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) ##CHUNK 7 log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) ##CHUNK 8 xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower ##CHUNK 9 xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else ##CHUNK 10 oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero Based on the information above, please generate test code for the following function: function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function mean(d::Censored)\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n log_prob_lower = _logcdf_noninclusive(d0, lower)\n log_prob_upper = logccdf(d0, upper)\n log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper))\n μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) +\n xexpy(mean(_to_truncated(d)), log_prob_interval))\n return μ\nend", "task_id": "Distributions/72" }
187
197
Distributions.jl
72
function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end
mean(d::Censored)
[ 187, 197 ]
function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) ##CHUNK 2 log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) ##CHUNK 3 d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) ##CHUNK 4 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 5 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::RightCensored) upper = d.upper ##CHUNK 6 v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) ##CHUNK 7 # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound ##CHUNK 8 #### Statistics quantile(d::Censored, p::Real) = _clamp(quantile(d.uncensored, p), d.lower, d.upper) median(d::Censored) = _clamp(median(d.uncensored), d.lower, d.upper) # the expectations use the following relation: # 𝔼_{x ~ d}[h(x)] = P_{x ~ d₀}(x < l) h(l) + P_{x ~ d₀}(x > u) h(u) # + P_{x ~ d₀}(l ≤ x ≤ u) 𝔼_{x ~ τ}[h(x)], # where d₀ is the uncensored distribution, d is d₀ censored to [l, u], # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) ##CHUNK 9 log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) ##CHUNK 10 xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower Based on the information above, please generate test code for the following function: function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function var(d::LeftCensored)\n lower = d.lower\n log_prob_lower = _logcdf_noninclusive(d.uncensored, lower)\n log_prob_interval = log1mexp(log_prob_lower)\n dtrunc = _to_truncated(d)\n μ_interval = mean(dtrunc)\n μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval)\n v_interval = var(dtrunc) + abs2(μ_interval - μ)\n v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval)\n return v\nend", "task_id": "Distributions/73" }
199
209
Distributions.jl
73
function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end
var(d::LeftCensored)
[ 199, 209 ]
function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) ##CHUNK 2 log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) ##CHUNK 3 d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) ##CHUNK 4 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower ##CHUNK 5 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 6 end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) ##CHUNK 7 log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) ##CHUNK 8 xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else ##CHUNK 9 v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) ##CHUNK 10 xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower Based on the information above, please generate test code for the following function: function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function var(d::RightCensored)\n upper = d.upper\n log_prob_upper = logccdf(d.uncensored, upper)\n log_prob_interval = log1mexp(log_prob_upper)\n dtrunc = _to_truncated(d)\n μ_interval = mean(dtrunc)\n μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)\n v_interval = var(dtrunc) + abs2(μ_interval - μ)\n v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)\n return v\nend", "task_id": "Distributions/74" }
210
220
Distributions.jl
74
function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end
var(d::RightCensored)
[ 210, 220 ]
function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) ##CHUNK 2 log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end ##CHUNK 3 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower ##CHUNK 4 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end # this expectation also uses the following relation: # 𝔼_{x ~ τ}[-log d(x)] = H[τ] - log P_{x ~ d₀}(l ≤ x ≤ u) # + (P_{x ~ d₀}(x = l) (log P_{x ~ d₀}(x = l) - log P_{x ~ d₀}(x ≤ l)) + # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored ##CHUNK 5 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 6 lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) ##CHUNK 7 dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper ##CHUNK 8 if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) ##CHUNK 9 xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower ##CHUNK 10 log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) Based on the information above, please generate test code for the following function: function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function var(d::Censored)\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n log_prob_lower = _logcdf_noninclusive(d0, lower)\n log_prob_upper = logccdf(d0, upper)\n log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper))\n dtrunc = _to_truncated(d)\n μ_interval = mean(dtrunc)\n μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) +\n xexpy(μ_interval, log_prob_interval))\n v_interval = var(dtrunc) + abs2(μ_interval - μ)\n v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) +\n xexpy(v_interval, log_prob_interval))\n return v\nend", "task_id": "Distributions/75" }
221
236
Distributions.jl
75
function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end
var(d::Censored)
[ 221, 236 ]
function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval)) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = (xexpy(abs2(lower - μ), log_prob_lower) + xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval)) return v end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end ##CHUNK 2 logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation ##CHUNK 3 log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) ##CHUNK 4 log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper ##CHUNK 5 # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu ##CHUNK 6 log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) ##CHUNK 7 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + ##CHUNK 8 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 9 log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end ##CHUNK 10 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower Based on the information above, please generate test code for the following function: function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function entropy(d::LeftCensored)\n d0 = d.uncensored\n lower = d.lower\n log_prob_lower_inc = logcdf(d0, lower)\n if value_support(typeof(d0)) === Discrete\n logpl = logpdf(d0, lower)\n log_prob_lower = logsubexp(log_prob_lower_inc, logpl)\n xlogx_pl = xexpx(logpl)\n else\n log_prob_lower = log_prob_lower_inc\n xlogx_pl = 0\n end\n log_prob_interval = log1mexp(log_prob_lower)\n entropy_bound = -xexpx(log_prob_lower_inc)\n dtrunc = _to_truncated(d)\n entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl\n return entropy_interval + entropy_bound\nend", "task_id": "Distributions/76" }
245
262
Distributions.jl
76
function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end
entropy(d::LeftCensored)
[ 245, 262 ]
function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation ##CHUNK 2 return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end ##CHUNK 3 log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) ##CHUNK 4 log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper ##CHUNK 5 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + ##CHUNK 6 # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl ##CHUNK 7 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower ##CHUNK 8 log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end ##CHUNK 9 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 10 if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) Based on the information above, please generate test code for the following function: function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function entropy(d::RightCensored)\n d0 = d.uncensored\n upper = d.upper\n log_prob_upper = logccdf(d0, upper)\n if value_support(typeof(d0)) === Discrete\n logpu = logpdf(d0, upper)\n log_prob_upper_inc = logaddexp(log_prob_upper, logpu)\n xlogx_pu = xexpx(logpu)\n else\n log_prob_upper_inc = log_prob_upper\n xlogx_pu = 0\n end\n log_prob_interval = log1mexp(log_prob_upper)\n entropy_bound = -xexpx(log_prob_upper_inc)\n dtrunc = _to_truncated(d)\n entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu\n return entropy_interval + entropy_bound\nend", "task_id": "Distributions/77" }
263
280
Distributions.jl
77
function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end
entropy(d::RightCensored)
[ 263, 280 ]
function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) ##CHUNK 2 return entropy_interval + entropy_bound end function entropy(d::RightCensored) d0 = d.uncensored upper = d.upper log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpu = logpdf(d0, upper) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pu = xexpx(logpu) else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end ##CHUNK 3 # P_{x ~ d₀}(x = u) (log P_{x ~ d₀}(x = u) - log P_{x ~ d₀}(x ≥ u)) # ) / P_{x ~ d₀}(l ≤ x ≤ u), # where H[τ] is the entropy of τ. function entropy(d::LeftCensored) d0 = d.uncensored lower = d.lower log_prob_lower_inc = logcdf(d0, lower) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) xlogx_pl = xexpx(logpl) else log_prob_lower = log_prob_lower_inc xlogx_pl = 0 end log_prob_interval = log1mexp(log_prob_lower) entropy_bound = -xexpx(log_prob_lower_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl ##CHUNK 4 else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) ##CHUNK 5 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end function var(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + ##CHUNK 6 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower ##CHUNK 7 log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) ##CHUNK 8 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper ##CHUNK 9 oftype(logpx, -Inf) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end ##CHUNK 10 log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(lower, log_prob_lower) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(lower - μ), log_prob_lower) + xexpy(v_interval, log_prob_interval) return v end function var(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) dtrunc = _to_truncated(d) μ_interval = mean(dtrunc) μ = xexpy(upper, log_prob_upper) + xexpy(μ_interval, log_prob_interval) v_interval = var(dtrunc) + abs2(μ_interval - μ) v = xexpy(abs2(upper - μ), log_prob_upper) + xexpy(v_interval, log_prob_interval) return v end Based on the information above, please generate test code for the following function: function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function entropy(d::Censored)\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n log_prob_lower_inc = logcdf(d0, lower)\n log_prob_upper = logccdf(d0, upper)\n if value_support(typeof(d0)) === Discrete\n logpl = logpdf(d0, lower)\n logpu = logpdf(d0, upper)\n log_prob_lower = logsubexp(log_prob_lower_inc, logpl)\n log_prob_upper_inc = logaddexp(log_prob_upper, logpu)\n xlogx_pl = xexpx(logpl)\n xlogx_pu = xexpx(logpu)\n else\n log_prob_lower = log_prob_lower_inc\n log_prob_upper_inc = log_prob_upper\n xlogx_pl = xlogx_pu = 0\n end\n log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper))\n entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc))\n dtrunc = _to_truncated(d)\n entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu\n return entropy_interval + entropy_bound\nend", "task_id": "Distributions/78" }
281
304
Distributions.jl
78
function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end
entropy(d::Censored)
[ 281, 304 ]
function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) ##CHUNK 2 dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function logpdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete ##CHUNK 3 oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower ##CHUNK 4 function insupport(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper return ( (_in_open_interval(x, lower, upper) && insupport(d0, x)) || (x == lower && cdf(d0, lower) > 0) || (x == upper && _ccdf_inclusive(d0, upper) > 0) ) end #### Show function show(io::IO, ::MIME"text/plain", d::Censored) print(io, "Censored(") d0 = d.uncensored uml, namevals = _use_multline_show(d0) uml ? show_multline(io, d0, namevals; newline=false) : show_oneline(io, d0, namevals) if d.lower === nothing print(io, "; upper=$(d.upper))") ##CHUNK 5 d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower ##CHUNK 6 upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else ##CHUNK 7 xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower ##CHUNK 8 function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) ##CHUNK 9 zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 10 zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling Based on the information above, please generate test code for the following function: function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(px, ccdf(d0, x) + px) else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function pdf(d::Censored, x::Real)\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n px = float(pdf(d0, x))\n return if _in_open_interval(x, lower, upper)\n px\n elseif x == lower\n x == upper ? one(px) : oftype(px, cdf(d0, x))\n elseif x == upper\n if value_support(typeof(d0)) === Discrete\n oftype(px, ccdf(d0, x) + px)\n else\n oftype(px, ccdf(d0, x))\n end\n else # not in support\n zero(px)\n end\nend", "task_id": "Distributions/79" }
309
327
Distributions.jl
79
function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(px, ccdf(d0, x) + px) else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end
pdf(d::Censored, x::Real)
[ 309, 327 ]
function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(px, ccdf(d0, x) + px) else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower ##CHUNK 2 d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower ##CHUNK 3 lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(px, ccdf(d0, x) + px) else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end function loglikelihood(d::Censored, x::AbstractArray{<:Real}) ##CHUNK 4 dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pl + xlogx_pu return entropy_interval + entropy_bound end #### Evaluation function pdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper px = float(pdf(d0, x)) return if _in_open_interval(x, lower, upper) px elseif x == lower x == upper ? one(px) : oftype(px, cdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(px, ccdf(d0, x) + px) ##CHUNK 5 upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else ##CHUNK 6 else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) ##CHUNK 7 zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 8 xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower ##CHUNK 9 function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) ##CHUNK 10 function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) Based on the information above, please generate test code for the following function: function logpdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function logpdf(d::Censored, x::Real)\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n logpx = logpdf(d0, x)\n return if _in_open_interval(x, lower, upper)\n logpx\n elseif x == lower\n x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x))\n elseif x == upper\n if value_support(typeof(d0)) === Discrete\n oftype(logpx, logaddexp(logccdf(d0, x), logpx))\n else\n oftype(logpx, logccdf(d0, x))\n end\n else # not in support\n oftype(logpx, -Inf)\n end\nend", "task_id": "Distributions/80" }
329
347
Distributions.jl
80
function logpdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end
logpdf(d::Censored, x::Real)
[ 329, 347 ]
function logpdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function cdf(d::Censored, x::Real) ##CHUNK 2 else oftype(px, ccdf(d0, x)) end else # not in support zero(px) end end function logpdf(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, x) return if _in_open_interval(x, lower, upper) logpx elseif x == lower x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x)) elseif x == upper if value_support(typeof(d0)) === Discrete oftype(logpx, logaddexp(logccdf(d0, x), logpx)) ##CHUNK 3 else oftype(logpx, logccdf(d0, x)) end else # not in support oftype(logpx, -Inf) end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end ##CHUNK 4 else log_prob_upper_inc = log_prob_upper xlogx_pu = 0 end log_prob_interval = log1mexp(log_prob_upper) entropy_bound = -xexpx(log_prob_upper_inc) dtrunc = _to_truncated(d) entropy_interval = xexpy(entropy(dtrunc), log_prob_interval) - xexpx(log_prob_interval) + xlogx_pu return entropy_interval + entropy_bound end function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) ##CHUNK 5 function entropy(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower_inc = logcdf(d0, lower) log_prob_upper = logccdf(d0, upper) if value_support(typeof(d0)) === Discrete logpl = logpdf(d0, lower) logpu = logpdf(d0, upper) log_prob_lower = logsubexp(log_prob_lower_inc, logpl) log_prob_upper_inc = logaddexp(log_prob_upper, logpu) xlogx_pl = xexpx(logpl) xlogx_pu = xexpx(logpu) else log_prob_lower = log_prob_lower_inc log_prob_upper_inc = log_prob_upper xlogx_pl = xlogx_pu = 0 end log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) entropy_bound = -(xexpx(log_prob_lower_inc) + xexpx(log_prob_upper_inc)) ##CHUNK 6 function insupport(d::Censored, x::Real) d0 = d.uncensored lower = d.lower upper = d.upper return ( (_in_open_interval(x, lower, upper) && insupport(d0, x)) || (x == lower && cdf(d0, lower) > 0) || (x == upper && _ccdf_inclusive(d0, upper) > 0) ) end #### Show function show(io::IO, ::MIME"text/plain", d::Censored) print(io, "Censored(") d0 = d.uncensored uml, namevals = _use_multline_show(d0) uml ? show_multline(io, d0, namevals; newline=false) : show_oneline(io, d0, namevals) if d.lower === nothing print(io, "; upper=$(d.upper))") ##CHUNK 7 upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper log_prob_lower = _logcdf_noninclusive(d0, lower) log_prob_upper = logccdf(d0, upper) log_prob_interval = log1mexp(logaddexp(log_prob_lower, log_prob_upper)) μ = (xexpy(lower, log_prob_lower) + xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval)) return μ end function var(d::LeftCensored) lower = d.lower ##CHUNK 8 lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result ##CHUNK 9 end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower ##CHUNK 10 # and τ is d₀ truncated to [l, u] function mean(d::LeftCensored) lower = d.lower log_prob_lower = _logcdf_noninclusive(d.uncensored, lower) log_prob_interval = log1mexp(log_prob_lower) μ = xexpy(lower, log_prob_lower) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::RightCensored) upper = d.upper log_prob_upper = logccdf(d.uncensored, upper) log_prob_interval = log1mexp(log_prob_upper) μ = xexpy(upper, log_prob_upper) + xexpy(mean(_to_truncated(d)), log_prob_interval) return μ end function mean(d::Censored) d0 = d.uncensored lower = d.lower upper = d.upper Based on the information above, please generate test code for the following function: function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function loglikelihood(d::Censored, x::AbstractArray{<:Real})\n d0 = d.uncensored\n lower = d.lower\n upper = d.upper\n logpx = logpdf(d0, first(x))\n log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower))\n log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper))\n logzero = oftype(logpx, -Inf)\n return sum(x) do xi\n _in_open_interval(xi, lower, upper) && return logpdf(d0, xi)\n xi == lower && return log_prob_lower\n xi == upper && return log_prob_upper\n return logzero\n end\nend", "task_id": "Distributions/81" }
349
363
Distributions.jl
81
function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end
loglikelihood(d::Censored, x::AbstractArray{<:Real})
[ 349, 363 ]
function loglikelihood(d::Censored, x::AbstractArray{<:Real}) d0 = d.uncensored lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper ##CHUNK 2 return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end ##CHUNK 3 result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end ##CHUNK 4 function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result ##CHUNK 5 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else ##CHUNK 2 oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end ##CHUNK 3 return logzero end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower ##CHUNK 4 function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) ##CHUNK 5 lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower Based on the information above, please generate test code for the following function: function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function cdf(d::Censored, x::Real)\n lower = d.lower\n upper = d.upper\n result = cdf(d.uncensored, x)\n return if lower !== nothing && x < lower\n zero(result)\n elseif upper === nothing || x < upper\n result\n else\n one(result)\n end\nend", "task_id": "Distributions/82" }
365
376
Distributions.jl
82
function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end
cdf(d::Censored, x::Real)
[ 365, 376 ]
function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end ##CHUNK 2 end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper ##CHUNK 3 result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end ##CHUNK 4 function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result ##CHUNK 5 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else ##CHUNK 2 return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function ccdf(d::Censored, x::Real) lower = d.lower ##CHUNK 3 function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) ##CHUNK 4 elseif upper === nothing || x < upper result else one(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end ##CHUNK 5 lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) Based on the information above, please generate test code for the following function: function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function logcdf(d::Censored, x::Real)\n lower = d.lower\n upper = d.upper\n result = logcdf(d.uncensored, x)\n return if d.lower !== nothing && x < d.lower\n oftype(result, -Inf)\n elseif d.upper === nothing || x < d.upper\n result\n else\n zero(result)\n end\nend", "task_id": "Distributions/83" }
378
389
Distributions.jl
83
function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end
logcdf(d::Censored, x::Real)
[ 378, 389 ]
function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper ##CHUNK 2 return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end ##CHUNK 3 result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end ##CHUNK 4 function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result ##CHUNK 5 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper ##CHUNK 2 result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else ##CHUNK 3 elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 4 function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) ##CHUNK 5 lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) Based on the information above, please generate test code for the following function: function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function ccdf(d::Censored, x::Real)\n lower = d.lower\n upper = d.upper\n result = ccdf(d.uncensored, x)\n return if lower !== nothing && x < lower\n one(result)\n elseif upper === nothing || x < upper\n result\n else\n zero(result)\n end\nend", "task_id": "Distributions/84" }
391
402
Distributions.jl
84
function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end
ccdf(d::Censored, x::Real)
[ 391, 402 ]
function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper ##CHUNK 2 return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end ##CHUNK 3 result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end ##CHUNK 4 function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result ##CHUNK 5 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) #CURRENT FILE: Distributions.jl/src/censored.jl ##CHUNK 1 result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) ##CHUNK 2 elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 3 return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper ##CHUNK 4 function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) ##CHUNK 5 lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) Based on the information above, please generate test code for the following function: function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "censored.jl" ], "ground_truth": "function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T}\n lower = d.lower\n upper = d.upper\n result = logccdf(d.uncensored, x)\n return if lower !== nothing && x < lower\n zero(result)\n elseif upper === nothing || x < upper\n result\n else\n oftype(result, -Inf)\n end\nend", "task_id": "Distributions/85" }
404
415
Distributions.jl
85
function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end
logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T}
[ 404, 415 ]
function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/product.jl ##CHUNK 1 ) where {N} return __logpdf(d, x) end _logpdf(d::FillArrayOfUnivariateDistribution{2}, x::AbstractMatrix{<:Real}) = __logpdf(d, x) function __logpdf( d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N} ) where {N} return @inbounds loglikelihood(first(d.dists), x) end # `_rand! for arrays of distributions function _rand!( rng::AbstractRNG, d::ProductDistribution{N,M}, A::AbstractArray{<:Real,N}, ) where {N,M} @inbounds for (di, Ai) in zip(d.dists, eachvariate(A, ArrayLikeVariate{M})) rand!(rng, di, Ai) end return A ##CHUNK 2 cov(d::ProductDistribution{2}, ::Val{false}) = reshape(cov(d), size(d)..., size(d)...) # `_rand!` for arrays of univariate distributions function _rand!( rng::AbstractRNG, d::ArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N}, ) where {N} @inbounds for (i, di) in zip(eachindex(x), d.dists) x[i] = rand(rng, di) end return x end # `_logpdf` for arrays of univariate distributions # we have to fix a method ambiguity function _logpdf(d::ArrayOfUnivariateDistribution, x::AbstractArray{<:Real,N}) where {N} return __logpdf(d, x) end _logpdf(d::MatrixOfUnivariateDistribution, x::AbstractMatrix{<:Real}) = __logpdf(d, x) #FILE: Distributions.jl/src/reshaped.jl ##CHUNK 1 throw(DimensionMismatch("inconsistent array dimensions")) end dist = d.dist trailingsize = ntuple(i -> size(x, N + i), Val(M - N)) return @inbounds loglikelihood(dist, reshape(x, size(dist)..., trailingsize...)) end # sampling function _rand!( rng::AbstractRNG, d::ReshapedDistribution{N}, x::AbstractArray{<:Real,N} ) where {N} dist = d.dist @inbounds rand!(rng, dist, reshape(x, size(dist))) return x end """ reshape(d::Distribution{<:ArrayLikeVariate}, dims::Int...) #FILE: Distributions.jl/src/multivariate/dirichlet.jl ##CHUNK 1 s = sum(xlogy(αi - 1, xi) for (αi, xi) in zip(d.alpha, x)) return s - d.lmnB end # sampling function _rand!(rng::AbstractRNG, d::Union{Dirichlet,DirichletCanon}, x::AbstractVector{<:Real}) for (i, αi) in zip(eachindex(x), d.alpha) @inbounds x[i] = rand(rng, Gamma(αi)) end lmul!(inv(sum(x)), x) # this returns x end function _rand!(rng::AbstractRNG, d::Dirichlet{T,<:FillArrays.AbstractFill{T}}, x::AbstractVector{<:Real}) where {T<:Real} rand!(rng, Gamma(FillArrays.getindex_value(d.alpha)), x) lmul!(inv(sum(x)), x) # this returns x #CURRENT FILE: Distributions.jl/src/genericrand.jl ##CHUNK 1 function _rand!( rng::AbstractRNG, s::Sampleable{<:ArrayLikeVariate}, x::AbstractArray{<:Real}, ) @inbounds for xi in eachvariate(x, variate_form(typeof(s))) rand!(rng, s, xi) end return x end Base.@propagate_inbounds function rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, ) where {N} sz = size(s) allocate = !all(isassigned(x, i) && size(@inbounds x[i]) == sz for i in eachindex(x)) return rand!(rng, s, x, allocate) end ##CHUNK 2 Base.@propagate_inbounds function rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, ) where {N} sz = size(s) allocate = !all(isassigned(x, i) && size(@inbounds x[i]) == sz for i in eachindex(x)) return rand!(rng, s, x, allocate) end Base.@propagate_inbounds function rand!( s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} return rand!(default_rng(), s, x, allocate) end @inline function rand!( rng::AbstractRNG, ##CHUNK 3 Base.@propagate_inbounds function rand!( s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} return rand!(default_rng(), s, x, allocate) end @inline function rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} @boundscheck begin if !allocate sz = size(s) all(size(xi) == sz for xi in x) || throw(DimensionMismatch("inconsistent array dimensions")) end ##CHUNK 4 throw(DimensionMismatch( "number of dimensions of `x` ($M) must be greater than number of dimensions of `s` ($N)" )) ntuple(i -> size(x, i), Val(N)) == size(s) || throw(DimensionMismatch("inconsistent array dimensions")) end # the function barrier fixes performance issues if `sampler(s)` is type unstable return _rand!(rng, sampler(s), x) end function _rand!( rng::AbstractRNG, s::Sampleable{<:ArrayLikeVariate}, x::AbstractArray{<:Real}, ) @inbounds for xi in eachvariate(x, variate_form(typeof(s))) rand!(rng, s, xi) end return x end ##CHUNK 5 s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} @boundscheck begin if !allocate sz = size(s) all(size(xi) == sz for xi in x) || throw(DimensionMismatch("inconsistent array dimensions")) end end # the function barrier fixes performance issues if `sampler(s)` is type unstable return _rand!(rng, sampler(s), x, allocate) end """ sampler(d::Distribution) -> Sampleable sampler(s::Sampleable) -> s ##CHUNK 6 """ rand(s::Sampleable, dims::Int...) = rand(default_rng(), s, dims...) rand(s::Sampleable, dims::Dims) = rand(default_rng(), s, dims) rand(rng::AbstractRNG, s::Sampleable, dim1::Int, moredims::Int...) = rand(rng, s, (dim1, moredims...)) # default fallback (redefined for univariate distributions) function rand(rng::AbstractRNG, s::Sampleable{<:ArrayLikeVariate}) return @inbounds rand!(rng, s, Array{eltype(s)}(undef, size(s))) end # multiple samples function rand(rng::AbstractRNG, s::Sampleable{Univariate}, dims::Dims) out = Array{eltype(s)}(undef, dims) return @inbounds rand!(rng, sampler(s), out) end function rand( rng::AbstractRNG, s::Sampleable{<:ArrayLikeVariate}, dims::Dims, ) sz = size(s) Based on the information above, please generate test code for the following function: function _rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} if allocate @inbounds for i in eachindex(x) x[i] = rand(rng, s) end else @inbounds for xi in x rand!(rng, s, xi) end end return x end
{ "fpath_tuple": [ "Distributions.jl", "src", "genericrand.jl" ], "ground_truth": "function _rand!(\n rng::AbstractRNG,\n s::Sampleable{ArrayLikeVariate{N}},\n x::AbstractArray{<:AbstractArray{<:Real,N}},\n allocate::Bool,\n) where {N}\n if allocate\n @inbounds for i in eachindex(x)\n x[i] = rand(rng, s)\n end\n else\n @inbounds for xi in x\n rand!(rng, s, xi)\n end\n end\n return x\nend", "task_id": "Distributions/86" }
156
172
Distributions.jl
86
function _rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} if allocate @inbounds for i in eachindex(x) x[i] = rand(rng, s) end else @inbounds for xi in x rand!(rng, s, xi) end end return x end
_rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N}
[ 156, 172 ]
function _rand!( rng::AbstractRNG, s::Sampleable{ArrayLikeVariate{N}}, x::AbstractArray{<:AbstractArray{<:Real,N}}, allocate::Bool, ) where {N} if allocate @inbounds for i in eachindex(x) x[i] = rand(rng, s) end else @inbounds for xi in x rand!(rng, s, xi) end end return x end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/test/matrixvariates.jl ##CHUNK 1 ν = max(n, p) + 1 M = randn(n, p) u = rand() U_scale = ScalMat(n, u) U_dense = Matrix(U_scale) U_pd = PDMat(U_dense) U_pdiag = PDiagMat(u*ones(n)) v = rand(p) V_pdiag = PDiagMat(v) V_dense = Matrix(V_pdiag) V_pd = PDMat(V_dense) UV = kron(V_dense, U_dense) ./ (ν - 2) baseeval = logpdf(MatrixTDist(ν, M, U_dense, V_dense), M) for U in [U_scale, U_dense, U_pd, U_pdiag] for V in [V_pdiag, V_dense, V_pd] d = MatrixTDist(ν, M, U, V) @test cov(d) ≈ UV @test logpdf(d, M) ≈ baseeval end end ##CHUNK 2 d = 4 η = abs(3randn()) G = LKJ(d, η) M = 10000 α = 0.05 L = sum(1:(d - 1)) ρ = Distributions._marginal(G) mymats = zeros(d, d, M) for m in 1:M mymats[:, :, m] = rand(G) end for i in 1:d for j in 1:i-1 @test pvalue_kolmogorovsmirnoff(mymats[i, j, :], ρ) >= α / L end end end @testset "LKJ integrating constant" begin # ============= # odd non-uniform ##CHUNK 3 v = rand(p) V_pdiag = PDiagMat(v) V_dense = Matrix(V_pdiag) V_pd = PDMat(V_dense) UV = kron(V_dense, U_dense) baseeval = logpdf(MatrixNormal(M, U_dense, V_dense), M) for U in [U_scale, U_dense, U_pd, U_pdiag] for V in [V_pdiag, V_dense, V_pd] d = MatrixNormal(M, U, V) @test cov(d) ≈ UV @test logpdf(d, M) ≈ baseeval end end end nothing end function test_special(dist::Type{Wishart}) n = 3 M = 5000 #FILE: Distributions.jl/src/mixtures/mixturemodel.jl ##CHUNK 1 LinearAlgebra.copytri!(V, 'U') return V end #### show function show(io::IO, d::MixtureModel) K = ncomponents(d) pr = probs(d) println(io, "MixtureModel{$(component_type(d))}(K = $K)") Ks = min(K, 8) for i = 1:Ks @printf(io, "components[%d] (prior = %.4f): ", i, pr[i]) println(io, component(d, i)) end if Ks < K println(io, "The rest are omitted ...") end #FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl ##CHUNK 1 lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T) i = j xᵢ = xⱼ end if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T) lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1)) end return lp end # given ∏ₖf(xₖ), marginalize all xₖ for i < k < j function _marginalize_range(dist, i, j, xᵢ, xⱼ, T) k = j - i - 1 k == 0 && return zero(T) return k * T(logdiffcdf(dist, xⱼ, xᵢ)) - loggamma(T(k + 1)) end function _rand!(rng::AbstractRNG, d::JointOrderStatistics, x::AbstractVector{<:Real}) n = d.n if n == length(d.ranks) # ranks == 1:n #FILE: Distributions.jl/src/matrix/matrixnormal.jl ##CHUNK 1 return Normal(μ, σ) end function _multivariate(d::MatrixNormal) n, p = size(d) all([n, p] .> 1) && throw(ArgumentError("Row or col dim of `MatrixNormal` must be 1 to coerce to `MvNormal`")) return vec(d) end function _rand_params(::Type{MatrixNormal}, elty, n::Int, p::Int) M = randn(elty, n, p) U = (X = 2 .* rand(elty, n, n) .- 1; X * X') V = (Y = 2 .* rand(elty, p, p) .- 1; Y * Y') return M, U, V end #FILE: Distributions.jl/src/multivariate/multinomial.jl ##CHUNK 1 C = Matrix{T}(undef, k, k) for j = 1:k pj = p[j] for i = 1:j-1 @inbounds C[i,j] = - n * p[i] * pj end @inbounds C[j,j] = n * pj * (1-pj) end for j = 1:k-1 for i = j+1:k @inbounds C[i,j] = C[j,i] end end C end function mgf(d::Multinomial{T}, t::AbstractVector) where T<:Real #CURRENT FILE: Distributions.jl/src/matrixvariates.jl ##CHUNK 1 Compute the covariance matrix for `vec(X)`, where `X` is a random matrix with distribution `d`. """ cov(d::MatrixDistribution, ::Val{true}) = cov(d) """ cov(d::MatrixDistribution, flattened = Val(false)) Compute the 4-dimensional array whose `(i, j, k, l)` element is `cov(X[i,j], X[k, l])`. """ function cov(d::MatrixDistribution, ::Val{false}) n, p = size(d) [cov(d, i, j, k, l) for i in 1:n, j in 1:p, k in 1:n, l in 1:p] end # pdf & logpdf # TODO: Remove or restrict - this causes many ambiguity errors... _logpdf(d::MatrixDistribution, X::AbstractMatrix{<:Real}) = logkernel(d, X) + d.logc0 ##CHUNK 2 function cov(d::MatrixDistribution, ::Val{false}) n, p = size(d) [cov(d, i, j, k, l) for i in 1:n, j in 1:p, k in 1:n, l in 1:p] end # pdf & logpdf # TODO: Remove or restrict - this causes many ambiguity errors... _logpdf(d::MatrixDistribution, X::AbstractMatrix{<:Real}) = logkernel(d, X) + d.logc0 # for testing is_univariate(d::MatrixDistribution) = size(d) == (1, 1) check_univariate(d::MatrixDistribution) = is_univariate(d) || throw(ArgumentError("not 1 x 1")) ##### Specific distributions ##### for fname in ["wishart.jl", "inversewishart.jl", "matrixnormal.jl", "matrixtdist.jl", "matrixbeta.jl", "matrixfdist.jl", "lkj.jl"] include(joinpath("matrix", fname)) end ##CHUNK 3 """ var(d::MatrixDistribution) Compute the matrix of element-wise variances for distribution `d`. """ var(d::MatrixDistribution) = ((n, p) = size(d); [var(d, i, j) for i in 1:n, j in 1:p]) """ cov(d::MatrixDistribution) Compute the covariance matrix for `vec(X)`, where `X` is a random matrix with distribution `d`. """ cov(d::MatrixDistribution, ::Val{true}) = cov(d) """ cov(d::MatrixDistribution, flattened = Val(false)) Compute the 4-dimensional array whose `(i, j, k, l)` element is `cov(X[i,j], X[k, l])`. """ Based on the information above, please generate test code for the following function: function cov(d::MatrixDistribution) M = length(d) V = zeros(partype(d), M, M) iter = CartesianIndices(size(d)) for el1 = 1:M for el2 = 1:el1 i, j = Tuple(iter[el1]) k, l = Tuple(iter[el2]) V[el1, el2] = cov(d, i, j, k, l) end end return V + tril(V, -1)' end
{ "fpath_tuple": [ "Distributions.jl", "src", "matrixvariates.jl" ], "ground_truth": "function cov(d::MatrixDistribution)\n M = length(d)\n V = zeros(partype(d), M, M)\n iter = CartesianIndices(size(d))\n for el1 = 1:M\n for el2 = 1:el1\n i, j = Tuple(iter[el1])\n k, l = Tuple(iter[el2])\n V[el1, el2] = cov(d, i, j, k, l)\n end\n end\n return V + tril(V, -1)'\nend", "task_id": "Distributions/87" }
54
66
Distributions.jl
87
function cov(d::MatrixDistribution) M = length(d) V = zeros(partype(d), M, M) iter = CartesianIndices(size(d)) for el1 = 1:M for el2 = 1:el1 i, j = Tuple(iter[el1]) k, l = Tuple(iter[el2]) V[el1, el2] = cov(d, i, j, k, l) end end return V + tril(V, -1)' end
cov(d::MatrixDistribution)
[ 54, 66 ]
function cov(d::MatrixDistribution) M = length(d) V = zeros(partype(d), M, M) iter = CartesianIndices(size(d)) for el1 = 1:M for el2 = 1:el1 i, j = Tuple(iter[el1]) k, l = Tuple(iter[el2]) V[el1, el2] = cov(d, i, j, k, l) end end return V + tril(V, -1)' end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/multivariate/multinomial.jl ##CHUNK 1 C = Matrix{T}(undef, k, k) for j = 1:k pj = p[j] for i = 1:j-1 @inbounds C[i,j] = - n * p[i] * pj end @inbounds C[j,j] = n * pj * (1-pj) end for j = 1:k-1 for i = j+1:k @inbounds C[i,j] = C[j,i] end end C end function mgf(d::Multinomial{T}, t::AbstractVector) where T<:Real ##CHUNK 2 @inbounds p_i = p[i] v[i] = n * p_i * (1 - p_i) end v end function cov(d::Multinomial{T}) where T<:Real p = probs(d) k = length(p) n = ntrials(d) C = Matrix{T}(undef, k, k) for j = 1:k pj = p[j] for i = 1:j-1 @inbounds C[i,j] = - n * p[i] * pj end @inbounds C[j,j] = n * pj * (1-pj) end #FILE: Distributions.jl/test/cholesky/lkjcholesky.jl ##CHUNK 1 end end # Compute logdetjac of ϕ: L → L L' where only strict lower triangle of L and L L' are unique function cholesky_inverse_logdetjac(L) size(L, 1) == 1 && return 0.0 J = jacobian(central_fdm(5, 1), cholesky_vec_to_corr_vec, stricttril_to_vec(L))[1] return logabsdet(J)[1] end stricttril_to_vec(L) = [L[i, j] for i in axes(L, 1) for j in 1:(i - 1)] function vec_to_stricttril(l) n = length(l) p = Int((1 + sqrt(8n + 1)) / 2) L = similar(l, p, p) fill!(L, 0) k = 1 for i in 1:p, j in 1:(i - 1) L[i, j] = l[k] k += 1 end ##CHUNK 2 function vec_to_stricttril(l) n = length(l) p = Int((1 + sqrt(8n + 1)) / 2) L = similar(l, p, p) fill!(L, 0) k = 1 for i in 1:p, j in 1:(i - 1) L[i, j] = l[k] k += 1 end return L end function cholesky_vec_to_corr_vec(l) L = vec_to_stricttril(l) for i in axes(L, 1) w = view(L, i, 1:(i-1)) wnorm = norm(w) if wnorm > 1 w ./= wnorm wnorm = 1 #FILE: Distributions.jl/src/multivariate/mvnormal.jl ##CHUNK 1 z = Matrix{Float64}(undef, m, n) for j = 1:n cj = sqrt(w[j]) for i = 1:m @inbounds z[i,j] = (x[i,j] - mu[i]) * cj end end C = BLAS.syrk('U', 'N', inv_sw, z) LinearAlgebra.copytri!(C, 'U') MvNormal(mu, PDMat(C)) end function fit_mle(D::Type{DiagNormal}, x::AbstractMatrix{Float64}) m = size(x, 1) n = size(x, 2) mu = vec(mean(x, dims=2)) va = zeros(Float64, m) for j = 1:n for i = 1:m ##CHUNK 2 end function fit_mle(D::Type{FullNormal}, x::AbstractMatrix{Float64}, w::AbstractVector) m = size(x, 1) n = size(x, 2) length(w) == n || throw(DimensionMismatch("Inconsistent argument dimensions")) inv_sw = inv(sum(w)) mu = BLAS.gemv('N', inv_sw, x, w) z = Matrix{Float64}(undef, m, n) for j = 1:n cj = sqrt(w[j]) for i = 1:m @inbounds z[i,j] = (x[i,j] - mu[i]) * cj end end C = BLAS.syrk('U', 'N', inv_sw, z) LinearAlgebra.copytri!(C, 'U') MvNormal(mu, PDMat(C)) ##CHUNK 3 end function fit_mle(D::Type{IsoNormal}, x::AbstractMatrix{Float64}, w::AbstractVector) m = size(x, 1) n = size(x, 2) length(w) == n || throw(DimensionMismatch("Inconsistent argument dimensions")) sw = sum(w) inv_sw = 1.0 / sw mu = BLAS.gemv('N', inv_sw, x, w) va = 0. for j = 1:n @inbounds wj = w[j] va_j = 0. for i = 1:m @inbounds va_j += abs2(x[i,j] - mu[i]) * wj end va += va_j end #FILE: Distributions.jl/src/matrix/wishart.jl ##CHUNK 1 function var(d::Wishart, i::Integer, j::Integer) S = d.S return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2) end # ----------------------------------------------------------------------------- # Evaluation # ----------------------------------------------------------------------------- function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real} p = size(S, 1) if df <= p - 1 return singular_wishart_logc0(p, df, S, rnk) else return nonsingular_wishart_logc0(p, df, S) end end function logkernel(d::Wishart, X::AbstractMatrix) if d.singular ##CHUNK 2 df = d.df return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2 end # Gupta/Nagar (1999) Theorem 3.3.15.i function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer) S = d.S return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k]) end function var(d::Wishart, i::Integer, j::Integer) S = d.S return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2) end # ----------------------------------------------------------------------------- # Evaluation # ----------------------------------------------------------------------------- function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real} #FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl ##CHUNK 1 kp1 = k + 1 for j in 1:(i - 1) A[j, k] = pi * A[j, k] + qi * A[j, kp1] end for j in (i+1):n A[j, k] = pi * A[j, k] + qi * A[j, kp1] end end for j in 1:(i-1) A[j, end] *= pi end for j in (i+1):n A[j, end] *= pi end end @inbounds for j in 1:n, i in 1:n A[i, j] -= A[i, j+1] end return A end #CURRENT FILE: Distributions.jl/src/multivariates.jl Based on the information above, please generate test code for the following function: function cor(d::MultivariateDistribution) C = cov(d) n = size(C, 1) @assert size(C, 2) == n R = Matrix{eltype(C)}(undef, n, n) for j = 1:n for i = 1:j-1 @inbounds R[i, j] = R[j, i] end R[j, j] = 1.0 for i = j+1:n @inbounds R[i, j] = C[i, j] / sqrt(C[i, i] * C[j, j]) end end return R end
{ "fpath_tuple": [ "Distributions.jl", "src", "multivariates.jl" ], "ground_truth": "function cor(d::MultivariateDistribution)\n C = cov(d)\n n = size(C, 1)\n @assert size(C, 2) == n\n R = Matrix{eltype(C)}(undef, n, n)\n\n for j = 1:n\n for i = 1:j-1\n @inbounds R[i, j] = R[j, i]\n end\n R[j, j] = 1.0\n for i = j+1:n\n @inbounds R[i, j] = C[i, j] / sqrt(C[i, i] * C[j, j])\n end\n end\n\n return R\nend", "task_id": "Distributions/88" }
98
115
Distributions.jl
88
function cor(d::MultivariateDistribution) C = cov(d) n = size(C, 1) @assert size(C, 2) == n R = Matrix{eltype(C)}(undef, n, n) for j = 1:n for i = 1:j-1 @inbounds R[i, j] = R[j, i] end R[j, j] = 1.0 for i = j+1:n @inbounds R[i, j] = C[i, j] / sqrt(C[i, i] * C[j, j]) end end return R end
cor(d::MultivariateDistribution)
[ 98, 115 ]
function cor(d::MultivariateDistribution) C = cov(d) n = size(C, 1) @assert size(C, 2) == n R = Matrix{eltype(C)}(undef, n, n) for j = 1:n for i = 1:j-1 @inbounds R[i, j] = R[j, i] end R[j, j] = 1.0 for i = j+1:n @inbounds R[i, j] = C[i, j] / sqrt(C[i, i] * C[j, j]) end end return R end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/product.jl ##CHUNK 1 function __logpdf(d::ArrayOfUnivariateDistribution, x::AbstractArray{<:Real,N}) where {N} # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) # without allocations to compute `sum(logpdf.(d.dists, x))` broadcasted = Broadcast.broadcasted(logpdf, d.dists, x) return sum(Broadcast.instantiate(broadcasted)) end # more efficient implementation of `_rand!` for `Fill` array of univariate distributions function _rand!( rng::AbstractRNG, d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N}, ) where {N} return @inbounds rand!(rng, sampler(first(d.dists)), x) end # more efficient implementation of `_logpdf` for `Fill` array of univariate distributions # we have to fix a method ambiguity function _logpdf( d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N} ##CHUNK 2 end return x end # `_logpdf` for arrays of univariate distributions # we have to fix a method ambiguity function _logpdf(d::ArrayOfUnivariateDistribution, x::AbstractArray{<:Real,N}) where {N} return __logpdf(d, x) end _logpdf(d::MatrixOfUnivariateDistribution, x::AbstractMatrix{<:Real}) = __logpdf(d, x) function __logpdf(d::ArrayOfUnivariateDistribution, x::AbstractArray{<:Real,N}) where {N} # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) # without allocations to compute `sum(logpdf.(d.dists, x))` broadcasted = Broadcast.broadcasted(logpdf, d.dists, x) return sum(Broadcast.instantiate(broadcasted)) end # more efficient implementation of `_rand!` for `Fill` array of univariate distributions function _rand!( rng::AbstractRNG, ##CHUNK 3 # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) return sum(Broadcast.instantiate(Broadcast.broadcasted(entropy, d.dists))) end # fix type instability with tuples entropy(d::VectorOfUnivariateDistribution{<:Tuple}) = sum(entropy, d.dists) ## Vector of univariate distributions length(d::VectorOfUnivariateDistribution) = length(d.dists) ## For matrix distributions cov(d::ProductDistribution{2}, ::Val{false}) = reshape(cov(d), size(d)..., size(d)...) # `_rand!` for arrays of univariate distributions function _rand!( rng::AbstractRNG, d::ArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N}, ) where {N} @inbounds for (i, di) in zip(eachindex(x), d.dists) x[i] = rand(rng, di) ##CHUNK 4 d::ProductDistribution{N,M,<:Fill}, x::AbstractArray{<:Real,N}, ) where {N,M} return __logpdf(d, x) end function _logpdf( d::ProductDistribution{2,M,<:Fill}, x::AbstractMatrix{<:Real}, ) where {M} return __logpdf(d, x) end function __logpdf( d::ProductDistribution{N,M,<:Fill}, x::AbstractArray{<:Real,N}, ) where {N,M} return @inbounds loglikelihood(first(d.dists), x) end """ product_distribution(dists::AbstractArray{<:Distribution{<:ArrayLikeVariate{M}},N}) ##CHUNK 5 ) where {N} return __logpdf(d, x) end _logpdf(d::FillArrayOfUnivariateDistribution{2}, x::AbstractMatrix{<:Real}) = __logpdf(d, x) function __logpdf( d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N} ) where {N} return @inbounds loglikelihood(first(d.dists), x) end # `_rand! for arrays of distributions function _rand!( rng::AbstractRNG, d::ProductDistribution{N,M}, A::AbstractArray{<:Real,N}, ) where {N,M} @inbounds for (di, Ai) in zip(d.dists, eachvariate(A, ArrayLikeVariate{M})) rand!(rng, di, Ai) end return A ##CHUNK 6 d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N}, ) where {N} return @inbounds rand!(rng, sampler(first(d.dists)), x) end # more efficient implementation of `_logpdf` for `Fill` array of univariate distributions # we have to fix a method ambiguity function _logpdf( d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N} ) where {N} return __logpdf(d, x) end _logpdf(d::FillArrayOfUnivariateDistribution{2}, x::AbstractMatrix{<:Real}) = __logpdf(d, x) function __logpdf( d::FillArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N} ) where {N} return @inbounds loglikelihood(first(d.dists), x) end ##CHUNK 7 d::ProductDistribution{N,M,<:Fill}, A::AbstractArray{<:Real,N}, ) where {N,M} @inbounds rand!(rng, sampler(first(d.dists)), A) return A end # more efficient implementation of `_logpdf` for `Fill` arrays of distributions # we have to fix a method ambiguity function _logpdf( d::ProductDistribution{N,M,<:Fill}, x::AbstractArray{<:Real,N}, ) where {N,M} return __logpdf(d, x) end function _logpdf( d::ProductDistribution{2,M,<:Fill}, x::AbstractMatrix{<:Real}, ) where {M} return __logpdf(d, x) ##CHUNK 8 function insupport(d::ArrayOfUnivariateDistribution{N}, x::AbstractArray{<:Real,N}) where {N} size(d) == size(x) && all(insupport(vi, xi) for (vi, xi) in zip(d.dists, x)) end minimum(d::ArrayOfUnivariateDistribution) = map(minimum, d.dists) minimum(d::VectorOfUnivariateDistribution{<:Tuple}) = collect(map(minimum, d.dists)) maximum(d::ArrayOfUnivariateDistribution) = map(maximum, d.dists) maximum(d::VectorOfUnivariateDistribution{<:Tuple}) = collect(map(maximum, d.dists)) function entropy(d::ArrayOfUnivariateDistribution) # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) return sum(Broadcast.instantiate(Broadcast.broadcasted(entropy, d.dists))) end # fix type instability with tuples entropy(d::VectorOfUnivariateDistribution{<:Tuple}) = sum(entropy, d.dists) ## Vector of univariate distributions length(d::VectorOfUnivariateDistribution) = length(d.dists) ## For matrix distributions ##CHUNK 9 # `_rand! for arrays of distributions function _rand!( rng::AbstractRNG, d::ProductDistribution{N,M}, A::AbstractArray{<:Real,N}, ) where {N,M} @inbounds for (di, Ai) in zip(d.dists, eachvariate(A, ArrayLikeVariate{M})) rand!(rng, di, Ai) end return A end # `_logpdf` for arrays of distributions # we have to fix some method ambiguities _logpdf(d::ProductDistribution{N}, x::AbstractArray{<:Real,N}) where {N} = __logpdf(d, x) _logpdf(d::ProductDistribution{2}, x::AbstractMatrix{<:Real}) = __logpdf(d, x) # more efficient implementation of `_rand!` for `Fill` arrays of distributions function _rand!( rng::AbstractRNG, ##CHUNK 10 end function __logpdf( d::ProductDistribution{N,M,<:Fill}, x::AbstractArray{<:Real,N}, ) where {N,M} return @inbounds loglikelihood(first(d.dists), x) end """ product_distribution(dists::AbstractArray{<:Distribution{<:ArrayLikeVariate{M}},N}) Create a distribution of `M + N`-dimensional arrays as a product distribution of independent `M`-dimensional distributions by stacking them. The function falls back to constructing a [`ProductDistribution`](@ref) distribution but specialized methods can be defined. """ function product_distribution(dists::AbstractArray{<:Distribution{<:ArrayLikeVariate}}) return ProductDistribution(dists) end Based on the information above, please generate test code for the following function: function __logpdf( d::ProductDistribution{N,M}, x::AbstractArray{<:Real,N}, ) where {N,M} # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) # to compute `sum(logpdf.(d.dists, eachvariate))` @inbounds broadcasted = Broadcast.broadcasted( logpdf, d.dists, eachvariate(x, ArrayLikeVariate{M}), ) return sum(Broadcast.instantiate(broadcasted)) end
{ "fpath_tuple": [ "Distributions.jl", "src", "product.jl" ], "ground_truth": "function __logpdf(\n d::ProductDistribution{N,M},\n x::AbstractArray{<:Real,N},\n) where {N,M}\n # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020)\n # to compute `sum(logpdf.(d.dists, eachvariate))`\n @inbounds broadcasted = Broadcast.broadcasted(\n logpdf, d.dists, eachvariate(x, ArrayLikeVariate{M}),\n )\n return sum(Broadcast.instantiate(broadcasted))\nend", "task_id": "Distributions/89" }
177
187
Distributions.jl
89
function __logpdf( d::ProductDistribution{N,M}, x::AbstractArray{<:Real,N}, ) where {N,M} # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) # to compute `sum(logpdf.(d.dists, eachvariate))` @inbounds broadcasted = Broadcast.broadcasted( logpdf, d.dists, eachvariate(x, ArrayLikeVariate{M}), ) return sum(Broadcast.instantiate(broadcasted)) end
__logpdf( d::ProductDistribution{N,M}, x::AbstractArray{<:Real,N}, ) where {N,M}
[ 177, 187 ]
function __logpdf( d::ProductDistribution{N,M}, x::AbstractArray{<:Real,N}, ) where {N,M} # we use pairwise summation (https://github.com/JuliaLang/julia/pull/31020) # to compute `sum(logpdf.(d.dists, eachvariate))` @inbounds broadcasted = Broadcast.broadcasted( logpdf, d.dists, eachvariate(x, ArrayLikeVariate{M}), ) return sum(Broadcast.instantiate(broadcasted)) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/continuous/rician.jl ##CHUNK 1 function mode(d::Rician) m = mean(d) _minimize_gss(x -> -pdf(d, x), zero(m), m) end # helper: 1D minimization using Golden-section search function _minimize_gss(f, a, b; tol=1e-12) ϕ = (√5 + 1) / 2 c = b - (b - a) / ϕ d = a + (b - a) / ϕ while abs(b - a) > tol if f(c) < f(d) b = d else a = c end c = b - (b - a) / ϕ d = a + (b - a) / ϕ end #FILE: Distributions.jl/test/truncate.jl ##CHUNK 1 # test if truncated quantile function can be evaluated consistently for different types at certain points @test isapprox(quantile(d, 0), quantile(d, Float32(0))) @test isapprox(quantile(d, 1), quantile(d, Float32(1.0))) @test isapprox(quantile(d, Float64(0.3)), quantile(d, Float32(0.3))) @test isapprox(quantile(d, Float64(0.7)), quantile(d, Float32(0.7))) try m = mgf(d,0.0) @test m == 1.0 m = mgf(d,Dual(0.0)) @test m == 1.0 catch e isa(e, MethodError) || throw(e) end try c = cf(d,0.0) @test c == 1.0 c = cf(d,Dual(0.0)) @test c == 1.0 #FILE: Distributions.jl/src/univariate/continuous/ksdist.jl ##CHUNK 1 end function ceil_rems_mult(n,x) t = big(x)*big(n) cl = ceil(t) lrem = t - (cl - one(cl)) urem = cl - t return convert(typeof(n),cl), convert(typeof(x),lrem), convert(typeof(x),urem) end # n!*(e/n)^n function stirling(n) if n < 500 s = 1.0 for i = 1:n s *= i/n*ℯ end return s else # 3rd-order Stirling's approximation more accurate for large n twn = 12*n #FILE: Distributions.jl/test/testutils.jl ##CHUNK 1 # using Monte Carlo methods if !(isfinite(mean(d)) && isfinite(var(d))) return end vd = var(d) n = length(xs) xmean = mean(xs) xvar = var(xs) xstd = sqrt(xvar) # we utilize central limit theorem, and consider xmean as (approximately) normally # distributed with std = std(d) / sqrt(n) # # For a normal distribution, it is extremely rare for a sample to deviate more # than 5 * std.dev, (chance < 6.0e-7) mean_tol = 5.0 * (sqrt(vd / n)) @test isapprox(mean(d), xmean, atol=mean_tol) ##CHUNK 2 end if !isa(d, StudentizedRange) # check: pdf should be the derivative of cdf for i = 2:(nv-1) if p[i] > 1.0e-6 v = vs[i] ap = (cdf(d, v + 1.0e-6) - cdf(d, v - 1.0e-6)) / (2.0e-6) @test isapprox(p[i], ap, atol=p[i] * 1.0e-3) end end end # consistency of scalar-based and vectorized evaluation if !isa(d, StudentizedRange) @test Base.Fix1(pdf, d).(vs) ≈ p @test Base.Fix1(logpdf, d).(vs) ≈ lp end @test Base.Fix1(cdf, d).(vs) ≈ c #FILE: Distributions.jl/src/samplers/obsoleted.jl ##CHUNK 1 w = h.weight # generate uniform UInt64 objects on the range 0:(w-1) # unfortunately we can't use Range objects, as they don't have sufficient length u = rand(UInt64) if (w & (w-1)) == 0 # power of 2 u = u & (w-1) else m = typemax(UInt64) lim = m - (rem(m,w)+1) while u > lim u = rand(UInt64) end u = rem(u,w) end h[u] end ##CHUNK 2 while !isempty(leafs) || length(branches) > 1 left = isempty(branches) || (!isempty(leafs) && first(leafs) < first(branches)) ? pop!(leafs) : pop!(branches) right = isempty(branches) || (!isempty(leafs) && first(leafs) < first(branches)) ? pop!(leafs) : pop!(branches) pushfirst!(branches,HuffmanBranch(left,right)) end pop!(branches) end function rand(h::HuffmanNode{T}) where T w = h.weight # generate uniform UInt64 objects on the range 0:(w-1) # unfortunately we can't use Range objects, as they don't have sufficient length u = rand(UInt64) if (w & (w-1)) == 0 # power of 2 u = u & (w-1) else m = typemax(UInt64) lim = m - (rem(m,w)+1) #FILE: Distributions.jl/src/samplers/gamma.jl ##CHUNK 1 # We also pre-compute the factor in the squeeze function return GammaMTSampler(promote(d, c, κ, 331//10_000)...) end function rand(rng::AbstractRNG, s::GammaMTSampler{T}) where {T<:Real} d = s.d c = s.c κ = s.κ r = s.r z = zero(T) while true # Generate v (Step 2) x = randn(rng, T) cbrt_v = 1 + c * x while cbrt_v <= z # requires x <= -sqrt(9 * shape - 3) x = randn(rng, T) cbrt_v = 1 + c * x end v = cbrt_v^3 #CURRENT FILE: Distributions.jl/src/quantilealgs.jl ##CHUNK 1 # if starting at mode, Newton is convergent for any unimodal continuous distribution, see: # Göknur Giner, Gordon K. Smyth (2014) # A Monotonically Convergent Newton Iteration for the Quantiles of any Unimodal # Distribution, with Application to the Inverse Gaussian Distribution # http://www.statsci.org/smyth/pubs/qinvgaussPreprint.pdf function quantile_newton(d::ContinuousUnivariateDistribution, p::Real, xs::Real=mode(d), tol::Real=1e-12) x = xs + (p - cdf(d, xs)) / pdf(d, xs) T = typeof(x) if 0 < p < 1 x0 = T(xs) while abs(x-x0) > max(abs(x),abs(x0)) * tol x0 = x x = x0 + (p - cdf(d, x0)) / pdf(d, x0) end return x elseif p == 0 return T(minimum(d)) elseif p == 1 return T(maximum(d)) ##CHUNK 2 # Various algorithms for computing quantile function quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::Real, rx::Real) return quantile_bisect(d, p, promote(lx, rx)...) end quantile_bisect(d::ContinuousUnivariateDistribution, p::Real) = quantile_bisect(d, p, minimum(d), maximum(d)) # if starting at mode, Newton is convergent for any unimodal continuous distribution, see: # Göknur Giner, Gordon K. Smyth (2014) # A Monotonically Convergent Newton Iteration for the Quantiles of any Unimodal # Distribution, with Application to the Inverse Gaussian Distribution # http://www.statsci.org/smyth/pubs/qinvgaussPreprint.pdf function quantile_newton(d::ContinuousUnivariateDistribution, p::Real, xs::Real=mode(d), tol::Real=1e-12) x = xs + (p - cdf(d, xs)) / pdf(d, xs) T = typeof(x) if 0 < p < 1 Based on the information above, please generate test code for the following function: function quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::T, rx::T) where {T<:Real} rx < lx && throw(ArgumentError("empty bracketing interval [$lx, $rx]")) # In some special cases, e.g. #1501, rx == lx` # If the distribution is degenerate the check below can fail, hence we skip it if rx == lx # Returns `lx` of the same type as `(lx + rx) / 2` # For specific types such as `Float64` it is more performant than `oftype((lx + rx) / 2, lx)` return middle(lx) end # base tolerance on types to support e.g. `Float32` (avoids an infinite loop) # ≈ 3.7e-11 for Float64 # ≈ 2.4e-5 for Float32 tol = cbrt(eps(float(T)))^2 # find quantile using bisect algorithm cl = cdf(d, lx) cr = cdf(d, rx) cl <= p <= cr || throw(ArgumentError("[$lx, $rx] is not a valid bracketing interval for `quantile(d, $p)`")) while rx - lx > tol m = (lx + rx)/2 c = cdf(d, m) if p > c cl = c lx = m else cr = c rx = m end end return (lx + rx)/2 end
{ "fpath_tuple": [ "Distributions.jl", "src", "quantilealgs.jl" ], "ground_truth": "function quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::T, rx::T) where {T<:Real}\n rx < lx && throw(ArgumentError(\"empty bracketing interval [$lx, $rx]\"))\n\n # In some special cases, e.g. #1501, rx == lx`\n # If the distribution is degenerate the check below can fail, hence we skip it\n if rx == lx\n # Returns `lx` of the same type as `(lx + rx) / 2`\n # For specific types such as `Float64` it is more performant than `oftype((lx + rx) / 2, lx)`\n return middle(lx)\n end\n\n # base tolerance on types to support e.g. `Float32` (avoids an infinite loop)\n # ≈ 3.7e-11 for Float64\n # ≈ 2.4e-5 for Float32\n tol = cbrt(eps(float(T)))^2\n # find quantile using bisect algorithm\n cl = cdf(d, lx)\n cr = cdf(d, rx)\n cl <= p <= cr ||\n throw(ArgumentError(\"[$lx, $rx] is not a valid bracketing interval for `quantile(d, $p)`\"))\n while rx - lx > tol\n m = (lx + rx)/2\n c = cdf(d, m)\n if p > c\n cl = c\n lx = m\n else\n cr = c\n rx = m\n end\n end\n return (lx + rx)/2\nend", "task_id": "Distributions/90" }
3
35
Distributions.jl
90
function quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::T, rx::T) where {T<:Real} rx < lx && throw(ArgumentError("empty bracketing interval [$lx, $rx]")) # In some special cases, e.g. #1501, rx == lx` # If the distribution is degenerate the check below can fail, hence we skip it if rx == lx # Returns `lx` of the same type as `(lx + rx) / 2` # For specific types such as `Float64` it is more performant than `oftype((lx + rx) / 2, lx)` return middle(lx) end # base tolerance on types to support e.g. `Float32` (avoids an infinite loop) # ≈ 3.7e-11 for Float64 # ≈ 2.4e-5 for Float32 tol = cbrt(eps(float(T)))^2 # find quantile using bisect algorithm cl = cdf(d, lx) cr = cdf(d, rx) cl <= p <= cr || throw(ArgumentError("[$lx, $rx] is not a valid bracketing interval for `quantile(d, $p)`")) while rx - lx > tol m = (lx + rx)/2 c = cdf(d, m) if p > c cl = c lx = m else cr = c rx = m end end return (lx + rx)/2 end
quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::T, rx::T) where {T<:Real}
[ 3, 35 ]
function quantile_bisect(d::ContinuousUnivariateDistribution, p::Real, lx::T, rx::T) where {T<:Real} rx < lx && throw(ArgumentError("empty bracketing interval [$lx, $rx]")) # In some special cases, e.g. #1501, rx == lx` # If the distribution is degenerate the check below can fail, hence we skip it if rx == lx # Returns `lx` of the same type as `(lx + rx) / 2` # For specific types such as `Float64` it is more performant than `oftype((lx + rx) / 2, lx)` return middle(lx) end # base tolerance on types to support e.g. `Float32` (avoids an infinite loop) # ≈ 3.7e-11 for Float64 # ≈ 2.4e-5 for Float32 tol = cbrt(eps(float(T)))^2 # find quantile using bisect algorithm cl = cdf(d, lx) cr = cdf(d, rx) cl <= p <= cr || throw(ArgumentError("[$lx, $rx] is not a valid bracketing interval for `quantile(d, $p)`")) while rx - lx > tol m = (lx + rx)/2 c = cdf(d, m) if p > c cl = c lx = m else cr = c rx = m end end return (lx + rx)/2 end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/cholesky/lkjcholesky.jl ##CHUNK 1 function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky) p = d.d factors = R.factors (isreal(factors) && size(factors, 1) == p) || return false iinds, jinds = axes(factors) # check that the diagonal of U'*U or L*L' is all ones @inbounds if R.uplo === 'U' for (j, jind) in enumerate(jinds) col_iinds = view(iinds, 1:j) sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false end else # R.uplo === 'L' for (i, iind) in enumerate(iinds) row_jinds = view(jinds, 1:i) sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false end end return true end ##CHUNK 2 # ----------------------------------------------------------------------------- # Properties # ----------------------------------------------------------------------------- Base.eltype(::Type{LKJCholesky{T}}) where {T} = T function Base.size(d::LKJCholesky) p = d.d return (p, p) end function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky) p = d.d factors = R.factors (isreal(factors) && size(factors, 1) == p) || return false iinds, jinds = axes(factors) # check that the diagonal of U'*U or L*L' is all ones @inbounds if R.uplo === 'U' for (j, jind) in enumerate(jinds) col_iinds = view(iinds, 1:j) #FILE: Distributions.jl/test/truncate.jl ##CHUNK 1 dname = string(dsym) dsymt = Symbol("truncated($(dct["dtype"]),$lower,$upper") dnamet = string(dsym) # test whether it is included in the selected list # or all are selected (when selected is empty) if !isempty(selected) && !(dname in selected) continue end # perform testing dtype = eval(dsym) dtypet = Truncated d0 = eval(Meta.parse(ex)) if minimum(d0) > lower || maximum(d0) < upper continue end println(" testing truncated($(ex),$lower,$upper)") ##CHUNK 2 function verify_and_test_drive(jsonfile, selected, n_tsamples::Int,lower::Int,upper::Int) R = JSON.parsefile(jsonfile) for dct in R ex = dct["expr"] dsym = Symbol(dct["dtype"]) if dsym in [:Skellam, :NormalInverseGaussian] continue end dname = string(dsym) dsymt = Symbol("truncated($(dct["dtype"]),$lower,$upper") dnamet = string(dsym) # test whether it is included in the selected list # or all are selected (when selected is empty) if !isempty(selected) && !(dname in selected) continue end #FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 support(d::Union{D,Type{D}}) where {D<:ContinuousUnivariateDistribution} = RealInterval(minimum(d), maximum(d)) support(d::Union{D,Type{D}}) where {D<:DiscreteUnivariateDistribution} = round(Int, minimum(d)):round(Int, maximum(d)) # Type used for dispatch on finite support # T = true or false struct FiniteSupport{T} end ## macros to declare support macro distr_support(D, lb, ub) D_has_constantbounds = (isa(ub, Number) || ub == :Inf) && (isa(lb, Number) || lb == :(-Inf)) paramdecl = D_has_constantbounds ? :(d::Union{$D, Type{<:$D}}) : :(d::$D) # overall esc(quote Base.minimum($(paramdecl)) = $lb Base.maximum($(paramdecl)) = $ub end) ##CHUNK 2 D_has_constantbounds = (isa(ub, Number) || ub == :Inf) && (isa(lb, Number) || lb == :(-Inf)) paramdecl = D_has_constantbounds ? :(d::Union{$D, Type{<:$D}}) : :(d::$D) # overall esc(quote Base.minimum($(paramdecl)) = $lb Base.maximum($(paramdecl)) = $ub end) end ##### generic methods (fallback) ##### ## sampling # multiple univariate with pre-allocated array # we use a function barrier since for some distributions `sampler(s)` is not type-stable: # https://github.com/JuliaStats/Distributions.jl/pull/1281 #FILE: Distributions.jl/src/samplers/binomial.jl ##CHUNK 1 comp = true scale = prob < 1.0 ? -1.0/log(prob) : Inf end BinomialGeomSampler(comp, n, scale) end function rand(rng::AbstractRNG, s::BinomialGeomSampler) y = 0 x = 0 n = s.n while true er = randexp(rng) v = er * s.scale if v > n # in case when v is very large or infinity break end y += ceil(Int,v) if y > n break end ##CHUNK 2 while true er = randexp(rng) v = er * s.scale if v > n # in case when v is very large or infinity break end y += ceil(Int,v) if y > n break end x += 1 end (s.comp ? s.n - x : x)::Int end # BTPE algorithm from: # # Kachitvichyanukul, V.; Schmeiser, B. W. # "Binomial random variate generation." #FILE: Distributions.jl/test/testutils.jl ##CHUNK 1 # q01 and q99 are 0.01 and 0.99 quantiles, and count the numbers of samples # falling into each bin. For each bin, we will compute a confidence interval # of the number, and see whether the actual number is in this interval. # # If the distribution has a bounded range, it also checks whether # the samples are all within this range. # # By setting a small q, we ensure that failure of the tests rarely # happen in practice. # verbose && println("test_samples on $(typeof(s))") n > 1 || error("The number of samples must be greater than 1.") nbins > 1 || error("The number of bins must be greater than 1.") 0.0 < q < 0.1 || error("The value of q must be within the open interval (0.0, 0.1).") # determine the range of values to examine vmin = minimum(distr) vmax = maximum(distr) #CURRENT FILE: Distributions.jl/src/show.jl ##CHUNK 1 show(io::IO, d::Distribution) = show(io, d, fieldnames(typeof(d))) # For some distributions, the fields may contain internal details, # which we don't want to show, this function allows one to # specify which fields to show. # function show(io::IO, d::Distribution, pnames) uml, namevals = _use_multline_show(d, pnames) uml ? show_multline(io, d, namevals) : show_oneline(io, d, namevals) end const _NameVal = Tuple{Symbol,Any} function _use_multline_show(d::Distribution) _use_multline_show(d, fieldnames(typeof(d))) end function show_oneline(io::IO, d::Distribution, namevals) Based on the information above, please generate test code for the following function: function _use_multline_show(d::Distribution, pnames) # decide whether to use one-line or multi-line format # # Criteria: if total number of values is greater than 8, or # there are params that are neither numbers, tuples, or vectors, # we use multi-line format # namevals = _NameVal[] multline = false tlen = 0 for (i, p) in enumerate(pnames) pv = getfield(d, p) if !(isa(pv, Number) || isa(pv, NTuple) || isa(pv, AbstractVector)) multline = true else tlen += length(pv) end push!(namevals, (p, pv)) end if tlen > 8 multline = true end return (multline, namevals) end
{ "fpath_tuple": [ "Distributions.jl", "src", "show.jl" ], "ground_truth": "function _use_multline_show(d::Distribution, pnames)\n # decide whether to use one-line or multi-line format\n #\n # Criteria: if total number of values is greater than 8, or\n # there are params that are neither numbers, tuples, or vectors,\n # we use multi-line format\n #\n namevals = _NameVal[]\n multline = false\n tlen = 0\n for (i, p) in enumerate(pnames)\n pv = getfield(d, p)\n if !(isa(pv, Number) || isa(pv, NTuple) || isa(pv, AbstractVector))\n multline = true\n else\n tlen += length(pv)\n end\n push!(namevals, (p, pv))\n end\n if tlen > 8\n multline = true\n end\n return (multline, namevals)\nend", "task_id": "Distributions/91" }
25
48
Distributions.jl
91
function _use_multline_show(d::Distribution, pnames) # decide whether to use one-line or multi-line format # # Criteria: if total number of values is greater than 8, or # there are params that are neither numbers, tuples, or vectors, # we use multi-line format # namevals = _NameVal[] multline = false tlen = 0 for (i, p) in enumerate(pnames) pv = getfield(d, p) if !(isa(pv, Number) || isa(pv, NTuple) || isa(pv, AbstractVector)) multline = true else tlen += length(pv) end push!(namevals, (p, pv)) end if tlen > 8 multline = true end return (multline, namevals) end
_use_multline_show(d::Distribution, pnames)
[ 25, 48 ]
function _use_multline_show(d::Distribution, pnames) # decide whether to use one-line or multi-line format # # Criteria: if total number of values is greater than 8, or # there are params that are neither numbers, tuples, or vectors, # we use multi-line format # namevals = _NameVal[] multline = false tlen = 0 for (i, p) in enumerate(pnames) pv = getfield(d, p) if !(isa(pv, Number) || isa(pv, NTuple) || isa(pv, AbstractVector)) multline = true else tlen += length(pv) end push!(namevals, (p, pv)) end if tlen > 8 multline = true end return (multline, namevals) end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/censored.jl ##CHUNK 1 result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) ##CHUNK 2 elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 3 function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper ##CHUNK 4 return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper ##CHUNK 5 end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) ##CHUNK 6 lower = d.lower upper = d.upper logpx = logpdf(d0, first(x)) log_prob_lower = lower === nothing ? zero(logpx) : oftype(logpx, logcdf(d0, lower)) log_prob_upper = upper === nothing ? zero(logpx) : oftype(logpx, _logccdf_inclusive(d0, upper)) logzero = oftype(logpx, -Inf) return sum(x) do xi _in_open_interval(xi, lower, upper) && return logpdf(d0, xi) xi == lower && return log_prob_lower xi == upper && return log_prob_upper return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) #CURRENT FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end ##CHUNK 2 result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end ##CHUNK 3 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function ccdf(d::Truncated, x::Real) ##CHUNK 4 function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper if tp > 0.25 Based on the information above, please generate test code for the following function: function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end
{ "fpath_tuple": [ "Distributions.jl", "src", "truncate.jl" ], "ground_truth": "function cdf(d::Truncated, x::Real)\n result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1)\n # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial`\n return if d.lower !== nothing && x < d.lower\n zero(result)\n elseif d.upper !== nothing && x >= d.upper\n one(result)\n else\n result\n end\nend", "task_id": "Distributions/92" }
168
178
Distributions.jl
92
function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end
cdf(d::Truncated, x::Real)
[ 168, 178 ]
function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/censored.jl ##CHUNK 1 result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) ##CHUNK 2 elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = logcdf(d.uncensored, x) return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper === nothing || x < d.upper result else zero(result) end end ##CHUNK 3 function ccdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = ccdf(d.uncensored, x) return if lower !== nothing && x < lower one(result) elseif upper === nothing || x < upper result else zero(result) end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper ##CHUNK 4 return logzero end end function cdf(d::Censored, x::Real) lower = d.lower upper = d.upper result = cdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else one(result) end end function logcdf(d::Censored, x::Real) lower = d.lower upper = d.upper ##CHUNK 5 end end function logccdf(d::Censored{<:Any,<:Any,T}, x::Real) where {T} lower = d.lower upper = d.upper result = logccdf(d.uncensored, x) return if lower !== nothing && x < lower zero(result) elseif upper === nothing || x < upper result else oftype(result, -Inf) end end #### Sampling rand(rng::AbstractRNG, d::Censored) = _clamp(rand(rng, d.uncensored), d.lower, d.upper) #CURRENT FILE: Distributions.jl/src/truncate.jl ##CHUNK 1 end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) ##CHUNK 2 return if d.lower !== nothing && x < d.lower zero(result) elseif d.upper !== nothing && x >= d.upper one(result) else result end end function logcdf(d::Truncated, x::Real) result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end ##CHUNK 3 result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp return if d.lower !== nothing && x < d.lower oftype(result, -Inf) elseif d.upper !== nothing && x >= d.upper zero(result) else result end end function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end ##CHUNK 4 function logccdf(d::Truncated, x::Real) result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp return if d.lower !== nothing && x <= d.lower zero(result) elseif d.upper !== nothing && x > d.upper oftype(result, -Inf) else result end end ## random number generation function rand(rng::AbstractRNG, d::Truncated) d0 = d.untruncated tp = d.tp lower = d.lower upper = d.upper if tp > 0.25 ##CHUNK 5 function quantile(d::Truncated, p::Real) x = quantile(d.untruncated, d.lcdf + p * d.tp) min_x, max_x = extrema(d) return clamp(x, oftype(x, min_x), oftype(x, max_x)) end function pdf(d::Truncated, x::Real) result = pdf(d.untruncated, x) / d.tp return _in_closed_interval(x, d.lower, d.upper) ? result : zero(result) end function logpdf(d::Truncated, x::Real) result = logpdf(d.untruncated, x) - d.logtp return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf) end function cdf(d::Truncated, x::Real) result = clamp((cdf(d.untruncated, x) - d.lcdf) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` Based on the information above, please generate test code for the following function: function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end
{ "fpath_tuple": [ "Distributions.jl", "src", "truncate.jl" ], "ground_truth": "function ccdf(d::Truncated, x::Real)\n result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1)\n # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial`\n return if d.lower !== nothing && x <= d.lower\n one(result)\n elseif d.upper !== nothing && x > d.upper\n zero(result)\n else\n result\n end\nend", "task_id": "Distributions/93" }
191
201
Distributions.jl
93
function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end
ccdf(d::Truncated, x::Real)
[ 191, 201 ]
function ccdf(d::Truncated, x::Real) result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1) # Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial` return if d.lower !== nothing && x <= d.lower one(result) elseif d.upper !== nothing && x > d.upper zero(result) else result end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/discrete/categorical.jl ##CHUNK 1 function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real} vfirst = round(Int, first(rgn)) vlast = round(Int, last(rgn)) vl = max(vfirst, 1) vr = min(vlast, ncategories(d)) p = probs(d) if vl > vfirst for i = 1:(vl - vfirst) r[i] = zero(T) end end fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = p[v] end if vr < vlast for i = (vr - vfirst + 2):length(rgn) r[i] = zero(T) end ##CHUNK 2 end end fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = p[v] end if vr < vlast for i = (vr - vfirst + 2):length(rgn) r[i] = zero(T) end end return r end # sampling sampler(d::Categorical{P,Ps}) where {P<:Real,Ps<:AbstractVector{P}} = AliasTable(probs(d)) ##CHUNK 3 cdf(d::Categorical, x::Real) = cdf_int(d, x) ccdf(d::Categorical, x::Real) = ccdf_int(d, x) cdf(d::Categorical, x::Int) = integerunitrange_cdf(d, x) ccdf(d::Categorical, x::Int) = integerunitrange_ccdf(d, x) function pdf(d::Categorical, x::Real) ps = probs(d) return insupport(d, x) ? ps[round(Int, x)] : zero(eltype(ps)) end function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real} vfirst = round(Int, first(rgn)) vlast = round(Int, last(rgn)) vl = max(vfirst, 1) vr = min(vlast, ncategories(d)) p = probs(d) if vl > vfirst for i = 1:(vl - vfirst) r[i] = zero(T) #FILE: Distributions.jl/src/truncated/normal.jl ##CHUNK 1 u = rand(rng) if u < exp(-0.5 * (r - a)^2) && r < ub return r end end elseif ub < 0 && ub - lb > 2.0 / (-ub + sqrt(ub^2 + 4.0)) * exp((ub^2 + ub * sqrt(ub^2 + 4.0)) / 4.0) a = (-ub + sqrt(ub^2 + 4.0)) / 2.0 while true r = rand(rng, Exponential(1.0 / a)) - ub u = rand(rng) if u < exp(-0.5 * (r - a)^2) && r < -lb return -r end end else while true r = lb + rand(rng) * (ub - lb) u = rand(rng) if lb > 0 rho = exp((lb^2 - r^2) * 0.5) ##CHUNK 2 r = randn(rng) end return r else span = ub - lb if lb > 0 && span > 2.0 / (lb + sqrt(lb^2 + 4.0)) * exp((lb^2 - lb * sqrt(lb^2 + 4.0)) / 4.0) a = (lb + sqrt(lb^2 + 4.0))/2.0 while true r = rand(rng, Exponential(1.0 / a)) + lb u = rand(rng) if u < exp(-0.5 * (r - a)^2) && r < ub return r end end elseif ub < 0 && ub - lb > 2.0 / (-ub + sqrt(ub^2 + 4.0)) * exp((ub^2 + ub * sqrt(ub^2 + 4.0)) / 4.0) a = (-ub + sqrt(ub^2 + 4.0)) / 2.0 while true r = rand(rng, Exponential(1.0 / a)) - ub u = rand(rng) ##CHUNK 3 if u < exp(-0.5 * (r - a)^2) && r < -lb return -r end end else while true r = lb + rand(rng) * (ub - lb) u = rand(rng) if lb > 0 rho = exp((lb^2 - r^2) * 0.5) elseif ub < 0 rho = exp((ub^2 - r^2) * 0.5) else rho = exp(-r^2 * 0.5) end if u < rho return r end end end ##CHUNK 4 # Rejection sampler based on algorithm from Robert (1995) # # - Available at http://arxiv.org/abs/0907.4010 function randnt(rng::AbstractRNG, lb::Float64, ub::Float64, tp::Float64) local r::Float64 if tp > 0.3 # has considerable chance of falling in [lb, ub] r = randn(rng) while r < lb || r > ub r = randn(rng) end return r else span = ub - lb if lb > 0 && span > 2.0 / (lb + sqrt(lb^2 + 4.0)) * exp((lb^2 - lb * sqrt(lb^2 + 4.0)) / 4.0) a = (lb + sqrt(lb^2 + 4.0))/2.0 while true r = rand(rng, Exponential(1.0 / a)) + lb #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end return r end abstract type RecursiveProbabilityEvaluator end function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end ##CHUNK 2 function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) ##CHUNK 3 # gradlogpdf gradlogpdf(d::ContinuousUnivariateDistribution, x::Real) = throw(MethodError(gradlogpdf, (d, x))) function _pdf!(r::AbstractArray{<:Real}, d::DiscreteUnivariateDistribution, X::UnitRange) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end return r end abstract type RecursiveProbabilityEvaluator end Based on the information above, please generate test code for the following function: function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange) vl = vfirst = first(X) vr = vlast = last(X) n = vlast - vfirst + 1 if islowerbounded(d) lb = minimum(d) if vl < lb vl = lb end end if isupperbounded(d) ub = maximum(d) if vr > ub vr = ub end end # fill left part if vl > vfirst for i = 1:(vl - vfirst) r[i] = 0.0 end end # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end # fill right part if vr < vlast for i = (vr-vfirst+2):n r[i] = 0.0 end end return vl, vr, vfirst, vlast end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange)\n vl = vfirst = first(X)\n vr = vlast = last(X)\n n = vlast - vfirst + 1\n if islowerbounded(d)\n lb = minimum(d)\n if vl < lb\n vl = lb\n end\n end\n if isupperbounded(d)\n ub = maximum(d)\n if vr > ub\n vr = ub\n end\n end\n\n # fill left part\n if vl > vfirst\n for i = 1:(vl - vfirst)\n r[i] = 0.0\n end\n end\n\n # fill central part: with non-zero pdf\n fm1 = vfirst - 1\n for v = vl:vr\n r[v - fm1] = pdf(d, v)\n end\n\n # fill right part\n if vr < vlast\n for i = (vr-vfirst+2):n\n r[i] = 0.0\n end\n end\n return vl, vr, vfirst, vlast\nend", "task_id": "Distributions/94" }
426
463
Distributions.jl
94
function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange) vl = vfirst = first(X) vr = vlast = last(X) n = vlast - vfirst + 1 if islowerbounded(d) lb = minimum(d) if vl < lb vl = lb end end if isupperbounded(d) ub = maximum(d) if vr > ub vr = ub end end # fill left part if vl > vfirst for i = 1:(vl - vfirst) r[i] = 0.0 end end # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end # fill right part if vr < vlast for i = (vr-vfirst+2):n r[i] = 0.0 end end return vl, vr, vfirst, vlast end
_pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange)
[ 426, 463 ]
function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange) vl = vfirst = first(X) vr = vlast = last(X) n = vlast - vfirst + 1 if islowerbounded(d) lb = minimum(d) if vl < lb vl = lb end end if isupperbounded(d) ub = maximum(d) if vr > ub vr = ub end end # fill left part if vl > vfirst for i = 1:(vl - vfirst) r[i] = 0.0 end end # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end # fill right part if vr < vlast for i = (vr-vfirst+2):n r[i] = 0.0 end end return vl, vr, vfirst, vlast end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/discrete/categorical.jl ##CHUNK 1 function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real} vfirst = round(Int, first(rgn)) vlast = round(Int, last(rgn)) vl = max(vfirst, 1) vr = min(vlast, ncategories(d)) p = probs(d) if vl > vfirst for i = 1:(vl - vfirst) r[i] = zero(T) end end fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = p[v] end if vr < vlast for i = (vr - vfirst + 2):length(rgn) r[i] = zero(T) end ##CHUNK 2 end end fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = p[v] end if vr < vlast for i = (vr - vfirst + 2):length(rgn) r[i] = zero(T) end end return r end # sampling sampler(d::Categorical{P,Ps}) where {P<:Real,Ps<:AbstractVector{P}} = AliasTable(probs(d)) ##CHUNK 3 cdf(d::Categorical, x::Real) = cdf_int(d, x) ccdf(d::Categorical, x::Real) = ccdf_int(d, x) cdf(d::Categorical, x::Int) = integerunitrange_cdf(d, x) ccdf(d::Categorical, x::Int) = integerunitrange_ccdf(d, x) function pdf(d::Categorical, x::Real) ps = probs(d) return insupport(d, x) ? ps[round(Int, x)] : zero(eltype(ps)) end function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real} vfirst = round(Int, first(rgn)) vlast = round(Int, last(rgn)) vl = max(vfirst, 1) vr = min(vlast, ncategories(d)) p = probs(d) if vl > vfirst for i = 1:(vl - vfirst) r[i] = zero(T) #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end # fill right part if vr < vlast for i = (vr-vfirst+2):n r[i] = 0.0 end end return vl, vr, vfirst, vlast end function _pdf!(r::AbstractArray{<:Real}, d::DiscreteUnivariateDistribution, X::UnitRange) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr ##CHUNK 2 end return vl, vr, vfirst, vlast end function _pdf!(r::AbstractArray{<:Real}, d::DiscreteUnivariateDistribution, X::UnitRange) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end return r end abstract type RecursiveProbabilityEvaluator end ### special definitions for distributions with integer-valued support ##CHUNK 3 end # fill left part if vl > vfirst for i = 1:(vl - vfirst) r[i] = 0.0 end end # fill central part: with non-zero pdf fm1 = vfirst - 1 for v = vl:vr r[v - fm1] = pdf(d, v) end # fill right part if vr < vlast for i = (vr-vfirst+2):n r[i] = 0.0 end ##CHUNK 4 lb = minimum(d) if vl < lb vl = lb end end if isupperbounded(d) ub = maximum(d) if vr > ub vr = ub end end # fill left part if vl > vfirst for i = 1:(vl - vfirst) r[i] = 0.0 end end # fill central part: with non-zero pdf ##CHUNK 5 # gradlogpdf gradlogpdf(d::ContinuousUnivariateDistribution, x::Real) = throw(MethodError(gradlogpdf, (d, x))) function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange) vl = vfirst = first(X) vr = vlast = last(X) n = vlast - vfirst + 1 if islowerbounded(d) lb = minimum(d) if vl < lb vl = lb end end if isupperbounded(d) ub = maximum(d) if vr > ub vr = ub end ##CHUNK 6 r[v - fm1] = pdf(d, v) end return r end abstract type RecursiveProbabilityEvaluator end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) ##CHUNK 7 """ invlogccdf(d::UnivariateDistribution, lp::Real) The (generalized) inverse function of [`logccdf`](@ref). For a given `lp ≤ 0`, `invlogccdf(d, lp)` is the smallest value `x` in the support of `d` for which `logccdf(d, x) ≤ lp`. """ invlogccdf(d::UnivariateDistribution, lp::Real) = quantile(d, -expm1(lp)) # gradlogpdf gradlogpdf(d::ContinuousUnivariateDistribution, x::Real) = throw(MethodError(gradlogpdf, (d, x))) function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange) vl = vfirst = first(X) vr = vlast = last(X) n = vlast - vfirst + 1 if islowerbounded(d) Based on the information above, please generate test code for the following function: function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator)\n vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X)\n\n # fill central part: with non-zero pdf\n if vl <= vr\n fm1 = vfirst - 1\n r[vl - fm1] = pv = pdf(d, vl)\n for v = (vl+1):vr\n r[v - fm1] = pv = nextpdf(rpe, pv, v)\n end\n end\n\n return r\nend", "task_id": "Distributions/95" }
479
492
Distributions.jl
95
function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end
_pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator)
[ 479, 492 ]
function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator) vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X) # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/continuous/triangular.jl ##CHUNK 1 #### Evaluation function pdf(d::TriangularDist, x::Real) a, b, c = params(d) res = if x < c 2 * (x - a) / ((b - a) * (c - a)) elseif x > c 2 * (b - x) / ((b - a) * (b - c)) else # Handle x == c separately to avoid `NaN` if `c == a` or `c == b` oftype(x - a, 2) / (b - a) end return insupport(d, x) ? res : zero(res) end logpdf(d::TriangularDist, x::Real) = log(pdf(d, x)) function cdf(d::TriangularDist, x::Real) a, b, c = params(d) if x < c #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) ##CHUNK 2 end function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` ##CHUNK 3 oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else ##CHUNK 4 return r end ### special definitions for distributions with integer-valued support function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end ##CHUNK 5 isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") ##CHUNK 6 # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end ### special definitions for distributions with integer-valued support function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) ##CHUNK 7 oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? zero(c) : c else c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? one(c) : c end return result end ##CHUNK 8 x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end ##CHUNK 9 result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? zero(c) : c else c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? one(c) : c end return result end function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = 1 - sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? one(c) : c else c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) Based on the information above, please generate test code for the following function: function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function cdf_int(d::DiscreteUnivariateDistribution, x::Real)\n # handle `NaN` and `±Inf` which can't be truncated to `Int`\n isfinite_x = isfinite(x)\n _x = isfinite_x ? x : zero(x)\n c = float(cdf(d, floor(Int, _x)))\n return if isfinite_x\n c\n elseif isnan(x)\n oftype(c, NaN)\n elseif x < 0\n zero(c)\n else\n one(c)\n end\nend", "task_id": "Distributions/96" }
496
510
Distributions.jl
96
function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end
cdf_int(d::DiscreteUnivariateDistribution, x::Real)
[ 496, 510 ]
function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/continuous/triangular.jl ##CHUNK 1 #### Evaluation function pdf(d::TriangularDist, x::Real) a, b, c = params(d) res = if x < c 2 * (x - a) / ((b - a) * (c - a)) elseif x > c 2 * (b - x) / ((b - a) * (b - c)) else # Handle x == c separately to avoid `NaN` if `c == a` or `c == b` oftype(x - a, 2) / (b - a) end return insupport(d, x) ? res : zero(res) end logpdf(d::TriangularDist, x::Real) = log(pdf(d, x)) function cdf(d::TriangularDist, x::Real) a, b, c = params(d) if x < c #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) ##CHUNK 2 function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` ##CHUNK 3 oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else ##CHUNK 4 return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end ##CHUNK 5 isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") ##CHUNK 6 # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) ##CHUNK 7 oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? zero(c) : c else c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? one(c) : c end return result end ##CHUNK 8 x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end ##CHUNK 9 result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? zero(c) : c else c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? one(c) : c end return result end function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = 1 - sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? one(c) : c else c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) Based on the information above, please generate test code for the following function: function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function ccdf_int(d::DiscreteUnivariateDistribution, x::Real)\n # handle `NaN` and `±Inf` which can't be truncated to `Int`\n isfinite_x = isfinite(x)\n _x = isfinite_x ? x : zero(x)\n c = float(ccdf(d, floor(Int, _x)))\n return if isfinite_x\n c\n elseif isnan(x)\n oftype(c, NaN)\n elseif x < 0\n one(c)\n else\n zero(c)\n end\nend", "task_id": "Distributions/97" }
512
526
Distributions.jl
97
function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end
ccdf_int(d::DiscreteUnivariateDistribution, x::Real)
[ 512, 526 ]
function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) ##CHUNK 2 function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` ##CHUNK 3 elseif x < 0 one(c) else zero(c) end end function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else ##CHUNK 4 return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end ##CHUNK 5 isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") ##CHUNK 6 # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) ##CHUNK 7 x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end ##CHUNK 8 function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = log1mexp(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))) x < minimum_d ? zero(c) : c else c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? oftype(c, -Inf) : c end return result end ### macros to use StatsFuns for method implementation macro _delegate_statsfuns(D, fpre, psyms...) # function names from StatsFuns ##CHUNK 9 result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = log1mexp(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))) x < minimum_d ? zero(c) : c else c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d) ##CHUNK 10 oftype(c, -Inf) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d))) x < minimum_d ? zero(c) : c else c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? one(c) : c end return result end Based on the information above, please generate test code for the following function: function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function logcdf_int(d::DiscreteUnivariateDistribution, x::Real)\n # handle `NaN` and `±Inf` which can't be truncated to `Int`\n isfinite_x = isfinite(x)\n _x = isfinite_x ? x : zero(x)\n c = float(logcdf(d, floor(Int, _x)))\n return if isfinite_x\n c\n elseif isnan(x)\n oftype(c, NaN)\n elseif x < 0\n oftype(c, -Inf)\n else\n zero(c)\n end\nend", "task_id": "Distributions/98" }
528
542
Distributions.jl
98
function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end
logcdf_int(d::DiscreteUnivariateDistribution, x::Real)
[ 528, 542 ]
function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end
Your task is to generate only the test code for the given focal function in Julia programming language. Instructions: - Use the Test module with idiomatic @testset and @test macros. - (IMPORTANT) Always refer to the focal function using the module_name.function_name format — even if it is exported. - Do NOT rewrite or include the function definition. - Make sure to test different input types, edge cases, and assertions. - Only generate the test code block. Generate the test code using this format: ```julia using Test using ModuleName @testset "Test function_name" begin @test ModuleName.function_name(args...) == expected # Add more test cases end ``` Here is all the context you may find useful to generate the test: #FILE: Distributions.jl/src/univariate/continuous/triangular.jl ##CHUNK 1 #### Evaluation function pdf(d::TriangularDist, x::Real) a, b, c = params(d) res = if x < c 2 * (x - a) / ((b - a) * (c - a)) elseif x > c 2 * (b - x) / ((b - a) * (b - c)) else # Handle x == c separately to avoid `NaN` if `c == a` or `c == b` oftype(x - a, 2) / (b - a) end return insupport(d, x) ? res : zero(res) end logpdf(d::TriangularDist, x::Real) = log(pdf(d, x)) function cdf(d::TriangularDist, x::Real) a, b, c = params(d) if x < c #CURRENT FILE: Distributions.jl/src/univariates.jl ##CHUNK 1 function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 one(c) else zero(c) end end function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) ##CHUNK 2 elseif x < 0 one(c) else zero(c) end end function logcdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) ##CHUNK 3 return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end function ccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(ccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) ##CHUNK 4 return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else one(c) end end ##CHUNK 5 _x = isfinite_x ? x : zero(x) c = float(logcdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 oftype(c, -Inf) else zero(c) end end # implementation of the cdf for distributions whose support is a unitrange of integers # note: incorrect for discrete distributions whose support includes non-integer numbers function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") ##CHUNK 6 # fill central part: with non-zero pdf if vl <= vr fm1 = vfirst - 1 r[vl - fm1] = pv = pdf(d, vl) for v = (vl+1):vr r[v - fm1] = pv = nextpdf(rpe, pv, v) end end return r end ### special definitions for distributions with integer-valued support function cdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(cdf(d, floor(Int, _x))) ##CHUNK 7 x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end ##CHUNK 8 function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = log1mexp(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))) x < minimum_d ? zero(c) : c else c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d) x >= maximum_d ? oftype(c, -Inf) : c end return result end ### macros to use StatsFuns for method implementation macro _delegate_statsfuns(D, fpre, psyms...) # function names from StatsFuns ##CHUNK 9 result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))) x < minimum_d ? oftype(c, -Inf) : c else c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)) x >= maximum_d ? zero(c) : c end return result end function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer) minimum_d, maximum_d = extrema(d) isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded") result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2)) c = log1mexp(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))) x < minimum_d ? zero(c) : c else c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d) Based on the information above, please generate test code for the following function: function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end
{ "fpath_tuple": [ "Distributions.jl", "src", "univariates.jl" ], "ground_truth": "function logccdf_int(d::DiscreteUnivariateDistribution, x::Real)\n # handle `NaN` and `±Inf` which can't be truncated to `Int`\n isfinite_x = isfinite(x)\n _x = isfinite_x ? x : zero(x)\n c = float(logccdf(d, floor(Int, _x)))\n return if isfinite_x\n c\n elseif isnan(x)\n oftype(c, NaN)\n elseif x < 0\n zero(c)\n else\n oftype(c, -Inf)\n end\nend", "task_id": "Distributions/99" }
544
558
Distributions.jl
99
function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end
logccdf_int(d::DiscreteUnivariateDistribution, x::Real)
[ 544, 558 ]
function logccdf_int(d::DiscreteUnivariateDistribution, x::Real) # handle `NaN` and `±Inf` which can't be truncated to `Int` isfinite_x = isfinite(x) _x = isfinite_x ? x : zero(x) c = float(logccdf(d, floor(Int, _x))) return if isfinite_x c elseif isnan(x) oftype(c, NaN) elseif x < 0 zero(c) else oftype(c, -Inf) end end