问:
Using MPI with Multi-threading in Julia
I have some issues while using multi-threading with MPI.jl. For multi-threading, I am using the Floops package. Here is the minimal code

```<code>function shiftInverse(A, s, n)

    A = Matrix(A)
    F = lu(A - s * I)
    A_lmap = LinearMap{eltype(A)}((y, x) -> ldiv!(y, F, x), size(A, 1), ismutating=true)
    decomp, = partialschur(A_lmap, nev=n, tol=1e-5, restarts=100, which=LM())
    _, X = partialeigen(decomp)

    return X
end

function func(mag, l, J, ϵ, nphi, ens)

    basis = buildBasis(l)
    N = 2^l; η = binomial(l, Int(l/2))
    # avgEE = similar(mag)
    stdEE = similar(mag)

    for (i,h) in enumerate(mag)
        H_init = buildHNonRnd(η, l, basis, J) + buildHRnd(h, basis, η, l)
        e0, = eigs(H_init; nev=1, which=:SM, ritzvec=false)
        emax, = eigs(H_init; nev=1, which=:LM, ritzvec=false)
        e = (e0[1] - emax[1]) * ϵ + emax[1]
        H_0 = buildHNonRnd(η, l, basis, J)
        ee = Vector{Float64}(undef, ens)

        @floop for m in 1:ens

            H = H_0 + buildHRnd(h, basis, η, l)
            ϕ = shiftInverse(H, e, nphi)
            ee[m] = getEE(ϕ, N, η, l, nphi)

        end

        # avgEE[i] = mean(ee)
        stdEE[i] = std(ee)

        print("completed h = $h \n")
        flush(stdout)

    end

    return stdEE

end
</code>```

And the MPI part

```<code>function main()

    L = 4
    sampleSize = 500
    h_arr = round.(LinRange(0.1, 8, 30), digits=3)
    J = 1.0; ϵ = 0.5; nphi = 5

    MPI.Init()
    comm = MPI.COMM_WORLD
    size = MPI.Comm_size(comm)
    rank = MPI.Comm_rank(comm)

    magLenNodes = div(length(h_arr), size)
    send_buf = zeros(magLenNodes)

    magRec = MPI.Scatter!(MPI.UBuffer(h_arr, magLenNodes), send_buf, 0, comm)

    magRec = func(send_buf, L, J, ϵ, nphi, sampleSize)

    recv_msg = MPI.Gather(magRec, 0, comm)

    if rank == 0
    print("completed, $recv_msg \n")
    end
    # end

    MPI.Barrier(comm)

end
</code>```

I ran the code with JULIA_NUM_THREADS=4 and mpiexec -n 2 julia example.jl, and got this error:

```<code>signal (11): Segmentation fault

signal (11): Segmentation fault
in expression starting at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:314
in expression starting at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:314
jl_gc_alloc at /home/20ph92r03/julia-1.8.0/bin/../lib/julia/libjulia-internal.so.1 (unknown line)
ijl_alloc_array_1d at /home/20ph92r03/julia-1.8.0/bin/../lib/julia/libjulia-internal.so.1 (unknown line)
Array at ./boot.jl:459 [inlined]
Array at ./boot.jl:468 [inlined]
similar at ./array.jl:378 [inlined]
similar at ./subarray.jl:65 [inlined]
similar at ./abstractarray.jl:797 [inlined]
* at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/matmul.jl:101 [inlined]
orthogonalize! at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/expansion.jl:89
iterate_arnoldi! at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/expansion.jl:123
_partialschur at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:185
jl_gc_state_set at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_threads.h:340 [inlined]
#partialschur#1 at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:106
maybe_collect at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_threads.h:333 [inlined]
jl_gc_pool_alloc_inner at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:1247 [inlined]
partialschur##kw at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:94 [inlined]
shiftInverse at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:164
jl_gc_pool_alloc_noinline at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:1306 [inlined]
macro expansion at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:217 [inlined]
__##reducing_function#313 at /home/20ph92r03/.julia/packages/FLoops/3ZEuy/src/reduce.jl:817 [inlined]
AdjoinIdentity at /home/20ph92r03/.julia/packages/InitialValues/OWP8V/src/InitialValues.jl:306
jl_gc_alloc_ at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_internal.h:369 [inlined]
jl_gc_alloc at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:3371
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/combinators.jl:290 [inlined]
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:289 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:181 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:199 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/simd.jl:41 [inlined]
_foldl_linear_bulk at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:198 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:192 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/basics.jl:115 [inlined]
_foldl_array at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:188 [inlined]
__foldl__ at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:182 [inlined]
foldl_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:365 [inlined]
_reduce_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/threading_utils.jl:56
_reduce at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/reduce.jl:150
#167 at ./threadingconstructs.jl:258
unknown function (ip: 0x2ad40bc67caf)
_new_array_ at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:134 [inlined]
_new_array at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:198 [inlined]
ijl_alloc_array_1d at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:436
_jl_invoke at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2367 [inlined]
ijl_apply_generic at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2549
Array at ./boot.jl:459 [inlined]
Array at ./boot.jl:468 [inlined]
similar at ./array.jl:378 [inlined]
similar at ./abstractarray.jl:797 [inlined]
getrf! at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lapack.jl:563
#lu!#172 at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:81 [inlined]
lu!##kw at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:80 [inlined]
#lu#179 at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:279 [inlined]
lu at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:278 [inlined]
lu at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:278 [inlined]
shiftInverse at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:160
macro expansion at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:217 [inlined]
__##reducing_function#313 at /home/20ph92r03/.julia/packages/FLoops/3ZEuy/src/reduce.jl:817 [inlined]
AdjoinIdentity at /home/20ph92r03/.julia/packages/InitialValues/OWP8V/src/InitialValues.jl:306
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/combinators.jl:290 [inlined]
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:289 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:181 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:199 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/simd.jl:41 [inlined]
_foldl_linear_bulk at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:198 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:192 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/basics.jl:115 [inlined]
_foldl_array at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:188 [inlined]
__foldl__ at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:182 [inlined]
foldl_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:365 [inlined]
_reduce_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/threading_utils.jl:56
_reduce at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/reduce.jl:150
#167 at ./threadingconstructs.jl:258
unknown function (ip: 0x2ad40bc67caf)
_jl_invoke at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2367 [inlined]
ijl_apply_generic at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2549

===================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   RANK 1 PID 53989 RUNNING AT cn039
=   KILLED BY SIGNAL: 11 (Segmentation fault)
===================================================================================
</code>```

In fact, the error is gone if I set nphi = 1, which modifies the nev argument of partialshur function used in the function shiftInverse defined above. I read that using Multi-threading has known issues in the MPI.jl documentation (https://juliaparallel.org/MPI.jl/stable/knownissues/#Multi-threading-and-signal-handling). However, the fix prescribed there doesn’t work for me. I even tried setting the environment variable UCX_ERROR_SIGNALS="", but it crashes.

Can you please suggest something which I can try? It works without multi-threading though!

Title: Using MPI with Multi-threading in Julia

Body:
I have some issues while using multi-threading with MPI.jl. For multi-threading, I am using the Floops package. Here is the minimal code

function shiftInverse(A, s, n)

    A = Matrix(A)
    F = lu(A - s * I)
    A_lmap = LinearMap{eltype(A)}((y, x) -> ldiv!(y, F, x), size(A, 1), ismutating=true)
    decomp, = partialschur(A_lmap, nev=n, tol=1e-5, restarts=100, which=LM())
    _, X = partialeigen(decomp)

    return X
end

function func(mag, l, J, ϵ, nphi, ens)

    basis = buildBasis(l)
    N = 2^l; η = binomial(l, Int(l/2))
    # avgEE = similar(mag)
    stdEE = similar(mag)

    for (i,h) in enumerate(mag)
        H_init = buildHNonRnd(η, l, basis, J) + buildHRnd(h, basis, η, l)
        e0, = eigs(H_init; nev=1, which=:SM, ritzvec=false)
        emax, = eigs(H_init; nev=1, which=:LM, ritzvec=false)
        e = (e0[1] - emax[1]) * ϵ + emax[1]
        H_0 = buildHNonRnd(η, l, basis, J)
        ee = Vector{Float64}(undef, ens)

        @floop for m in 1:ens

            H = H_0 + buildHRnd(h, basis, η, l)
            ϕ = shiftInverse(H, e, nphi)
            ee[m] = getEE(ϕ, N, η, l, nphi)

        end

        # avgEE[i] = mean(ee)
        stdEE[i] = std(ee)

        print("completed h = $h \n")
        flush(stdout)

    end

    return stdEE

end

And the MPI part

function main()

    L = 4
    sampleSize = 500
    h_arr = round.(LinRange(0.1, 8, 30), digits=3)
    J = 1.0; ϵ = 0.5; nphi = 5

    MPI.Init()
    comm = MPI.COMM_WORLD
    size = MPI.Comm_size(comm)
    rank = MPI.Comm_rank(comm)

    magLenNodes = div(length(h_arr), size)
    send_buf = zeros(magLenNodes)

    magRec = MPI.Scatter!(MPI.UBuffer(h_arr, magLenNodes), send_buf, 0, comm)

    magRec = func(send_buf, L, J, ϵ, nphi, sampleSize)

    recv_msg = MPI.Gather(magRec, 0, comm)

    if rank == 0
    print("completed, $recv_msg \n")
    end
    # end

    MPI.Barrier(comm)

end

I ran the code with JULIA_NUM_THREADS=4 and mpiexec -n 2 julia example.jl, and got this error:

signal (11): Segmentation fault

signal (11): Segmentation fault
in expression starting at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:314
in expression starting at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:314
jl_gc_alloc at /home/20ph92r03/julia-1.8.0/bin/../lib/julia/libjulia-internal.so.1 (unknown line)
ijl_alloc_array_1d at /home/20ph92r03/julia-1.8.0/bin/../lib/julia/libjulia-internal.so.1 (unknown line)
Array at ./boot.jl:459 [inlined]
Array at ./boot.jl:468 [inlined]
similar at ./array.jl:378 [inlined]
similar at ./subarray.jl:65 [inlined]
similar at ./abstractarray.jl:797 [inlined]
* at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/matmul.jl:101 [inlined]
orthogonalize! at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/expansion.jl:89
iterate_arnoldi! at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/expansion.jl:123
_partialschur at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:185
jl_gc_state_set at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_threads.h:340 [inlined]
#partialschur#1 at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:106
maybe_collect at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_threads.h:333 [inlined]
jl_gc_pool_alloc_inner at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:1247 [inlined]
partialschur##kw at /home/20ph92r03/.julia/packages/ArnoldiMethod/JdEiw/src/run.jl:94 [inlined]
shiftInverse at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:164
jl_gc_pool_alloc_noinline at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:1306 [inlined]
macro expansion at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:217 [inlined]
__##reducing_function#313 at /home/20ph92r03/.julia/packages/FLoops/3ZEuy/src/reduce.jl:817 [inlined]
AdjoinIdentity at /home/20ph92r03/.julia/packages/InitialValues/OWP8V/src/InitialValues.jl:306
jl_gc_alloc_ at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/julia_internal.h:369 [inlined]
jl_gc_alloc at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gc.c:3371
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/combinators.jl:290 [inlined]
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:289 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:181 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:199 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/simd.jl:41 [inlined]
_foldl_linear_bulk at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:198 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:192 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/basics.jl:115 [inlined]
_foldl_array at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:188 [inlined]
__foldl__ at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:182 [inlined]
foldl_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:365 [inlined]
_reduce_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/threading_utils.jl:56
_reduce at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/reduce.jl:150
#167 at ./threadingconstructs.jl:258
unknown function (ip: 0x2ad40bc67caf)
_new_array_ at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:134 [inlined]
_new_array at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:198 [inlined]
ijl_alloc_array_1d at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/array.c:436
_jl_invoke at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2367 [inlined]
ijl_apply_generic at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2549
Array at ./boot.jl:459 [inlined]
Array at ./boot.jl:468 [inlined]
similar at ./array.jl:378 [inlined]
similar at ./abstractarray.jl:797 [inlined]
getrf! at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lapack.jl:563
#lu!#172 at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:81 [inlined]
lu!##kw at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:80 [inlined]
#lu#179 at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:279 [inlined]
lu at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:278 [inlined]
lu at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/usr/share/julia/stdlib/v1.8/LinearAlgebra/src/lu.jl:278 [inlined]
shiftInverse at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:160
macro expansion at /scratch/20ph92r03/juliafiles/proj_2/mblPTmpi.jl:217 [inlined]
__##reducing_function#313 at /home/20ph92r03/.julia/packages/FLoops/3ZEuy/src/reduce.jl:817 [inlined]
AdjoinIdentity at /home/20ph92r03/.julia/packages/InitialValues/OWP8V/src/InitialValues.jl:306
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/combinators.jl:290 [inlined]
next at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:289 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/core.jl:181 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:199 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/simd.jl:41 [inlined]
_foldl_linear_bulk at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:198 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:192 [inlined]
macro expansion at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/basics.jl:115 [inlined]
_foldl_array at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:188 [inlined]
__foldl__ at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:182 [inlined]
foldl_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/processes.jl:365 [inlined]
_reduce_basecase at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/threading_utils.jl:56
_reduce at /home/20ph92r03/.julia/packages/Transducers/HBMTc/src/reduce.jl:150
#167 at ./threadingconstructs.jl:258
unknown function (ip: 0x2ad40bc67caf)
_jl_invoke at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2367 [inlined]
ijl_apply_generic at /cache/build/default-amdci4-3/julialang/julia-release-1-dot-8/src/gf.c:2549

===================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   RANK 1 PID 53989 RUNNING AT cn039
=   KILLED BY SIGNAL: 11 (Segmentation fault)
===================================================================================

In fact, the error is gone if I set nphi = 1, which modifies the nev argument of partialshur function used in the function shiftInverse defined above. I read that using Multi-threading has known issues in the MPI.jl documentation (https://juliaparallel.org/MPI.jl/stable/knownissues/#Multi-threading-and-signal-handling). However, the fix prescribed there doesn’t work for me. I even tried setting the environment variable UCX_ERROR_SIGNALS="", but it crashes.

Can you please suggest something which I can try? It works without multi-threading though!


来源: stackexchange

问:
Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail || Dialogflow || Firebase Realtime Database
I was trying to connect firebase realtime database with dialogflow. and I want, when user ask question to chatbot it will read data from firebase realtime database and show that data to user. I have tried this way:-

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const firebaseAdmin = require("firebase-admin");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeApp({
     apiKey: "AI*********************",
  authDomain: "**********.firebaseapp.com",
  databaseURL:"https://**************.firebaseio.com",
  storageBucket:"*******.appspot.com",
  messagingSenderId: "***************",
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to akvo agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function getFromFirebase(agent){
    return firebaseAdmin.database().ref('board_id').once("value").then((snapshot) => {
    var boardid = snapshot.val();
      agent.add(boardid);
    });
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('board id', getFromFirebase);
  agent.handleRequest(intentMap);
});```
</div>
</div>
</p>
<p>This is my Package.json</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "10"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "^2.2.0",
    "firebase-admin": "^5.13.1",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.5.0"
  }
}</code>```

after deploying this code I am getting an error.

In Logs explorer :- Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail

FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Failed to parse access token response: SyntaxError: Unexpected token M in JSON at position 0"."}

In Diagnostic info Fulfillment status :- "Webhook call failed. Error: DEADLINE_EXCEEDED,
State: URL_TIMEOUT, Reason: TIMEOUT_WEB."

Please help to solve this problem.

ContentLicense: CC BY-SA 4.0

Body:
I was trying to connect firebase realtime database with dialogflow. and I want, when user ask question to chatbot it will read data from firebase realtime database and show that data to user. I have tried this way:-

'use strict';

const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const firebaseAdmin = require("firebase-admin");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

 firebaseAdmin.initializeApp({
     apiKey: "AI*********************",
  authDomain: "**********.firebaseapp.com",
  databaseURL:"https://**************.firebaseio.com",
  storageBucket:"*******.appspot.com",
  messagingSenderId: "***************",
});

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));

  function welcome(agent) {
    agent.add(`Welcome to akvo agent!`);
  }

  function fallback(agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  function getFromFirebase(agent){
    return firebaseAdmin.database().ref('board_id').once("value").then((snapshot) => {
    var boardid = snapshot.val();
      agent.add(boardid);
    });
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('board id', getFromFirebase);
  agent.handleRequest(intentMap);
});

This is my Package.json

{
  "name": "dialogflowFirebaseFulfillment",
  "description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": "10"
  },
  "scripts": {
    "start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
    "deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
  },
  "dependencies": {
    "actions-on-google": "^2.2.0",
    "firebase-admin": "^5.13.1",
    "firebase-functions": "^2.0.2",
    "dialogflow": "^0.6.0",
    "dialogflow-fulfillment": "^0.5.0"
  }
}

after deploying this code I am getting an error.

In Logs explorer :- Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail

FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Failed to parse access token response: SyntaxError: Unexpected token M in JSON at position 0"."}

In Diagnostic info Fulfillment status :- "Webhook call failed. Error: DEADLINE_EXCEEDED,
State: URL_TIMEOUT, Reason: TIMEOUT_WEB."

Please help to solve this problem.


问:
update datatable when selecting network node in bokeh
I am able to generate an interactive networkx (How to add permanent name labels (not interactive ones) on nodes for a networkx graph in bokeh?)using BOKEH, and a nice table (Display a pandas data frame with Bokeh), is it possible to make these two visuals interactive?

I am interested in the ability to select a node, which updates the datatable showing info related to the node.


问:
openmp with fftw gcc
I have a parallel for loop (with typically 1000 iterations) with multiple calculations.
At one point I need to make:

fftw_plan_dft_r2c_1d
on a set of data.

again fftw_plan_dft_r2c_1d
on another set of data.

again fftw_plan_dft_r2c_1d

make calculations on the data calculated by fftw

make fftw_plan_dft_c2r_1d

again fftw_plan_dft_c2r_1d
Unfortunately, I cannot create the plans before entering in the parallel region.
The number of data is always a factor of 2.
The data to transform change at each iteration of the loop
Even if I try to use the same plan, I need to update the data, and this create a mess because they are not private but shared if I understand correctly.

What is the solution?

Have a solution to the issue

Title: openmp with fftw gcc


问:
Error when using traefik to generate SSL certificate in aws elastic beanstalk
I have a website running in AWS using elastic beanstalk service. I'm using docker to deploy it, by importing a docker-compose file that pulls and runs an image from my dockerhub repository. I also have a 53 route redirecting to my website, so it's working great until now. Here is my very simple docker-compose file:

```<code>version: "3.8"
services:
  backend:
    image: "mypersonalrepo/image:tag"
    ports:
      - "80:8080"
    restart: "always"
</code>```

The problem is that only works with http since I don't have any SSL certifcate, so I want to generate one.
I thought about using Traefik, because it seems like a good tool to use right now and use it with kubernetes in the future

I'm trying to use traefik to generate one certificate and redirect all traffic to my application, and this is what I'm trying to deploy:

```<code>version: "3.8"
services:
  backend:
    image: "mypersonalrepo/image:tag"
    restart: "always"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.backend.rule=Host(`my.53.route.net`)"
      - "traefik.http.routers.backend.entrypoints=websecure"
      - "traefik.http.routers.backend.tls.certresolver=myresolver"
      - "traefik.http.services.backend.loadbalancer.server.port=8080"
    depends_on:
      - traefik

  traefik:
    image: "traefik:v2.9"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.myresolver.acme.httpchallenge=true"
      - "--certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web"
      - "--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"
      - "--certificatesresolvers.myresolver.acme.email=myemail@gmail.com"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - "./letsencrypt:/letsencrypt"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
</code>```

I'm getting errors when deploying it, but cannot understand what's going on. Maybe I need to add port 443 in my EC2 instance security group. And that is probably not enough, just feel a bit lost and don't know what the next steps are.

After I deploy it with the new docker-compose file, health will go to Severe condition

Body:
I have a website running in AWS using elastic beanstalk service. I'm using docker to deploy it, by importing a docker-compose file that pulls and runs an image from my dockerhub repository. I also have a 53 route redirecting to my website, so it's working great until now. Here is my very simple docker-compose file:

version: "3.8"
services:
  backend:
    image: "mypersonalrepo/image:tag"
    ports:
      - "80:8080"
    restart: "always"

The problem is that only works with http since I don't have any SSL certifcate, so I want to generate one.
I thought about using Traefik, because it seems like a good tool to use right now and use it with kubernetes in the future

I'm trying to use traefik to generate one certificate and redirect all traffic to my application, and this is what I'm trying to deploy:

version: "3.8"
services:
  backend:
    image: "mypersonalrepo/image:tag"
    restart: "always"
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.backend.rule=Host(`my.53.route.net`)"
      - "traefik.http.routers.backend.entrypoints=websecure"
      - "traefik.http.routers.backend.tls.certresolver=myresolver"
      - "traefik.http.services.backend.loadbalancer.server.port=8080"
    depends_on:
      - traefik

  traefik:
    image: "traefik:v2.9"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.myresolver.acme.httpchallenge=true"
      - "--certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web"
      - "--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"
      - "--certificatesresolvers.myresolver.acme.email=myemail@gmail.com"
      - "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - "./letsencrypt:/letsencrypt"
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

I'm getting errors when deploying it, but cannot understand what's going on. Maybe I need to add port 443 in my EC2 instance security group. And that is probably not enough, just feel a bit lost and don't know what the next steps are.

After I deploy it with the new docker-compose file, health will go to Severe condition


问:
Authentication error: "The provider field is required"
What could be the problem I get the following when launching in localhost my .net core application:

```<code>POST http://localhost:5000/api/Authentication/login 400 (Bad Request)

{"errors":{"provider":["The provider field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1", "title":"One or more validation errors occurred.","status":400,"traceId":"00-[...]-00"}
</code>```

That is the first try for my migrated and refactored .NET 7 web api application from .NET 5, where everything worked well, I use same Azure authentication data from the "old" application:

in secrets:

in appsettings.json:

```<code>{
  "AllowedHosts": "*",
  "Authentication": {
    "Azure": {
      "AADInstance": "https://login.microsoftonline.com/",
      "CallbackPath": "/signin-oidc"
    }
  },
</code>```

and in Program.cs:

```<code>// ------------
// Configure Services
// ------------
string? connectionString = builder.Configuration.GetConnectionString("SqlServerConnection");
var configuration = builder.Configuration;

// Identity
builder.Services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

// Authentication
var clientId = configuration.GetValue<string>("Authentication:Azure:ClientId");
if (clientId == null)
    throw new System.Configuration.ConfigurationErrorsException("Missing Azure configuration");

builder.Services.AddAuthentication()
    .AddOpenIdConnect(
        options =>
        {
            options.ClientId = configuration.GetValue<string>("Authentication:Azure:ClientId");
            options.ClientSecret = configuration.GetValue<string>("Authentication:Azure:ClientSecret");
            options.Authority =
                            $"{configuration.GetValue<string>("Authentication:Azure:AADInstance")}{configuration.GetValue<string>("Authentication:Azure:TenantId")}";
            options.CallbackPath = configuration.GetValue<string>("Authentication:Azure:CallbackPath");
            options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
        });
</code>```

The Index.cshtml page that autehticate the user

```<code>@inject SignInManager<User> SignInManager

<body>
  <h2>Development Mode</h2>
  <p>This page is used for authentication in development mode only. It will be automatically replaced with the Angular
    generated one.</p>
  @{
    var providers = await SignInManager.GetExternalAuthenticationSchemesAsync();
    if (!providers.Any())
    {
      <div>
        <p>
          There are no external authentication services configured.
        </p>
      </div>
    }
    else
    {
      <form asp-controller="Authentication" asp-action="ExternalLogin" asp-route-returnurl="@ViewData["ReturnUrl"]"
    method="post">
        <br />
        <div>
          <p>
            @foreach (var provider in providers)
            {
              <button type="submit" name="provider" value="@provider.Name"
            title="Log in using your Azure Active Directory account">
                Azure Active Directory
              </button>
            }
          </p>
        </div>
      </form>
    }
  }
</body>
</code>```

Body:
What could be the problem I get the following when launching in localhost my .net core application:

POST http://localhost:5000/api/Authentication/login 400 (Bad Request)

{"errors":{"provider":["The provider field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1", "title":"One or more validation errors occurred.","status":400,"traceId":"00-[...]-00"}

That is the first try for my migrated and refactored .NET 7 web api application from .NET 5, where everything worked well, I use same Azure authentication data from the "old" application:

in secrets:

in appsettings.json:

{
  "AllowedHosts": "*",
  "Authentication": {
    "Azure": {
      "AADInstance": "https://login.microsoftonline.com/",
      "CallbackPath": "/signin-oidc"
    }
  },

and in Program.cs:

// ------------
// Configure Services
// ------------
string? connectionString = builder.Configuration.GetConnectionString("SqlServerConnection");
var configuration = builder.Configuration;

// Identity
builder.Services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

// Authentication
var clientId = configuration.GetValue<string>("Authentication:Azure:ClientId");
if (clientId == null)
    throw new System.Configuration.ConfigurationErrorsException("Missing Azure configuration");

builder.Services.AddAuthentication()
    .AddOpenIdConnect(
        options =>
        {
            options.ClientId = configuration.GetValue<string>("Authentication:Azure:ClientId");
            options.ClientSecret = configuration.GetValue<string>("Authentication:Azure:ClientSecret");
            options.Authority =
                            $"{configuration.GetValue<string>("Authentication:Azure:AADInstance")}{configuration.GetValue<string>("Authentication:Azure:TenantId")}";
            options.CallbackPath = configuration.GetValue<string>("Authentication:Azure:CallbackPath");
            options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
        });

The Index.cshtml page that autehticate the user

@inject SignInManager<User> SignInManager

Development Mode

This page is used for authentication in development mode only. It will be automatically replaced with the Angular
    generated one.

  @{
    var providers = await SignInManager.GetExternalAuthenticationSchemesAsync();
    if (!providers.Any())
    {

          There are no external authentication services configured.

    }
    else
    {
      <form asp-controller="Authentication" asp-action="ExternalLogin" asp-route-returnurl="@ViewData["ReturnUrl"]"
    method="post">

            @foreach (var provider in providers)
            {
              <button type="submit" name="provider" value="@provider.Name"
            title="Log in using your Azure Active Directory account">
                Azure Active Directory
              </button>
            }

      </form>
    }
  }


问:
How to open a predefined modal from a method - Angular TypeScript
Apologies if this has already been asked but I am unable to find a solution for it, I am very new to Angular and what I'm trying to do is, capture the screen refresh button (F5) of the browser and on detecting the F5, it should display a Confirmation Dialog on screen. Right now this is how I am trying to detect Browser Refresh (Please feel free to advise if there is another better way than this),

app.component.ts

```<code>// call this event handler before browser refresh
@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
  console.log("Processing beforeunload...", this.myValue);
  this.processData();
}

// execute this function before browser refresh
processData(){
  // open Confirmation Modal here!!!
}
</code>```

I found the following code for Confirmation Modal which might fit my purpose but I am unable to open this modal dialog

confirmation-modal.component.html

```<code><my-modal-container [identifier]="this.modalIdentifier">
  <my-modal size="small">
    <my-modal-header>
      <h3>{{ this.header }}</h3>
    </my-modal-header>
    <my-modal-content>
      <p data-test="confirmation-modal-content">
        {{ this.content }}
      </p>
    </my-modal-content>
    <my-modal-actions>
      <button my-btn type="button" (click)="closeModal()">
        Close
      </button>
      <button my-btn type="button" data-test="confirm-button-modal" btnType="secondary" (click)="removeAll()">
        Confirm
      </button>
    </my-modal-actions>
  </my-modal>
</my-modal-container>
</code>```

Any help will he greatly appreciated.

Thank you all

Kind Regards

Body:
Apologies if this has already been asked but I am unable to find a solution for it, I am very new to Angular and what I'm trying to do is, capture the screen refresh button (F5) of the browser and on detecting the F5, it should display a Confirmation Dialog on screen. Right now this is how I am trying to detect Browser Refresh (Please feel free to advise if there is another better way than this),

app.component.ts

// call this event handler before browser refresh
@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
  console.log("Processing beforeunload...", this.myValue);
  this.processData();
}

// execute this function before browser refresh
processData(){
  // open Confirmation Modal here!!!
}

I found the following code for Confirmation Modal which might fit my purpose but I am unable to open this modal dialog

confirmation-modal.component.html

<my-modal-container [identifier]="this.modalIdentifier">
  <my-modal size="small">
    <my-modal-header>

{{ this.header }}

    </my-modal-header>
    <my-modal-content>

        {{ this.content }}

    </my-modal-content>
    <my-modal-actions>
      <button my-btn type="button" (click)="closeModal()">
        Close
      </button>
      <button my-btn type="button" data-test="confirm-button-modal" btnType="secondary" (click)="removeAll()">
        Confirm
      </button>
    </my-modal-actions>
  </my-modal>
</my-modal-container>

Any help will he greatly appreciated.

Thank you all

Kind Regards


问:
How to reduce jittering in mediapipe face mesh?
How to reduce jittering in mediapipe face mesh ?

I am using mediapipe face mesh for getting face landmarks to generate a point cloud from those landmarks, but I am facing jittering issue in mediapipe face_mesh. Can you help me to solve this issue?


问:
Flutter error after recloning application
I get this error after I recloned a flutter app, I am a contributor too.
also so cardano_wallet_sdk: ^0.1.0-alpha.12 stopped working and I am getting this error

```<code>: Error: Type 'TxContentUtxoInputs' not found.
../…/blockfrost/blockfrost_blockchain_adapter.dart:382
  List<TransactionInput> _buildIputs(BuiltList<TxContentUtxoInputs> list) {
                                               ^^^^^^^^^^^^^^^^^^^
: Error: Type 'TxContentUtxoOutputs' not found.
../…/blockfrost/blockfrost_blockchain_adapter.dart:403
  List<TransactionOutput> _buildOutputs(BuiltList<TxContentUtxoOutputs> list) {
                                                  ^^^^^^^^^^^^^^^^^^^^
</code>```

for android i get this error in vscode problem tab

```<code>The supplied phased action failed with an exception.
A problem occurred evaluating settings 'android'.
assert localPropertiesFile.exists()
       |                   |
       |                   false
       /Users/Davyking/Documents/wootz-browser/android/local.properties
</code>```

local.properties

```<code>sdk.dir=/Users/Davyking/Library/Android/sdk
flutter.sdk=/Users/Davyking/Documents/flutter
flutter.buildMode=debug
flutter.versionName=1.1.0
flutter.versionCode=14
</code>```

Body:
I get this error after I recloned a flutter app, I am a contributor too.
also so cardano_wallet_sdk: ^0.1.0-alpha.12 stopped working and I am getting this error

: Error: Type 'TxContentUtxoInputs' not found.
../…/blockfrost/blockfrost_blockchain_adapter.dart:382
  List<TransactionInput> _buildIputs(BuiltList<TxContentUtxoInputs> list) {
                                               ^^^^^^^^^^^^^^^^^^^
: Error: Type 'TxContentUtxoOutputs' not found.
../…/blockfrost/blockfrost_blockchain_adapter.dart:403
  List<TransactionOutput> _buildOutputs(BuiltList<TxContentUtxoOutputs> list) {
                                                  ^^^^^^^^^^^^^^^^^^^^

for android i get this error in vscode problem tab

The supplied phased action failed with an exception.
A problem occurred evaluating settings 'android'.
assert localPropertiesFile.exists()
       |                   |
       |                   false
       /Users/Davyking/Documents/wootz-browser/android/local.properties

local.properties

sdk.dir=/Users/Davyking/Library/Android/sdk
flutter.sdk=/Users/Davyking/Documents/flutter
flutter.buildMode=debug
flutter.versionName=1.1.0
flutter.versionCode=14


问:
Sorting Array of structs in Solidity
I've been looking online on how to implement a sorting function to my Array of structs in Solidity. I want to sort the candidate array of structs by field name "voteCount"

my Struct looks like this:

```<code>`struct Candidate {
    uint candidateId;
    string CandidateName;
    string party;
    uint voteCount;
  }`
</code>```

my Array of structs:

```<code>`Candidate [] public registeredCandidates;`
</code>```

I want to be able to return an array of structs in my function returnResult sorted by voteCount.

my returnResult function:

```<code>`function sortCandidate() public view return(Candidate[] memory){
    //do stuff here to sort the array of struct by voteCount.
 }`
</code>```

returnCandidates function ( works fine)

```<code> `function returnCandidates() public view returns (Candidate[] memory){
      Candidate[] memory array = new Candidate[](candidatesCount);
      for (uint i = 0; i < candidatesCount; i++) {
        Candidate storage candidate = registeredCandidates[i];
        array[i] = candidate;
      }
      return array;
   }`
</code>```

Can someone please help me with an easy approach. Thank you in advance all.

Title: Sorting Array of structs in Solidity

Body:
I've been looking online on how to implement a sorting function to my Array of structs in Solidity. I want to sort the candidate array of structs by field name "voteCount"

my Struct looks like this:

`struct Candidate {
    uint candidateId;
    string CandidateName;
    string party;
    uint voteCount;
  }`

my Array of structs:

`Candidate [] public registeredCandidates;`

I want to be able to return an array of structs in my function returnResult sorted by voteCount.

my returnResult function:

`function sortCandidate() public view return(Candidate[] memory){
    //do stuff here to sort the array of struct by voteCount.
 }`

returnCandidates function ( works fine)

 `function returnCandidates() public view returns (Candidate[] memory){
      Candidate[] memory array = new Candidate[](candidatesCount);
      for (uint i = 0; i < candidatesCount; i++) {
        Candidate storage candidate = registeredCandidates[i];
        array[i] = candidate;
      }
      return array;
   }`

Can someone please help me with an easy approach. Thank you in advance all.


问:
Import CSV file into SQL (PostgreSQL or BigQuery)
My problem is that I have a dataset from Kaggle (I'm currently doing this Google Analytics Capstone Project; FitBit tracker dataset). These are CSV files and contain the timestamp in the 12-hour format [m/dd/yyyy hh:dd:mm AM / PM] which cannot be imported into PostgreSQL or BigQuery directly. My question is that what should I do in order to be able to import these data and work with them? I don't intend to use Excel/GSheet to transform the timestamp because I want to learn the necessary method (and why it works) and I could not use the Sheets for this anyway.

So, can you help me with this, please?

Thank you in advance & have a nice day.

I tried to change datestyle in PostgreSQL, but it didn't work (but I can imagine that I did not try everything).


问:
Spring WebFlux and Spring MVC in one project with implementing WebFilter as interceptor
I have an old Spring MVC application where I would like to introduce some new Reactive routes for async heavy processing. Normal MVC routes work fine like this and I can return a Mono or Flux.

```<code>@GetMapping("/{id}")
public Mono<String> doSomething(@PathVariable("id") Long id) {
    ...
}
</code>```

I would like to get the request headers for further Context containing authentication information, and have this kind of filter in place so I could access the Request in Mono.deferContextual()

```<code>@Component
public class ReactiveRequestContextFilter implements WebFilter {
    public static final Class<ServerHttpRequest> SERVER_HTTP_REQUEST_CLASS = ServerHttpRequest.class;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        return chain.filter(exchange)
                    .contextWrite(ctx -> ctx.put(SERVER_HTTP_REQUEST_CLASS, request));
    }
}
</code>```

However, the filter does not trigger with the default configuration. If add the configuration class

```<code>@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer
</code>```

I'm getting the following error

The Java/XML config for Spring MVC and Spring WebFlux cannot both be enabled, e.g. via @EnableWebMvc and @EnableWebFlux, in the same application.

Is there any way to access the request with this kind of pattern, when I would like to develop new functionality using Reactor/Mono, but can't refactor all the existing routes at once to support WebFlux entirely?

Body:
I have an old Spring MVC application where I would like to introduce some new Reactive routes for async heavy processing. Normal MVC routes work fine like this and I can return a Mono or Flux.

@GetMapping("/{id}")
public Mono<String> doSomething(@PathVariable("id") Long id) {
    ...
}

I would like to get the request headers for further Context containing authentication information, and have this kind of filter in place so I could access the Request in Mono.deferContextual()

@Component
public class ReactiveRequestContextFilter implements WebFilter {
    public static final Class<ServerHttpRequest> SERVER_HTTP_REQUEST_CLASS = ServerHttpRequest.class;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        return chain.filter(exchange)
                    .contextWrite(ctx -> ctx.put(SERVER_HTTP_REQUEST_CLASS, request));
    }
}

However, the filter does not trigger with the default configuration. If add the configuration class

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer

I'm getting the following error

The Java/XML config for Spring MVC and Spring WebFlux cannot both be enabled, e.g. via @EnableWebMvc and @EnableWebFlux, in the same application.

Is there any way to access the request with this kind of pattern, when I would like to develop new functionality using Reactor/Mono, but can't refactor all the existing routes at once to support WebFlux entirely?


问:
Are Namespaces not properly supported in SoapCore (.NET Core)?
Say i want to expose a simple soap service in .NET core using SoapCore.
My service as 2 functions as shown below:

```<code>namespace TestSoapEndPoint
{
    public class SimpleService: ISimpleServiceInterface
    {
        public string Function1(TestSoapEndPoint.Req1.Request input)
        {
            return string.Concat("Function1: ", DateTime.Now.ToString());
        }
        public string Function2(TestSoapEndPoint.Req2.Request input)
        {
            return string.Concat("Function2: ", DateTime.Now.ToString());
        }
    }

    [ServiceContract]
    public interface ISimpleServiceInterface
    {
        [OperationContract]
        string Function1(TestSoapEndPoint.Req1.Request input);
        [OperationContract]
        string Function2(TestSoapEndPoint.Req2.Request input);
    }
}
</code>```

Note that input for each function is using 2 different classes but the 2 classes are using same name. They are defined in their own namespace:

```<code>namespace TestSoapEndPoint.Req1
{
    public class Request
    {
        public string str1 { get; set; } = "";
        public int int1 { get; set; } = 0;
    }
}

namespace TestSoapEndPoint.Req2
{
    public class Request
    {
        public string mystr { get; set; } = "";
        public int myint { get; set; } = 0;
        public double mydbl { get; set; } = 0.0;
    }
}
</code>```

The main routine is very simple:

```<code>        static void Main(string[] args)
        {
            var host = WebApplication.CreateBuilder();
            host.Services.AddSingleton<ISimpleServiceInterface, SimpleService>();

            _App = host.Build();
            _App.UseRouting();

            _App.UseEndpoints(endpoints =>
            {
                endpoints.UseSoapEndpoint<ISimpleServiceInterface>("/SimpleService.asmx", new SoapEncoderOptions(), SoapSerializer.XmlSerializer);
            });
            _App.Urls.Add("http://*:5000");
            _App.RunAsync();
            Console.WriteLine("Server has been started successfully ...");

            Console.ReadLine();
        }
</code>```

Problem i see is that the WSDL generated for this service is incorrect. It does not generate the 2 input structures properly. Only first defined structure will show up?
See below WSDL: http://localhost:5000/SimpleService.asmx?wsdl

Note that input for Function2 is defined to be using same request than Function1.
Seems namespace is not properly managed in SoapCore.
Is there any specific settings or option i should use to make it work or is it simply not supported?
Thanks in advance for any help provided

Body:
Say i want to expose a simple soap service in .NET core using SoapCore.
My service as 2 functions as shown below:

namespace TestSoapEndPoint
{
    public class SimpleService: ISimpleServiceInterface
    {
        public string Function1(TestSoapEndPoint.Req1.Request input)
        {
            return string.Concat("Function1: ", DateTime.Now.ToString());
        }
        public string Function2(TestSoapEndPoint.Req2.Request input)
        {
            return string.Concat("Function2: ", DateTime.Now.ToString());
        }
    }

    [ServiceContract]
    public interface ISimpleServiceInterface
    {
        [OperationContract]
        string Function1(TestSoapEndPoint.Req1.Request input);
        [OperationContract]
        string Function2(TestSoapEndPoint.Req2.Request input);
    }
}

Note that input for each function is using 2 different classes but the 2 classes are using same name. They are defined in their own namespace:

namespace TestSoapEndPoint.Req1
{
    public class Request
    {
        public string str1 { get; set; } = "";
        public int int1 { get; set; } = 0;
    }
}

namespace TestSoapEndPoint.Req2
{
    public class Request
    {
        public string mystr { get; set; } = "";
        public int myint { get; set; } = 0;
        public double mydbl { get; set; } = 0.0;
    }
}

The main routine is very simple:

        static void Main(string[] args)
        {
            var host = WebApplication.CreateBuilder();
            host.Services.AddSingleton<ISimpleServiceInterface, SimpleService>();

            _App = host.Build();
            _App.UseRouting();

            _App.UseEndpoints(endpoints =>
            {
                endpoints.UseSoapEndpoint<ISimpleServiceInterface>("/SimpleService.asmx", new SoapEncoderOptions(), SoapSerializer.XmlSerializer);
            });
            _App.Urls.Add("http://*:5000");
            _App.RunAsync();
            Console.WriteLine("Server has been started successfully ...");

            Console.ReadLine();
        }

Problem i see is that the WSDL generated for this service is incorrect. It does not generate the 2 input structures properly. Only first defined structure will show up?
See below WSDL: http://localhost:5000/SimpleService.asmx?wsdl

Note that input for Function2 is defined to be using same request than Function1.
Seems namespace is not properly managed in SoapCore.
Is there any specific settings or option i should use to make it work or is it simply not supported?
Thanks in advance for any help provided


问:
elasticsearch-create-enrollment-token using IP from wrong ethernet adaptor
We have two ethernet adaptors and hence 2 IPs, When we try to generate an enrollment token, it always uses IP from the 2nd adaptor (ens224) by default.

Is there any way to override the default and specify which IP to use or can we use hostname? TIA


问:
Microsoft team ui modification
I want to make changes in the ui like in the picture. Want to add card like that is that possible to modify the team ui?enter image description here

I'm looking in teams tool kit

Title: Microsoft team ui modification


问:
How to get Elasticsearch to listen to site IP address?
I have a python jupyter notebook on other server. I want to do

```<code>es = Elasticsearch("http://localhost:9200")
results = es.search(index="civile", body=queryAll, scroll = '10m')
</code>```

I want to connect with my ip address 172.20.28.137 and elasticsearch is installed on 172.20.28.30:9200

My configuration file /etc/elasticsearch/elasticsearch.yml

```<code>network.host: localhost
</code>```

I have changed network.host in 0.0.0.0 but I get error. How can I do?

Body:
I have a python jupyter notebook on other server. I want to do

es = Elasticsearch("http://localhost:9200")
results = es.search(index="civile", body=queryAll, scroll = '10m')

I want to connect with my ip address 172.20.28.137 and elasticsearch is installed on 172.20.28.30:9200

My configuration file /etc/elasticsearch/elasticsearch.yml

network.host: localhost

I have changed network.host in 0.0.0.0 but I get error. How can I do?


问:
Loading category tags with load more button
I am new to jQuery. I have implemented a "load more" button on my blog app using jQuery, however the categories tags doesn't get displayed on the html when I click on that button.

Everything works fine so far, I can't just display the tags on the post card, it keeps returning undefined.

Note: I'm getting my categories from a many to many field relationship

Here are my views:

def home(request):
    post = BlogPost.objects.all()[0:5]
    total_post = BlogPost.objects.count()
    context = {'post': post, 'total_post':total_post}
    return render(request,'blog/home.html', context)

def load_more(request):
    # get total items currently being displayed
    total_item = int(request.GET.get('total_item'))
    # amount of additional posts to be displayed when i click on load more
    limit = 3
    posts = list(BlogPost.objects.values()[total_item:total_item+limit])
    print(BlogPost.objects.all())
    data = {
        'posts':posts,
    }
    return JsonResponse(data=data)
```
<p>Template:</p>
```

    {% for post in post %}

{{post.title}}

            {% for category in post.category.all%}

{{category}}

            {%endfor%}

{{post.summary}}

    {%endfor%}

    <button type="button" class="more-content">load more</button>

    No more post to load!!!

{{total_post|json_script:"json-total"}}
```
<p>JS file:</p>
<pre class="lang-js prettyprint-override"><code>const loadBtn = document.getElementById('add-btn')
const total_post = JSON.parse(document.getElementById('json-total').textContent);
const alert = document.getElementById('alert')

function loadmorePost(){
    const content_container = document.getElementById('blog-content');
    var _current_item =$('.post').length;
    $.ajax({
            url:$('.add-more').attr('data-url'),
            type:'GET',
            data:{
                    'total_item':_current_item
            },

            beforeSend:function(){
                alert.classList.add('no-more-data')

            },
            success:function(response){
                    const data = response.posts
                    alert.classList.add('no-more-data')

                    data.forEach(posts => {
                            const imageurl = 'media/'+posts.image
                            const detailurl = 'post/'+posts.id;
                            const category = posts.category;
                            content_container.innerHTML +=`<div class="post" id=${posts.id}>
                                                                    <img id="img-src" src=${imageurl} image-url="{{post.image.url}alt="">
                                                                    <p><strong>${posts.title}</strong></p>

                                                                    <h3>${category}</h3>
                                                                    <h2>${posts.summary}</h2>
                                                            </div>`
                    })

                    if (_current_item == total_post){

                    alert.classList.remove('no-more-data')
                    loadBtn.classList.add('no-more-data')
                    }
                    else{ loadBtn.classList.remove('no-more-data')
                    alert.classList.add('no-more-data')
                    }

            },
            error:function(err){
                    console.log(err);

            },

    });

};
loadBtn.addEventListener('click', () => {
    loadmorePost()
});
</code>```

Body:
I am new to jQuery. I have implemented a "load more" button on my blog app using jQuery, however the categories tags doesn't get displayed on the html when I click on that button.

Everything works fine so far, I can't just display the tags on the post card, it keeps returning undefined.

Note: I'm getting my categories from a many to many field relationship

Here are my views:

def home(request):
    post = BlogPost.objects.all()[0:5]
    total_post = BlogPost.objects.count()
    context = {'post': post, 'total_post':total_post}
    return render(request,'blog/home.html', context)

def load_more(request):
    # get total items currently being displayed
    total_item = int(request.GET.get('total_item'))
    # amount of additional posts to be displayed when i click on load more
    limit = 3
    posts = list(BlogPost.objects.values()[total_item:total_item+limit])
    print(BlogPost.objects.all())
    data = {
        'posts':posts,
    }
    return JsonResponse(data=data)

Template:

    {% for post in post %}

{{post.title}}

            {% for category in post.category.all%}

{{category}}

            {%endfor%}

{{post.summary}}

    {%endfor%}

    <button type="button" class="more-content">load more</button>

    No more post to load!!!

{{total_post|json_script:"json-total"}}

JS file:

const loadBtn = document.getElementById('add-btn')
const total_post = JSON.parse(document.getElementById('json-total').textContent);
const alert = document.getElementById('alert')

function loadmorePost(){
    const content_container = document.getElementById('blog-content');
    var _current_item =$('.post').length;
    $.ajax({
            url:$('.add-more').attr('data-url'),
            type:'GET',
            data:{
                    'total_item':_current_item
            },

            beforeSend:function(){
                alert.classList.add('no-more-data')

            },
            success:function(response){
                    const data = response.posts
                    alert.classList.add('no-more-data')

                    data.forEach(posts => {
                            const imageurl = 'media/'+posts.image
                            const detailurl = 'post/'+posts.id;
                            const category = posts.category;
                            content_container.innerHTML +=`

${posts.title}

${category}

${posts.summary}

`
                    })

                    if (_current_item == total_post){

                    alert.classList.remove('no-more-data')
                    loadBtn.classList.add('no-more-data')
                    }
                    else{ loadBtn.classList.remove('no-more-data')
                    alert.classList.add('no-more-data')
                    }

            },
            error:function(err){
                    console.log(err);

            },

    });

};
loadBtn.addEventListener('click', () => {
    loadmorePost()
});


问:
How can set Date in Request Headers in HttpHeaders in Angular 13?
I was tried to many ways to set Date in Request Headers in Angular, But its not taking Date in the http request.

I tested same thing in Postman and its working there, But not working in Angular.

I written below code for it

```<code>indiaPostBookingAPI(accessToken: any, bookingDeatil: any, indiaPostBookingUrl: any): Promise<any> {
    return await this.httpClient.post<any>(indiaPostBookingUrl + '/Booking/api/createbulkreq', bookingDeatil, {
      headers: new HttpHeaders().set('Authorization', `${accessToken}`).set('x-request-id', "123e4567-e89b-12d3-a456-426614174000").set('Date', "Wed, 16 Oct 2019 07:28:00 GMT")
    }).toPromise();
}
</code>```

Body:
I was tried to many ways to set Date in Request Headers in Angular, But its not taking Date in the http request.

I tested same thing in Postman and its working there, But not working in Angular.

I written below code for it

indiaPostBookingAPI(accessToken: any, bookingDeatil: any, indiaPostBookingUrl: any): Promise<any> {
    return await this.httpClient.post<any>(indiaPostBookingUrl + '/Booking/api/createbulkreq', bookingDeatil, {
      headers: new HttpHeaders().set('Authorization', `${accessToken}`).set('x-request-id', "123e4567-e89b-12d3-a456-426614174000").set('Date', "Wed, 16 Oct 2019 07:28:00 GMT")
    }).toPromise();
}


问:
Is it possible to use UglifyJS in Cloudflare worker JS Script?
I am working on a Cloudflare Worker App and want to use Uglify JS in the app. But Worker does not support Node.JS environment. Is there any any to use the following method of Uglify JS without Node.JS:</p>
```<code>var code = "function add(first, second) { return first + second; }";
var result = UglifyJS.minify(code);
</code>```

Body:
I am working on a Cloudflare Worker App and want to use Uglify JS in the app. But Worker does not support Node.JS environment. Is there any any to use the following method of Uglify JS without Node.JS:

var code = "function add(first, second) { return first + second; }";
var result = UglifyJS.minify(code);


问:
Xdebug not stopping on breakpoints in VS Code
I'm trying to set up Xdebug on a docker container running on Ubuntu 22.04 host. It is not stopping on breakpoints.

Xdebug is correctly installed because in PhpStorm breakpoints are working but not in VS Code

{
    // Use IntelliSense para saber los atributos posibles.
    // Mantenga el puntero para ver las descripciones de los existentes atributos.
    // Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "/home/myuser/projects/myproject": "/application"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 0,
            "runtimeArgs": [
                "-dxdebug.start_with_request=yes"
            ],
            "env": {
                "XDEBUG_MODE": "debug,develop",
                "XDEBUG_CONFIG": "client_port=${port}"
            }
        },
        {
            "name": "Launch Built-in web server",
            "type": "php",
            "request": "launch",
            "runtimeArgs": [
                "-dxdebug.mode=debug",
                "-dxdebug.start_with_request=yes",
                "-S",
                "localhost:0"
            ],
            "program": "",
            "cwd": "${workspaceRoot}",
            "port": 9003,
            "serverReadyAction": {
                "pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
                "uriFormat": "http://localhost:%s",
                "action": "openExternally"
            }
        }
    ]
}
```

I've added pathMappings options in launch.json file but it is still not working. Did I missed something?

Body:
I'm trying to set up Xdebug on a docker container running on Ubuntu 22.04 host. It is not stopping on breakpoints.

Xdebug is correctly installed because in PhpStorm breakpoints are working but not in VS Code

{
    // Use IntelliSense para saber los atributos posibles.
    // Mantenga el puntero para ver las descripciones de los existentes atributos.
    // Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9003,
            "pathMappings": {
                "/home/myuser/projects/myproject": "/application"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 0,
            "runtimeArgs": [
                "-dxdebug.start_with_request=yes"
            ],
            "env": {
                "XDEBUG_MODE": "debug,develop",
                "XDEBUG_CONFIG": "client_port=${port}"
            }
        },
        {
            "name": "Launch Built-in web server",
            "type": "php",
            "request": "launch",
            "runtimeArgs": [
                "-dxdebug.mode=debug",
                "-dxdebug.start_with_request=yes",
                "-S",
                "localhost:0"
            ],
            "program": "",
            "cwd": "${workspaceRoot}",
            "port": 9003,
            "serverReadyAction": {
                "pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
                "uriFormat": "http://localhost:%s",
                "action": "openExternally"
            }
        }
    ]
}

I've added pathMappings options in launch.json file but it is still not working. Did I missed something?


问:
How to run sciprt during subprocess.call() function?
I have an issue running script during the subprocess.call() function,

```<code>import subprocess
import keyboard
from pynput.mouse import Controller,Button
import string
mouse=Controller()
mouse.position=(0,0)
phi=[1,6,1,8,0,3,3,9,8,8,7,4,9,8,9,4,8,4,8,2,0,4,5,8,6,8,3,4,3,6,5,6,3,8,1,1,7,7,2,0,3,0,9,1,7,9,8,0,5,7,6,2,8,6,2,1,3,5,4,4,8,6,2,2,7,0,5,2,6,0,4,6,2,8,1,8,9,0,2,4,4,9,7,0,7,2,0,7,2,0,4,1,8,9,3,9,1,1,3,7,4]
x=(1,2,3,4,5,6,7,8,9,0)
subprocess.call("Notepad.exe"):
mouse.move(688,389)
mouse.click(Button.left)
n=0
</code>```

It can't read this part of the script.

```<code>mouse.move(688,389)
mouse.click(Button.left)
n=0
</code>```

the only way to read it is by closing notepad.exe so the subprocess.call() ends up.

How would you fix this?

I tried to use some loops.

```<code>while subprocess.run("Notepad.exe"):
    for j in range(2):
        keyboard.send('alt+tab') #this is made to refresh the page just in case it would work
    mouse.move(688,389)
    mouse.click(Button.left)
</code>```

Body:
I have an issue running script during the subprocess.call() function,

import subprocess
import keyboard
from pynput.mouse import Controller,Button
import string
mouse=Controller()
mouse.position=(0,0)
phi=[1,6,1,8,0,3,3,9,8,8,7,4,9,8,9,4,8,4,8,2,0,4,5,8,6,8,3,4,3,6,5,6,3,8,1,1,7,7,2,0,3,0,9,1,7,9,8,0,5,7,6,2,8,6,2,1,3,5,4,4,8,6,2,2,7,0,5,2,6,0,4,6,2,8,1,8,9,0,2,4,4,9,7,0,7,2,0,7,2,0,4,1,8,9,3,9,1,1,3,7,4]
x=(1,2,3,4,5,6,7,8,9,0)
subprocess.call("Notepad.exe"):
mouse.move(688,389)
mouse.click(Button.left)
n=0

It can't read this part of the script.

mouse.move(688,389)
mouse.click(Button.left)
n=0

the only way to read it is by closing notepad.exe so the subprocess.call() ends up.

How would you fix this?

I tried to use some loops.

while subprocess.run("Notepad.exe"):
    for j in range(2):
        keyboard.send('alt+tab') #this is made to refresh the page just in case it would work
    mouse.move(688,389)
    mouse.click(Button.left)


问:
How to give write storage permissions in android 13
unable to create directory in android 13

i have used READ_MEDIA_IMAGES permission for reading the images from gallery but images are not saving in storage


问:
Angular toastr2 doesnt shows up
So I am trying to do toastr in many ways but it's not working.
Heres doc: https://www.npmjs.com/package/angular2-toaster?activeTab=readme
My HTML:

```<code><button (click)="test()">Make a toast!</button>
</code>```

MY TS:

```<code>import {ToasterService} from 'angular2-toaster';
</code>```

constructor
(
private router: Router,
private toastr: ToasterService
) { }

```<code> test() {
this.toastr.pop('success', 'Success', 'The Joke has been added');
</code>```

}

App HTML:

```<code> <toaster-container>

</toaster-container>
<router-outlet></router-outlet>
</code>```

My app.module:

```<code>import { ToasterModule } from 'angular2-toaster';

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    PagesModule,
    HttpClientModule,
    NgbModule,
    CommonModule,
    BrowserAnimationsModule,
    ToasterModule.forRoot(),
  ],
</code>```

Also in my angular.json have:

```<code>"styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "./node_modules/angular2-toaster/toaster.css",
              "src/styles.css"
</code>```

I Have no idea why that's not working. Any suggestions ?

Title: Angular toastr2 doesnt shows up

Body:
So I am trying to do toastr in many ways but it's not working.
Heres doc: https://www.npmjs.com/package/angular2-toaster?activeTab=readme
My HTML:

<button (click)="test()">Make a toast!</button>

MY TS:

import {ToasterService} from 'angular2-toaster';

constructor
(
private router: Router,
private toastr: ToasterService
) { }

 test() {
this.toastr.pop('success', 'Success', 'The Joke has been added');

}

App HTML:

 <toaster-container>

</toaster-container>
<router-outlet></router-outlet>

My app.module:

import { ToasterModule } from 'angular2-toaster';

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    PagesModule,
    HttpClientModule,
    NgbModule,
    CommonModule,
    BrowserAnimationsModule,
    ToasterModule.forRoot(),
  ],

Also in my angular.json have:

"styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "node_modules/bootstrap/scss/bootstrap.scss",
              "./node_modules/angular2-toaster/toaster.css",
              "src/styles.css"

I Have no idea why that's not working. Any suggestions ?


问:
Focus or Highlight on Sidebar Navigation Menu in Mobile View
I am new to jquery, I have a smartwave porto theme in magento 2.4, I have an accessibility issue when trigger on menu in mobile view. I want to focus on an open area (i.e. Nav Menu). Subject to that, I want to highlight through opened nav menu through keyboard's tab button.

Till now, I have achieved to trigger the menu on click through keycode, but I am unable to go through to the main opened menu through keyboard (using TAB button). Expected is to go through open menu using keyboard on clicking / trigger the menu. Here is the code for that

```<code>require([
      'jquery'
    ], function ($) {
      $(".nav-toggle").keypress(function(e) {
        if ((e.which == 13) || (e.which == 32)) {
          $(e.target).trigger('click');
          //$(e.target).show().focus().click();
        }
      });
    });

</code>```

Updated with HTML

HTML for nav-toggle

```<code><span data-action="toggle-nav" class="action nav-toggle" tabindex="0"><span>Toggle Nav</span></span>
</code>```

Opened nav-toggle which needs to be focused

```<code><div class="section-item-title nav-sections-item-title active" data-role="collapsible" role="tab" data-collapsible="true" aria-controls="store.menu" aria-selected="false" aria-expanded="true" tabindex="0">
    <a class="nav-sections-item-switch" data-toggle="switch" href="#store.menu">Menu</a>
</div>
</code>```

Body:
I am new to jquery, I have a smartwave porto theme in magento 2.4, I have an accessibility issue when trigger on menu in mobile view. I want to focus on an open area (i.e. Nav Menu). Subject to that, I want to highlight through opened nav menu through keyboard's tab button.

Till now, I have achieved to trigger the menu on click through keycode, but I am unable to go through to the main opened menu through keyboard (using TAB button). Expected is to go through open menu using keyboard on clicking / trigger the menu. Here is the code for that

require([
      'jquery'
    ], function ($) {
      $(".nav-toggle").keypress(function(e) {
        if ((e.which == 13) || (e.which == 32)) {
          $(e.target).trigger('click');
          //$(e.target).show().focus().click();
        }
      });
    });

Updated with HTML

HTML for nav-toggle

Toggle Nav

Opened nav-toggle which needs to be focused

    Menu


问:
Choose browser encryption algorithm for user authentication
I am working on authentication system that works only with public-private keys for authentication. No email, no phone.

I need to pick "proper" algorithms for user authentication and account recovery.

https://diafygi.github.io/webcrypto-examples/

user_id - public-key generated by user's browser during sign-in. Should be short and not include special chars. Will be used more as unique identifier for the user between different systems. Also used for account recovery. Could be for ex. last 20 bytes of the public address, as long as the chance of collisions is very low.

login_pub_key - generated by user`s browser. User will use the private key for authentication.

recovery_pub_key - generated by user's browser. User will use the private key together with user_id private key for for account recovery and to change login_pub_key.

Do you have any suggestions what would be suitable for these 3 cases?


问:
How to re-use one directory between several apps inside nx monorepo?
I have an nx monorepo with a number of @nrwl/next apps.
Most of them has same files inside pages folder (routes, api routes) and have differencies only in themes.
Is there a way to re-use several directories to avoid code repetition? Maybe a symlink to a shared library as shown on an image?

Image with repo structure

I've searched for such a functionality in docs but got nothing.
A solution to this problem will allow to create new pages or api routes in got them applied to all apps. So we'll have the possibility to minimize repetion of files and override default app files only when needed.


问:
Connecting to multiple hosts in Hive with SqlAlchemy
I've already had a working connection through ODBC using Cloudera ODBC Driver for Apache Hive, where I had my DSN set and all I needed was to call pyodbc.connect(f"DSN={mydsn}", autocommit=True).

Since I'm planning to use pandas on the query result, I've read that SQLAlchemy is the preferred choice and I'd like to avoid warnings resulting from other ways of connection. My DSN for Hive was using Zookeeper and "Hosts" field was filled in the form of host1:2181,host2:2181,host3:2181. I'm trying to connect to these 3 hosts and I've tried changing connection url in analogous way to the one provided in here, but I got invalid literal for int() with base 10: '2181,host2:2181,host3:2181 etc.

```<code>from sqlalchemy import create_engine
query = """SELECT TOP 10 * from eb.mobile_sa"""
conn_url = f'hive://{UID}@host1:2181,host2:2181,host3:2181/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2'
engine = create_engine(conn_url)
with engine.connect() as conn:
    df = pd.read_sql(query, conn)
</code>```

I found kazoo module that is said to be Zookeeper implementation in Python, but when I tried the very first lines from Basic Usage and just 1 host:

```<code>from kazoo.client import KazooClient
zk = KazooClient(hosts = "host1:2181", read_only=True)
zk.start()
</code>```

I got a lot of lines of Connection dropped: socket connection error
How can I correctly connect to multiple hosts in hive?

Body:
I've already had a working connection through ODBC using Cloudera ODBC Driver for Apache Hive, where I had my DSN set and all I needed was to call pyodbc.connect(f"DSN={mydsn}", autocommit=True).

Since I'm planning to use pandas on the query result, I've read that SQLAlchemy is the preferred choice and I'd like to avoid warnings resulting from other ways of connection. My DSN for Hive was using Zookeeper and "Hosts" field was filled in the form of host1:2181,host2:2181,host3:2181. I'm trying to connect to these 3 hosts and I've tried changing connection url in analogous way to the one provided in here, but I got invalid literal for int() with base 10: '2181,host2:2181,host3:2181 etc.

from sqlalchemy import create_engine
query = """SELECT TOP 10 * from eb.mobile_sa"""
conn_url = f'hive://{UID}@host1:2181,host2:2181,host3:2181/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2'
engine = create_engine(conn_url)
with engine.connect() as conn:
    df = pd.read_sql(query, conn)

I found kazoo module that is said to be Zookeeper implementation in Python, but when I tried the very first lines from Basic Usage and just 1 host:

from kazoo.client import KazooClient
zk = KazooClient(hosts = "host1:2181", read_only=True)
zk.start()

I got a lot of lines of Connection dropped: socket connection error
How can I correctly connect to multiple hosts in hive?


问:
I get a TypeError in code typed "list indices must be integers or slices, not str" and no error in same code copied and pasted. Why?
I make a war card game. I wrote first code myself and it showed error below, then from frustration I typed from the answer of my course. AND IT SHOWS the same message:

```<code>   if card1["Power"] == card2["Power"]:
       ~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str
</code>```

On other hand I have a file with the same code but pasted from the answer sheet. And it works fine.

This is my git repository. https://github.com/Mind-revolt/War-card_game.py

How do I make this typed file work without copying and pasting?

Do you see where I've made a mistake??

Thanks guys!

I tried typing the code myself first without looking in the answers. Then after a while of frustration, I typed the "right" code lines. And it doesn't work at the same line as it did before I typed from the answer sheet. I looked at the two files many times, and I didn't see a mistake. It should work. Then why it doesn't. Maybe I'm blind I don't know.

Body:
I make a war card game. I wrote first code myself and it showed error below, then from frustration I typed from the answer of my course. AND IT SHOWS the same message:

   if card1["Power"] == card2["Power"]:
       ~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not str

On other hand I have a file with the same code but pasted from the answer sheet. And it works fine.

This is my git repository. https://github.com/Mind-revolt/War-card_game.py

How do I make this typed file work without copying and pasting?

Do you see where I've made a mistake??

Thanks guys!

I tried typing the code myself first without looking in the answers. Then after a while of frustration, I typed the "right" code lines. And it doesn't work at the same line as it did before I typed from the answer sheet. I looked at the two files many times, and I didn't see a mistake. It should work. Then why it doesn't. Maybe I'm blind I don't know.


问:
Trouble mapping a simple object to an nnotated index
I have an index with the following mappings:

```<code>{
    "term_based_documents": {
        "aliases": {},
        "mappings": {
            "properties": {
                "catch_all": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "high_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "low_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "medium_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                }
            }
        },
        "settings": {
            ...
        }
    }
}

</code>```

Basically every property is a text field which I want to distinguish from each other.

The object I am feeding the index with looks like this (in Java):

```<code>public class EntityDocument {
    private String entity;
    public String high_importance_predicates;
    public String medium_importance_predicates;
    public String low_importance_predicates;
    public ArrayList<String> catch_all;

    // ...methods and less interesting stuff
}
</code>```

I am using the (apparently) new ElasticSearch 8.5 Java client, where the request for the inclusion of a new document is the following one:

```<code>EntityDocument doc = ...;

// Fill the doc

IndexResponse response = client.index(i -> i
                    .index("term_based_documents")
                    .id(doc.entity)
                    .document(doc)
            );

            System.out.println(response);
</code>```

Whenever I add a document, it fails with the following error, without elaborating much on it:

```<code>failed: [mapper_parsing_exception] failed to parse field [medium_importance_predicates.raw] of type [keyword] in document with id 'http://dbpedia.org/resource/Michael_Schumacher'. Preview of field's value: ' .... '
</code>```

It seems that some parser is failing when adding it, since whenever I simply replace the contents of  medium_importance_predicates with something simple as hello, it works perfectly. This field contains a lot of untreated URIs, non-english characters and some symbols such as <, >, [ or ], but the other two fields also do contain such characters, although they are smaller.

What could this be?

Body:
I have an index with the following mappings:

{
    "term_based_documents": {
        "aliases": {},
        "mappings": {
            "properties": {
                "catch_all": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "high_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "low_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                },
                "medium_importance_predicates": {
                    "type": "text",
                    "fields": {
                        "english": {
                            "type": "text",
                            "analyzer": "english"
                        },
                        "raw": {
                            "type": "keyword"
                        },
                        "spanish": {
                            "type": "text",
                            "analyzer": "spanish"
                        }
                    }
                }
            }
        },
        "settings": {
            ...
        }
    }
}

Basically every property is a text field which I want to distinguish from each other.

The object I am feeding the index with looks like this (in Java):

public class EntityDocument {
    private String entity;
    public String high_importance_predicates;
    public String medium_importance_predicates;
    public String low_importance_predicates;
    public ArrayList<String> catch_all;

    // ...methods and less interesting stuff
}

I am using the (apparently) new ElasticSearch 8.5 Java client, where the request for the inclusion of a new document is the following one:

EntityDocument doc = ...;

// Fill the doc

IndexResponse response = client.index(i -> i
                    .index("term_based_documents")
                    .id(doc.entity)
                    .document(doc)
            );

            System.out.println(response);

Whenever I add a document, it fails with the following error, without elaborating much on it:

failed: [mapper_parsing_exception] failed to parse field [medium_importance_predicates.raw] of type [keyword] in document with id 'http://dbpedia.org/resource/Michael_Schumacher'. Preview of field's value: ' .... '

It seems that some parser is failing when adding it, since whenever I simply replace the contents of  medium_importance_predicates with something simple as hello, it works perfectly. This field contains a lot of untreated URIs, non-english characters and some symbols such as <, >, [ or ], but the other two fields also do contain such characters, although they are smaller.

What could this be?


问:
how to calculate percisely the character movement in a tiles
So, i have started building a game 2d just a few day so its make me so confuse with some reason of the movement character in the tilemap.In my tilemap, every per tiles2 is have the width and height 16px and the whole map is 800 x 1250, every movement of my character will add/sub 1 in per step, when I calculating detection collisions, the position became wrong position specifically when character move a step then the position return to far though i try to divide 16 px in every movement of character.
This is my movement:

```<code>this.setting_walking_speed = 3 ;
if (this.player.control_direction[0] == 1) {
this.player.x -= this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 0;

            } else if (this.player.control_direction[1] == 1) {

                this.player.y -= this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 2;

            } else if (this.player.control_direction[2] == 1) {
                this.player.x += this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 1;
            } else if (this.player.control_direction[3] == 1) {
                this.player.y += this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 3;
            }
            var posf = {
                x:Math.floor( this.player.y /16 ) ,
                y:Math.floor( this.player.x /16 )
            };
            this.collide(posf);
            console.log(posf.x  , posf.y);

}
</code>```

And the collision function is:

```<code>The this.setting_minblocksize\[k\] = 16;
this.bound = this.draw_collision();

        function rectangularCollision({rect1, rect2 }) {
            return (
                rect1.x  >= rect2.x  &&
                rect1.x <= rect2.x   &&
                rect1.y  <= rect2.y  &&
                rect1.y  >= rect2.y
            )
        }

        this.collide = function(player){
            // console.log(this.bound);
            this.bound.forEach((boundaries) => {
                if(
                    rectangularCollision({,
                        rect1: player,
                        rect2: boundaries
                    })
                ){
                    console.log('collide');
                }
            })
        }

        this.draw_collision = function () {
            var obj = [];
            this.ctxt.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < canvas.height; i++) {
                for (var j = 0; j < canvas.width; j++) {

                    var data = 0;
                    if (i >= 0 && j >= 0 && i < this.map.layers[1].height && j < this.map.layers[1].width) {
                        var data = this.map.layers[1].data[i * this.map.layers[1].width + j];
                        for (var k = 0; k < 1; k++) {
                            this.ctxt.fillStyle = 'red';
                            if (data != 0) {
                                obj.push({
                                    x: j ,
                                    y: i
                                });
                                this.ctxt.fillRect(
                                    (j * this.setting_minblocksize[k]) ,
                                    (i * this.setting_minblocksize[k]) ,
                                    this.setting_minblocksize[k],
                                    this.setting_minblocksize[k]
                                );
                            }
                        }
                    }
                }
            }
            return obj;
        }

</code>```

My codepen link is right here
Thank you all for helping me!

Body:
So, i have started building a game 2d just a few day so its make me so confuse with some reason of the movement character in the tilemap.In my tilemap, every per tiles2 is have the width and height 16px and the whole map is 800 x 1250, every movement of my character will add/sub 1 in per step, when I calculating detection collisions, the position became wrong position specifically when character move a step then the position return to far though i try to divide 16 px in every movement of character.
This is my movement:

this.setting_walking_speed = 3 ;
if (this.player.control_direction[0] == 1) {
this.player.x -= this.setting_walking_speed;
this.player.walking = 1;
this.player.direction = 0;

            } else if (this.player.control_direction[1] == 1) {

                this.player.y -= this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 2;

            } else if (this.player.control_direction[2] == 1) {
                this.player.x += this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 1;
            } else if (this.player.control_direction[3] == 1) {
                this.player.y += this.setting_walking_speed;
                this.player.walking = 1;
                this.player.direction = 3;
            }
            var posf = {
                x:Math.floor( this.player.y /16 ) ,
                y:Math.floor( this.player.x /16 )
            };
            this.collide(posf);
            console.log(posf.x  , posf.y);

}

And the collision function is:

The this.setting_minblocksize\[k\] = 16;
this.bound = this.draw_collision();

        function rectangularCollision({rect1, rect2 }) {
            return (
                rect1.x  >= rect2.x  &&
                rect1.x <= rect2.x   &&
                rect1.y  <= rect2.y  &&
                rect1.y  >= rect2.y
            )
        }

        this.collide = function(player){
            // console.log(this.bound);
            this.bound.forEach((boundaries) => {
                if(
                    rectangularCollision({,
                        rect1: player,
                        rect2: boundaries
                    })
                ){
                    console.log('collide');
                }
            })
        }

        this.draw_collision = function () {
            var obj = [];
            this.ctxt.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < canvas.height; i++) {
                for (var j = 0; j < canvas.width; j++) {

                    var data = 0;
                    if (i >= 0 && j >= 0 && i < this.map.layers[1].height && j < this.map.layers[1].width) {
                        var data = this.map.layers[1].data[i * this.map.layers[1].width + j];
                        for (var k = 0; k < 1; k++) {
                            this.ctxt.fillStyle = 'red';
                            if (data != 0) {
                                obj.push({
                                    x: j ,
                                    y: i
                                });
                                this.ctxt.fillRect(
                                    (j * this.setting_minblocksize[k]) ,
                                    (i * this.setting_minblocksize[k]) ,
                                    this.setting_minblocksize[k],
                                    this.setting_minblocksize[k]
                                );
                            }
                        }
                    }
                }
            }
            return obj;
        }

My codepen link is right here
Thank you all for helping me!