问:
Logging my service's HttpServletResponse body text is truncated when response header "transfer-encoding": "chunked"
My implementation:

```<code>import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.output.TeeOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class ApiLoggingFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiLoggingFilter.class);

    ApiLoggingFilter(String requestIdParamName, String requestIdMDCParamName) {
        this.requestIdParamName = requestIdParamName;
        this.requestIdMDCParamName = requestIdMDCParamName;
    }

    private String requestIdParamName;

    private String requestIdMDCParamName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            Map<String, String> requestMap = this.getTypesafeRequestMap(httpServletRequest);
            BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpServletRequest);
            BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(httpServletResponse);
            String requestId = requestMap.containsKey(requestIdParamName) ? requestMap.get(requestIdParamName)
                    : UUID.randomUUID().toString();
            MDC.put(requestIdMDCParamName, requestId);
            final StringBuilder logRequest = new StringBuilder("HTTP ").append(httpServletRequest.getMethod())
                    .append(" \"").append(httpServletRequest.getServletPath()).append("\" ").append(", parameters=")
                    .append(requestMap).append(", body=").append(bufferedRequest.getRequestBody())
                    .append(", remote_address=").append(httpServletRequest.getRemoteAddr());
            LOGGER.info(logRequest.toString());
            try {
                chain.doFilter(bufferedRequest, bufferedResponse);
            } finally {
                final StringBuilder logResponse = new StringBuilder("HTTP RESPONSE ")
                        .append(bufferedResponse.getContent());
                LOGGER.info(logResponse.toString());
                MDC.clear();
            }
        } catch (Throwable a) {
            LOGGER.error(a.getMessage());
        }
    }

    private Map<String, String> getTypesafeRequestMap(HttpServletRequest request) {
        Map<String, String> typesafeRequestMap = new HashMap<String, String>();
        Enumeration<?> requestParamNames = request.getParameterNames();
        while (requestParamNames.hasMoreElements()) {
            String requestParamName = (String) requestParamNames.nextElement();
            String requestParamValue;
            if (requestParamName.equalsIgnoreCase("password")) {
                requestParamValue = "********";
            } else {
                requestParamValue = request.getParameter(requestParamName);
            }
            typesafeRequestMap.put(requestParamName, requestParamValue);
        }
        return typesafeRequestMap;
    }

    @Override
    public void destroy() {
    }

    private static final class BufferedRequestWrapper extends HttpServletRequestWrapper {

        private ByteArrayInputStream bais = null;
        private ByteArrayOutputStream baos = null;
        private BufferedServletInputStream bsis = null;
        private byte[] buffer = null;

        public BufferedRequestWrapper(HttpServletRequest req) throws IOException {
            super(req);
            // Read InputStream and store its content in a buffer.
            InputStream is = req.getInputStream();
            this.baos = new ByteArrayOutputStream();
            byte buf[] = new byte[1024];
            int read;
            while ((read = is.read(buf)) > 0) {
                this.baos.write(buf, 0, read);
            }
            this.buffer = this.baos.toByteArray();
        }

        @Override
        public ServletInputStream getInputStream() {
            this.bais = new ByteArrayInputStream(this.buffer);
            this.bsis = new BufferedServletInputStream(this.bais);
            return this.bsis;
        }

        String getRequestBody() throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(this.getInputStream()));
            String line = null;
            StringBuilder inputBuffer = new StringBuilder();
            do {
                line = reader.readLine();
                if (null != line) {
                    inputBuffer.append(line.trim());
                }
            } while (line != null);
            reader.close();
            return inputBuffer.toString().trim();
        }
    }

    private static final class BufferedServletInputStream extends ServletInputStream {

        private ByteArrayInputStream bais;

        public BufferedServletInputStream(ByteArrayInputStream bais) {
            this.bais = bais;
        }

        @Override
        public int available() {
            return this.bais.available();
        }

        @Override
        public int read() {
            return this.bais.read();
        }

        @Override
        public int read(byte[] buf, int off, int len) {
            return this.bais.read(buf, off, len);
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }
    }

    public class TeeServletOutputStream extends ServletOutputStream {

        private final TeeOutputStream targetStream;

        public TeeServletOutputStream(OutputStream one, OutputStream two) {
            targetStream = new TeeOutputStream(one, two);
        }

        @Override
        public void write(int arg0) throws IOException {
            this.targetStream.write(arg0);
        }

        public void flush() throws IOException {
            super.flush();
            this.targetStream.flush();
        }

        public void close() throws IOException {
            super.close();
            this.targetStream.close();
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }

    public class BufferedResponseWrapper implements HttpServletResponse {

        HttpServletResponse original;
        TeeServletOutputStream tee;
        ByteArrayOutputStream bos;

        public BufferedResponseWrapper(HttpServletResponse response) {
            original = response;
        }

        public String getContent() {
            return bos.toString();
        }

        public PrintWriter getWriter() throws IOException {
            return original.getWriter();
        }

        public ServletOutputStream getOutputStream() throws IOException {
            if (tee == null) {
                bos = new ByteArrayOutputStream();
                tee = new TeeServletOutputStream(original.getOutputStream(), bos);
            }
            return tee;

        }

        @Override
        public String getCharacterEncoding() {
            return original.getCharacterEncoding();
        }

        @Override
        public String getContentType() {
            return original.getContentType();
        }

        @Override
        public void setCharacterEncoding(String charset) {
            original.setCharacterEncoding(charset);
        }

        @Override
        public void setContentLength(int len) {
            original.setContentLength(len);
        }

        @Override
        public void setContentLengthLong(long l) {
            original.setContentLengthLong(l);
        }

        @Override
        public void setContentType(String type) {
            original.setContentType(type);
        }

        @Override
        public void setBufferSize(int size) {
            original.setBufferSize(size);
        }

        @Override
        public int getBufferSize() {
            return original.getBufferSize();
        }

        @Override
        public void flushBuffer() throws IOException {
            tee.flush();
        }

        @Override
        public void resetBuffer() {
            original.resetBuffer();
        }

        @Override
        public boolean isCommitted() {
            return original.isCommitted();
        }

        @Override
        public void reset() {
            original.reset();
        }

        @Override
        public void setLocale(Locale loc) {
            original.setLocale(loc);
        }

        @Override
        public Locale getLocale() {
            return original.getLocale();
        }

        @Override
        public void addCookie(Cookie cookie) {
            original.addCookie(cookie);
        }

        @Override
        public boolean containsHeader(String name) {
            return original.containsHeader(name);
        }

        @Override
        public String encodeURL(String url) {
            return original.encodeURL(url);
        }

        @Override
        public String encodeRedirectURL(String url) {
            return original.encodeRedirectURL(url);
        }

        @SuppressWarnings("deprecation")
        @Override
        public String encodeUrl(String url) {
            return original.encodeUrl(url);
        }

        @SuppressWarnings("deprecation")
        @Override
        public String encodeRedirectUrl(String url) {
            return original.encodeRedirectUrl(url);
        }

        @Override
        public void sendError(int sc, String msg) throws IOException {
            original.sendError(sc, msg);
        }

        @Override
        public void sendError(int sc) throws IOException {
            original.sendError(sc);
        }

        @Override
        public void sendRedirect(String location) throws IOException {
            original.sendRedirect(location);
        }

        @Override
        public void setDateHeader(String name, long date) {
            original.setDateHeader(name, date);
        }

        @Override
        public void addDateHeader(String name, long date) {
            original.addDateHeader(name, date);
        }

        @Override
        public void setHeader(String name, String value) {
            original.setHeader(name, value);
        }

        @Override
        public void addHeader(String name, String value) {
            original.addHeader(name, value);
        }

        @Override
        public void setIntHeader(String name, int value) {
            original.setIntHeader(name, value);
        }

        @Override
        public void addIntHeader(String name, int value) {
            original.addIntHeader(name, value);
        }

        @Override
        public void setStatus(int sc) {
            original.setStatus(sc);
        }

        @SuppressWarnings("deprecation")
        @Override
        public void setStatus(int sc, String sm) {
            original.setStatus(sc, sm);
        }

        @Override
        public String getHeader(String arg0) {
            return original.getHeader(arg0);
        }

        @Override
        public Collection<String> getHeaderNames() {
            return original.getHeaderNames();
        }

        @Override
        public Collection<String> getHeaders(String arg0) {
            return original.getHeaders(arg0);
        }

        @Override
        public int getStatus() {
            return original.getStatus();
        }

    }
}
</code>```

I've created a custom filter over my Spring app to log the request and responses including headers, params and body text.

It works fine for requests and responses usually, but when applied to a service which returns a large payload, the service returns all lines in full in the response but the service logs the response truncated to only a few lines.
Response header "transfer-encoding": "chunked" is what I believe is causing the odd behaviour for the logging. I think my logging code might be defaulting to a fixed size in the absence of content-length as it is streaming.

Is there a wrapper class or better approach I could take to get to copy the stream until completion. I have scoured the web but haven't seen this specific question asked - this one came close https://stackoverflow.com/questions/59295514/how-to-stream-chunked-response-with-spring-boot-restcontroller

I tried numerous filter implementations others have posted but the behaviour remained the same.

Body:
My implementation:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.output.TeeOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class ApiLoggingFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiLoggingFilter.class);

    ApiLoggingFilter(String requestIdParamName, String requestIdMDCParamName) {
        this.requestIdParamName = requestIdParamName;
        this.requestIdMDCParamName = requestIdMDCParamName;
    }

    private String requestIdParamName;

    private String requestIdMDCParamName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            Map<String, String> requestMap = this.getTypesafeRequestMap(httpServletRequest);
            BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(httpServletRequest);
            BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(httpServletResponse);
            String requestId = requestMap.containsKey(requestIdParamName) ? requestMap.get(requestIdParamName)
                    : UUID.randomUUID().toString();
            MDC.put(requestIdMDCParamName, requestId);
            final StringBuilder logRequest = new StringBuilder("HTTP ").append(httpServletRequest.getMethod())
                    .append(" \"").append(httpServletRequest.getServletPath()).append("\" ").append(", parameters=")
                    .append(requestMap).append(", body=").append(bufferedRequest.getRequestBody())
                    .append(", remote_address=").append(httpServletRequest.getRemoteAddr());
            LOGGER.info(logRequest.toString());
            try {
                chain.doFilter(bufferedRequest, bufferedResponse);
            } finally {
                final StringBuilder logResponse = new StringBuilder("HTTP RESPONSE ")
                        .append(bufferedResponse.getContent());
                LOGGER.info(logResponse.toString());
                MDC.clear();
            }
        } catch (Throwable a) {
            LOGGER.error(a.getMessage());
        }
    }

    private Map<String, String> getTypesafeRequestMap(HttpServletRequest request) {
        Map<String, String> typesafeRequestMap = new HashMap<String, String>();
        Enumeration<?> requestParamNames = request.getParameterNames();
        while (requestParamNames.hasMoreElements()) {
            String requestParamName = (String) requestParamNames.nextElement();
            String requestParamValue;
            if (requestParamName.equalsIgnoreCase("password")) {
                requestParamValue = "********";
            } else {
                requestParamValue = request.getParameter(requestParamName);
            }
            typesafeRequestMap.put(requestParamName, requestParamValue);
        }
        return typesafeRequestMap;
    }

    @Override
    public void destroy() {
    }

    private static final class BufferedRequestWrapper extends HttpServletRequestWrapper {

        private ByteArrayInputStream bais = null;
        private ByteArrayOutputStream baos = null;
        private BufferedServletInputStream bsis = null;
        private byte[] buffer = null;

        public BufferedRequestWrapper(HttpServletRequest req) throws IOException {
            super(req);
            // Read InputStream and store its content in a buffer.
            InputStream is = req.getInputStream();
            this.baos = new ByteArrayOutputStream();
            byte buf[] = new byte[1024];
            int read;
            while ((read = is.read(buf)) > 0) {
                this.baos.write(buf, 0, read);
            }
            this.buffer = this.baos.toByteArray();
        }

        @Override
        public ServletInputStream getInputStream() {
            this.bais = new ByteArrayInputStream(this.buffer);
            this.bsis = new BufferedServletInputStream(this.bais);
            return this.bsis;
        }

        String getRequestBody() throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(this.getInputStream()));
            String line = null;
            StringBuilder inputBuffer = new StringBuilder();
            do {
                line = reader.readLine();
                if (null != line) {
                    inputBuffer.append(line.trim());
                }
            } while (line != null);
            reader.close();
            return inputBuffer.toString().trim();
        }
    }

    private static final class BufferedServletInputStream extends ServletInputStream {

        private ByteArrayInputStream bais;

        public BufferedServletInputStream(ByteArrayInputStream bais) {
            this.bais = bais;
        }

        @Override
        public int available() {
            return this.bais.available();
        }

        @Override
        public int read() {
            return this.bais.read();
        }

        @Override
        public int read(byte[] buf, int off, int len) {
            return this.bais.read(buf, off, len);
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }
    }

    public class TeeServletOutputStream extends ServletOutputStream {

        private final TeeOutputStream targetStream;

        public TeeServletOutputStream(OutputStream one, OutputStream two) {
            targetStream = new TeeOutputStream(one, two);
        }

        @Override
        public void write(int arg0) throws IOException {
            this.targetStream.write(arg0);
        }

        public void flush() throws IOException {
            super.flush();
            this.targetStream.flush();
        }

        public void close() throws IOException {
            super.close();
            this.targetStream.close();
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }

    public class BufferedResponseWrapper implements HttpServletResponse {

        HttpServletResponse original;
        TeeServletOutputStream tee;
        ByteArrayOutputStream bos;

        public BufferedResponseWrapper(HttpServletResponse response) {
            original = response;
        }

        public String getContent() {
            return bos.toString();
        }

        public PrintWriter getWriter() throws IOException {
            return original.getWriter();
        }

        public ServletOutputStream getOutputStream() throws IOException {
            if (tee == null) {
                bos = new ByteArrayOutputStream();
                tee = new TeeServletOutputStream(original.getOutputStream(), bos);
            }
            return tee;

        }

        @Override
        public String getCharacterEncoding() {
            return original.getCharacterEncoding();
        }

        @Override
        public String getContentType() {
            return original.getContentType();
        }

        @Override
        public void setCharacterEncoding(String charset) {
            original.setCharacterEncoding(charset);
        }

        @Override
        public void setContentLength(int len) {
            original.setContentLength(len);
        }

        @Override
        public void setContentLengthLong(long l) {
            original.setContentLengthLong(l);
        }

        @Override
        public void setContentType(String type) {
            original.setContentType(type);
        }

        @Override
        public void setBufferSize(int size) {
            original.setBufferSize(size);
        }

        @Override
        public int getBufferSize() {
            return original.getBufferSize();
        }

        @Override
        public void flushBuffer() throws IOException {
            tee.flush();
        }

        @Override
        public void resetBuffer() {
            original.resetBuffer();
        }

        @Override
        public boolean isCommitted() {
            return original.isCommitted();
        }

        @Override
        public void reset() {
            original.reset();
        }

        @Override
        public void setLocale(Locale loc) {
            original.setLocale(loc);
        }

        @Override
        public Locale getLocale() {
            return original.getLocale();
        }

        @Override
        public void addCookie(Cookie cookie) {
            original.addCookie(cookie);
        }

        @Override
        public boolean containsHeader(String name) {
            return original.containsHeader(name);
        }

        @Override
        public String encodeURL(String url) {
            return original.encodeURL(url);
        }

        @Override
        public String encodeRedirectURL(String url) {
            return original.encodeRedirectURL(url);
        }

        @SuppressWarnings("deprecation")
        @Override
        public String encodeUrl(String url) {
            return original.encodeUrl(url);
        }

        @SuppressWarnings("deprecation")
        @Override
        public String encodeRedirectUrl(String url) {
            return original.encodeRedirectUrl(url);
        }

        @Override
        public void sendError(int sc, String msg) throws IOException {
            original.sendError(sc, msg);
        }

        @Override
        public void sendError(int sc) throws IOException {
            original.sendError(sc);
        }

        @Override
        public void sendRedirect(String location) throws IOException {
            original.sendRedirect(location);
        }

        @Override
        public void setDateHeader(String name, long date) {
            original.setDateHeader(name, date);
        }

        @Override
        public void addDateHeader(String name, long date) {
            original.addDateHeader(name, date);
        }

        @Override
        public void setHeader(String name, String value) {
            original.setHeader(name, value);
        }

        @Override
        public void addHeader(String name, String value) {
            original.addHeader(name, value);
        }

        @Override
        public void setIntHeader(String name, int value) {
            original.setIntHeader(name, value);
        }

        @Override
        public void addIntHeader(String name, int value) {
            original.addIntHeader(name, value);
        }

        @Override
        public void setStatus(int sc) {
            original.setStatus(sc);
        }

        @SuppressWarnings("deprecation")
        @Override
        public void setStatus(int sc, String sm) {
            original.setStatus(sc, sm);
        }

        @Override
        public String getHeader(String arg0) {
            return original.getHeader(arg0);
        }

        @Override
        public Collection<String> getHeaderNames() {
            return original.getHeaderNames();
        }

        @Override
        public Collection<String> getHeaders(String arg0) {
            return original.getHeaders(arg0);
        }

        @Override
        public int getStatus() {
            return original.getStatus();
        }

    }
}

I've created a custom filter over my Spring app to log the request and responses including headers, params and body text.

It works fine for requests and responses usually, but when applied to a service which returns a large payload, the service returns all lines in full in the response but the service logs the response truncated to only a few lines.
Response header "transfer-encoding": "chunked" is what I believe is causing the odd behaviour for the logging. I think my logging code might be defaulting to a fixed size in the absence of content-length as it is streaming.

Is there a wrapper class or better approach I could take to get to copy the stream until completion. I have scoured the web but haven't seen this specific question asked - this one came close https://stackoverflow.com/questions/59295514/how-to-stream-chunked-response-with-spring-boot-restcontroller

I tried numerous filter implementations others have posted but the behaviour remained the same.


来源: stackexchange

问:
Which should I prefer IEnumerable vs List for LINQ Expressions on IRepository
I want to return a whole list as LINQ for a product based project. I have questions about which one I use in IRepository will be more effective or correct.

```<code>Task<List<TEntity>> GetAllProducts();
</code>```

Normally I used something like this.

```<code>IEnumerable<TEntity> GetAllProducts();
</code>```

What is the difference between these two types?

ContentLicense: CC BY-SA 4.0

Body:
I want to return a whole list as LINQ for a product based project. I have questions about which one I use in IRepository will be more effective or correct.

Task<List<TEntity>> GetAllProducts();

Normally I used something like this.

IEnumerable<TEntity> GetAllProducts();

What is the difference between these two types?


问:
How to query for nested document inside of nested document in mongodb?
I'm trying to query a search parameter to match values of a nested document inside an already nested document.

I get my search parameter value from the request using this code :
It could have multiple values, so they're split separately into an array.

```<code>_params.rewardTypes = _params.rewardTypes ? _params.rewardTypes.split(",") : null
</code>```

the rewardTypes is an array in my document, as it's got a key field that I'm trying to query for.

My current query for key field in _rewardTypes is

```<code>              _rewardDetails: {
                $elemMatch: {
                  _rewardTypes: {
                    $elemMatch: {
                      key: {
                        $in: _params.rewardTypes,
                      },
                    },
                  },
                },
              },
</code>```

This works, and I do get rewardTypes with matching key names as in the parameter array, however I get other documents' rewardTypes that don't match the parameter that I searched for. Is my query correct or am I missing something ?

Body:
I'm trying to query a search parameter to match values of a nested document inside an already nested document.

I get my search parameter value from the request using this code :
It could have multiple values, so they're split separately into an array.

_params.rewardTypes = _params.rewardTypes ? _params.rewardTypes.split(",") : null

the rewardTypes is an array in my document, as it's got a key field that I'm trying to query for.

My current query for key field in _rewardTypes is

              _rewardDetails: {
                $elemMatch: {
                  _rewardTypes: {
                    $elemMatch: {
                      key: {
                        $in: _params.rewardTypes,
                      },
                    },
                  },
                },
              },

This works, and I do get rewardTypes with matching key names as in the parameter array, however I get other documents' rewardTypes that don't match the parameter that I searched for. Is my query correct or am I missing something ?


问:
why does ta.valuewhen jump back to a previous occurrence in pine script v5?
```<code>been trying to solve this since weeks:
why does the KSSP_Low value change back to an older occurrence a few bars after KuverSellSavePlot  happened???
KuverSellPlot also changes back to previous value after 2 bars, that,s why i used the array, but it does not help either ... but the associated plot remains correctly.
///////////////////////////////////////////////////////////////////////
KuverSellSave = 0.0
if KuverSellPlot
    array.push(KuverPlotSave, KuverSellPlot)
    KuverSellSave := -1
    KuverSellSave

KuverSellSavePlot = KuverSellSave == -1
//
KSSP_Low    = ta.valuewhen(KuverSellSavePlot, low, 0)
</code>```

as said above i even tried to save the value in an array but that also goes back to the previous value ... and i read everything that could find on the topic but have not seen this question discussed anywhere so far ... i recorded a short video to xplain it, too, but i guess it,s not allowed to share youtube links here?

```<code>KuverSellSave = 0.0
if KuverSellPlot
    array.push(KuverPlotSave, KuverSellPlot)
    KuverSellSave := -1
    KuverSellSave

KuverSellSavePlot = KuverSellSave == -1
//
KSSP_Low    = ta.valuewhen(KuverSellSavePlot, low, 0)

</code>```

Body:
been trying to solve this since weeks:
why does the KSSP_Low value change back to an older occurrence a few bars after KuverSellSavePlot  happened???
KuverSellPlot also changes back to previous value after 2 bars, that,s why i used the array, but it does not help either ... but the associated plot remains correctly.
///////////////////////////////////////////////////////////////////////
KuverSellSave = 0.0
if KuverSellPlot
    array.push(KuverPlotSave, KuverSellPlot)
    KuverSellSave := -1
    KuverSellSave

KuverSellSavePlot = KuverSellSave == -1
//
KSSP_Low    = ta.valuewhen(KuverSellSavePlot, low, 0)

as said above i even tried to save the value in an array but that also goes back to the previous value ... and i read everything that could find on the topic but have not seen this question discussed anywhere so far ... i recorded a short video to xplain it, too, but i guess it,s not allowed to share youtube links here?

KuverSellSave = 0.0
if KuverSellPlot
    array.push(KuverPlotSave, KuverSellPlot)
    KuverSellSave := -1
    KuverSellSave

KuverSellSavePlot = KuverSellSave == -1
//
KSSP_Low    = ta.valuewhen(KuverSellSavePlot, low, 0)


问:
How can I open Imap mailbox with using special-use mailboxes name?
I'm trying open "Gmail/Sent Mail" (special-use mailboxes name is "\Sent") folder using with imap-simple in NodeJs.
In case users localized their mailbox I'm having trouble open boxes.
I need to use the special-use mailboxes instead.
When I try to open with "\Sent" I'm getting Unknown Mailbox: Sent (Failure) error.

```<code>var imaps = require('imap-simple');

// in English
//var boxName="[Gmail]/Sent Mail"

// in Turkish
//var boxName="[Gmail]/Gönderilmiş Postalar"

// in special-use mailboxes name
var boxName="\Sent"

var config = {
    imap: {
        user: 'your@email.address',
        password: 'yourpassword',
        host: 'imap.gmail.com',
        port: 993,
        tls: true,
        authTimeout: 3000
    }
};

imaps.connect(config).then(function (connection) {

    return connection.openBox(boxName).then(function () {
        var searchCriteria = [
            'UNSEEN'
        ];

        var fetchOptions = {
            bodies: ['HEADER', 'TEXT'],
            markSeen: false
        };

        return connection.search(searchCriteria, fetchOptions).then(function (results) {
            var subjects = results.map(function (res) {
                return res.parts.filter(function (part) {
                    return part.which === 'HEADER';
                })[0].body.subject[0];
            });

            console.log(subjects);

        });
    });
});
</code>```

How can I open Imap mailbox with using special-use mailboxes name?

Body:
I'm trying open "Gmail/Sent Mail" (special-use mailboxes name is "\Sent") folder using with imap-simple in NodeJs.
In case users localized their mailbox I'm having trouble open boxes.
I need to use the special-use mailboxes instead.
When I try to open with "\Sent" I'm getting Unknown Mailbox: Sent (Failure) error.

var imaps = require('imap-simple');

// in English
//var boxName="[Gmail]/Sent Mail"

// in Turkish
//var boxName="[Gmail]/Gönderilmiş Postalar"

// in special-use mailboxes name
var boxName="\Sent"

var config = {
    imap: {
        user: 'your@email.address',
        password: 'yourpassword',
        host: 'imap.gmail.com',
        port: 993,
        tls: true,
        authTimeout: 3000
    }
};

imaps.connect(config).then(function (connection) {

    return connection.openBox(boxName).then(function () {
        var searchCriteria = [
            'UNSEEN'
        ];

        var fetchOptions = {
            bodies: ['HEADER', 'TEXT'],
            markSeen: false
        };

        return connection.search(searchCriteria, fetchOptions).then(function (results) {
            var subjects = results.map(function (res) {
                return res.parts.filter(function (part) {
                    return part.which === 'HEADER';
                })[0].body.subject[0];
            });

            console.log(subjects);

        });
    });
});

How can I open Imap mailbox with using special-use mailboxes name?


问:
React Native Phone Call?
Is There any way to terminate or cancel a phone call pragmatically from react native application   with any type of Npm package or react native tool

i have tried using a lot of Npm packages but didn't found a way to do is there any any package ?

Title: React Native Phone Call?


问:
What to do with input variables from the GUI in netlogo headless?
In the model I wrote in the GUI, there are input variables coming from the interface.
I want to run headless, should I include those variables in the code ? Assuming that the interface variables cannot be loaded ?

Moreover, to start the model, I click the setup button, than I click on the go command (which is repeated a number of time by calling it again at the end of the go procedure) : see below.

```<code>to go
;doing many thinks related to other procedure
set year year + 1
if (year = 2070) [stop]
go
end
</code>```

My question : in the headless mode, how are launched the procedures ?
Is there a key word ?

Body:
In the model I wrote in the GUI, there are input variables coming from the interface.
I want to run headless, should I include those variables in the code ? Assuming that the interface variables cannot be loaded ?

Moreover, to start the model, I click the setup button, than I click on the go command (which is repeated a number of time by calling it again at the end of the go procedure) : see below.

to go
;doing many thinks related to other procedure
set year year + 1
if (year = 2070) [stop]
go
end

My question : in the headless mode, how are launched the procedures ?
Is there a key word ?


问:
JEST: after mocking response from API, the data is not set in component
Index.js

`

```<code>import React, {useEffect} from 'react'
import store from '../store_path'
import loadable from '@loadable/component'
import { apiCall } from './apiService_path'
import useTokenHook from 'hook_path'
const ChildComponent = loadable(() => import('../childComponent_path'))

export const ParentComponent = () => {
const token = useTokenHook()
const [data, setData] = useState({})
const [showChild, setShowChild] = useState(false)
const lang = store(state => state.lang)
const apiCall = store(state => state.apicall)

const myFn = async() => {
    const res = await apiCall();
    console.log('[RES DATA]: ', res)
    setData(res)
    setShowChild(true)
}

useEffect(() => { myFn() }, [])

return(
    <>
        {showChild ? <ChildComponent data={data} /> : 'No data found'}
    </>
)
}
</code>```

`

Index.test.js

`

```<code>import {mockData} from '../mockdata_path'

jest.mock('./apiService_path', () => {
    apiCall: () => (mockData)
})

test('component to be defined', () => {
    render(<Component />)
})`
</code>```

Now problem here is that mock service is returning the mock data and I can see that in the console.
But the next line which is setter function is not getting covered in testcase

I tried mocking setter function but that also didn't worked. So not sure what's going wrong.

Body:
Index.js

`

import React, {useEffect} from 'react'
import store from '../store_path'
import loadable from '@loadable/component'
import { apiCall } from './apiService_path'
import useTokenHook from 'hook_path'
const ChildComponent = loadable(() => import('../childComponent_path'))

export const ParentComponent = () => {
const token = useTokenHook()
const [data, setData] = useState({})
const [showChild, setShowChild] = useState(false)
const lang = store(state => state.lang)
const apiCall = store(state => state.apicall)

const myFn = async() => {
    const res = await apiCall();
    console.log('[RES DATA]: ', res)
    setData(res)
    setShowChild(true)
}

useEffect(() => { myFn() }, [])

return(
    <>
        {showChild ? <ChildComponent data={data} /> : 'No data found'}
    </>
)
}

`

Index.test.js

`

import {mockData} from '../mockdata_path'

jest.mock('./apiService_path', () => {
    apiCall: () => (mockData)
})

test('component to be defined', () => {
    render(<Component />)
})`

Now problem here is that mock service is returning the mock data and I can see that in the console.
But the next line which is setter function is not getting covered in testcase

I tried mocking setter function but that also didn't worked. So not sure what's going wrong.


问:
How much data can you pass via branch.io deep links?
I have a flutter app, and on a specific screen I want to extract data from a link that the user has clicked on (an alternative would be to get the data from a QR code, but I want to explore the link option here).

The data and the link would be generated on a separate website that is not connected to the app in any way. The link would be sent via email to the user, and when the user clicks the link, the desired screen is opened in the app and the data is extracted.

I stumbled across branch.io that allows you to set up deep links that can take you to specific screens in your app. I also found the flutter_branch_sdk that could be a useful (maybe mandatory?) integration in my flutter app. But I haven't found a lot of information about how much custom data you can pass to the deep links. I haven't started using branch.io yet so I'm not exactly sure how the setup works.

Can you create a deep link like:
https://my.branch.io.deep.link

and then pass any data to that link, and extract it in the app?
https://my.branch.io.deep.link?data=something

and how much data are you able to pass? I'm looking to pass some dates, some integers and some strings.


问:
How to Display all associated subtask with specific taskId (Parent/Child relationship) --XAMARIN FORMS
I'm posting this question again because I didn't get the answer when I asked before ...This time I'm hoping I will get the answer I'm sharing the link of my Github repo:--     https://github.com/vishu2219/Todolist-new.git

And also the link of my question asked previously you can find code here also:-https://stackoverflow.com/questions/74560120/display-all-task-with-associated-subtask

I am new to Xamarin Forms and I am trying to create a task app. In the app, there will be the task list page and when the user selects a task, it will bring to the task view page. In the task view page, it will display the task details and the subtasks. The issue is that I can't figure out how to display the associated subtasks for the specific task id.

I'm Trying to make a todo task app with subtasks.


问:
Mounting a volume from a Docker container in another Docker container in Jenkins-Pipeline
Original question

I'm a bit stuck at the moment. Here is the scenario.

The pipeline itself is currently still running in a Docker Jenkins container.

I have a Jenkins pipeline which itself is currently still running in a Docker Jenkins container. The pipeline contains the following statement.

```<code>sh '''
   echo ${WORKSPACE}
   WORKSPACE=${WORKSPACE} docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
   '''
</code>```

The corresponding docker-compose.yml looks like this.

```<code>version: '3'
services:
  rspec:
    build:
      context: /var/jenkins_home/dockerfiles/rspec_docker/
    container_name: rspec
    environment:
      - "MYSQL_PASSWORD=xyz"
      - "MYSQL_USER=test_user"
      - "MYSQL_ROOT_PASSWORD=yxz"
    image: jenkins/rspec
    networks:
      - jenkins
    tty: true
    volumes:
      - "$WORKSPACE:/workspace"
  database_host:
    container_name: maria_db_test
    environment:
      - "MYSQL_PASSWORD=xyz"
      - "MYSQL_USER=test_user"
      - "MYSQL_ROOT_PASSWORD=yxz"
    image: mariadb:10.4
    networks:
      - jenkins
    volumes:
      - "$PWD/db_data:/var/lib/mysql"
networks:
  jenkins:
</code>```

Mounting the folder for the database container works perfectly. But when I try to mount the folder created by the Jenkins pipeline into the RSpec container, only the "workspace" folder is created and also filled with the db_setup folder and its contents. So just like the maria_db_test container.

The output within the pipeline looks like this:

```<code>+ docker volume prune -f
Total reclaimed space: 0B
[Pipeline] sh
+ echo /var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2
/var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2
+ WORKSPACE=/var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2 docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 32B done
#1 DONE 0.0s
</code>```

The path seems to be correct at this point and is also transferred correctly.

Can someone explain to me why the path is still not mounted correctly?

Kind regards and many thanks in advance.

Additional information

I have gathered some more information in the hope that it will help to find a solution.
First of all, the setup. Jenkins is run as a Docker container and assembled via the following docker-compose.yml.

```<code>version: '3'
services:
  jenkins:
    container_name: jenkins
    restart: always
    image: jenkins/docker
    build:
      context: /home/arthur/RubymineProjects/Jenkins/docker/dockerfiles/jenkins_docker
    ports:
      - "8080:8080"
    volumes:
      - "$PWD/jenkins_home:/var/jenkins_home"
      - "/var/run/docker.sock:/var/run/docker.sock"
    networks:
      - jenkins
networks:
  jenkins:
</code>```

The corresponding Dockerfile looks like this:

```<code>FROM jenkins/jenkins

USER root

# Installs Docker
RUN apt-get update
RUN apt-get -y install \
        apt-utils \
        ca-certificates \
        curl \
        gnupg \
        lsb-release
RUN mkdir -p /etc/apt/keyrings
RUN curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | gpg --batch --keyserver --dearmor -o /etc/apt/keyrings/docker.gpg

RUN echo \
      "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \
      $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
RUN apt-get update

RUN chmod a+r /etc/apt/keyrings/docker.gpg
RUN apt-get update
RUN apt-get -y install docker-ce docker-ce-cli containerd.io docker-compose-plugin

# Installs Docker Compose
RUN curl -L "https://github.com/docker/compose/releases/download/v2.13.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose
RUN usermod -aG docker jenkins
USER jenkins
</code>```

Mounting this container - i.e. from "$PWD/jenkins_home:/var/jenkins_home" and from "/var/run/docker.sock:/var/run/docker.sock" has worked without any problems so far.

The following is the Jenkinsfile I use:

```<code>pipeline {
agent any

  environment {
    BRANCH_NAME = "${env.BRANCH_NAME}"
  }

stages {
       //
     stage('Preparing') {
                steps {
                    // Removes old containers to enable a clean start of the pipeline before creating new ones in a further step
                    sh '''
                        echo "removing old container: rspec"
                        docker container rm -f rspec

                        echo "removing old container: maria_db_test"
                        docker container rm -f maria_db_test
                    '''

                    // Prunes the volumes of the old containers
                    sh '''
                        echo "cleaning volumes"
                        docker volume prune -f
                    '''

                    // Creates new containers for the RSpecs and the database
                    // docker build -t jenkins/rspec: /var/jenkins_home/dockerfiles/rspec_docker/
                    // docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
                    sh '''
                        WORKSPACE=${WORKSPACE} docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --force-recreate
                    '''

                    // Removes the standard database.yml and replaces it with the cicd_database.yml to enable communication with the previously created database container
                    sh '''
                        rm ${WORKSPACE}/config/database.yml
                        cp ${WORKSPACE}/config/cicd_database.yml ${WORKSPACE}/config/database.yml
                    '''

                    // Prepares the RSpec container for testing
                    sh '''
                        docker exec -i rspec /bin/sh < ./var/jenkins_home/scripts/db-setup.sh
                    '''
                }
            }

     stage('Push') {
                steps {
                    sh '''
                        echo pushing...
                    '''
                }
            }

     stage('Deploy') {
                steps {
                    sh '''
                        echo deploying...
                    '''
                }
            }
        }
     }
</code>```

What I have found out so far is that one problem seems to be the build-context that is specified in the second docker-compose.yml. So:

```<code>    build:
      context: /var/jenkins_home/dockerfiles/rspec_docker/
</code>```

So it doesn't seem to matter what I put in the $WORKSPACE variable. This build-context seems to be used as a starting point.

As you can see, in the directory where the docker-compose.yml is located, there is also the folder db-data, which is to serve as an image of the database container. Exactly this order is then also located on the rspec Docker container under new_workspaces.

One more "special feature" at the end. It works, for example, to specify the absolute path to a folder on my system where the Jenkins container is also running. In other words, a folder that exists outside the Docker environments.

Please help me. I really can't find an explanation for this, let alone a solution.

Body:
Original question

I'm a bit stuck at the moment. Here is the scenario.

The pipeline itself is currently still running in a Docker Jenkins container.

I have a Jenkins pipeline which itself is currently still running in a Docker Jenkins container. The pipeline contains the following statement.

sh '''
   echo ${WORKSPACE}
   WORKSPACE=${WORKSPACE} docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
   '''

The corresponding docker-compose.yml looks like this.

version: '3'
services:
  rspec:
    build:
      context: /var/jenkins_home/dockerfiles/rspec_docker/
    container_name: rspec
    environment:
      - "MYSQL_PASSWORD=xyz"
      - "MYSQL_USER=test_user"
      - "MYSQL_ROOT_PASSWORD=yxz"
    image: jenkins/rspec
    networks:
      - jenkins
    tty: true
    volumes:
      - "$WORKSPACE:/workspace"
  database_host:
    container_name: maria_db_test
    environment:
      - "MYSQL_PASSWORD=xyz"
      - "MYSQL_USER=test_user"
      - "MYSQL_ROOT_PASSWORD=yxz"
    image: mariadb:10.4
    networks:
      - jenkins
    volumes:
      - "$PWD/db_data:/var/lib/mysql"
networks:
  jenkins:

Mounting the folder for the database container works perfectly. But when I try to mount the folder created by the Jenkins pipeline into the RSpec container, only the "workspace" folder is created and also filled with the db_setup folder and its contents. So just like the maria_db_test container.

The output within the pipeline looks like this:

+ docker volume prune -f
Total reclaimed space: 0B
[Pipeline] sh
+ echo /var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2
/var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2
+ WORKSPACE=/var/jenkins_home/workspace/ITSHOP-247-jenkinsfile-anlegen_2 docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
#1 [internal] load build definition from Dockerfile
#1 transferring dockerfile: 32B done
#1 DONE 0.0s

The path seems to be correct at this point and is also transferred correctly.

Can someone explain to me why the path is still not mounted correctly?

Kind regards and many thanks in advance.

Additional information

I have gathered some more information in the hope that it will help to find a solution.
First of all, the setup. Jenkins is run as a Docker container and assembled via the following docker-compose.yml.

version: '3'
services:
  jenkins:
    container_name: jenkins
    restart: always
    image: jenkins/docker
    build:
      context: /home/arthur/RubymineProjects/Jenkins/docker/dockerfiles/jenkins_docker
    ports:
      - "8080:8080"
    volumes:
      - "$PWD/jenkins_home:/var/jenkins_home"
      - "/var/run/docker.sock:/var/run/docker.sock"
    networks:
      - jenkins
networks:
  jenkins:

The corresponding Dockerfile looks like this:

FROM jenkins/jenkins

USER root

# Installs Docker
RUN apt-get update
RUN apt-get -y install \
        apt-utils \
        ca-certificates \
        curl \
        gnupg \
        lsb-release
RUN mkdir -p /etc/apt/keyrings
RUN curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo "$ID")/gpg | gpg --batch --keyserver --dearmor -o /etc/apt/keyrings/docker.gpg

RUN echo \
      "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \
      $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
RUN apt-get update

RUN chmod a+r /etc/apt/keyrings/docker.gpg
RUN apt-get update
RUN apt-get -y install docker-ce docker-ce-cli containerd.io docker-compose-plugin

# Installs Docker Compose
RUN curl -L "https://github.com/docker/compose/releases/download/v2.13.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
RUN chmod +x /usr/local/bin/docker-compose
RUN usermod -aG docker jenkins
USER jenkins

Mounting this container - i.e. from "$PWD/jenkins_home:/var/jenkins_home" and from "/var/run/docker.sock:/var/run/docker.sock" has worked without any problems so far.

The following is the Jenkinsfile I use:

pipeline {
agent any

  environment {
    BRANCH_NAME = "${env.BRANCH_NAME}"
  }

stages {
       //
     stage('Preparing') {
                steps {
                    // Removes old containers to enable a clean start of the pipeline before creating new ones in a further step
                    sh '''
                        echo "removing old container: rspec"
                        docker container rm -f rspec

                        echo "removing old container: maria_db_test"
                        docker container rm -f maria_db_test
                    '''

                    // Prunes the volumes of the old containers
                    sh '''
                        echo "cleaning volumes"
                        docker volume prune -f
                    '''

                    // Creates new containers for the RSpecs and the database
                    // docker build -t jenkins/rspec: /var/jenkins_home/dockerfiles/rspec_docker/
                    // docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --build --force-recreate
                    sh '''
                        WORKSPACE=${WORKSPACE} docker-compose -f /var/jenkins_home/dockerfiles/rspec_docker/docker-compose.yml up -d --force-recreate
                    '''

                    // Removes the standard database.yml and replaces it with the cicd_database.yml to enable communication with the previously created database container
                    sh '''
                        rm ${WORKSPACE}/config/database.yml
                        cp ${WORKSPACE}/config/cicd_database.yml ${WORKSPACE}/config/database.yml
                    '''

                    // Prepares the RSpec container for testing
                    sh '''
                        docker exec -i rspec /bin/sh < ./var/jenkins_home/scripts/db-setup.sh
                    '''
                }
            }

     stage('Push') {
                steps {
                    sh '''
                        echo pushing...
                    '''
                }
            }

     stage('Deploy') {
                steps {
                    sh '''
                        echo deploying...
                    '''
                }
            }
        }
     }

What I have found out so far is that one problem seems to be the build-context that is specified in the second docker-compose.yml. So:

    build:
      context: /var/jenkins_home/dockerfiles/rspec_docker/

So it doesn't seem to matter what I put in the $WORKSPACE variable. This build-context seems to be used as a starting point.

As you can see, in the directory where the docker-compose.yml is located, there is also the folder db-data, which is to serve as an image of the database container. Exactly this order is then also located on the rspec Docker container under new_workspaces.

One more "special feature" at the end. It works, for example, to specify the absolute path to a folder on my system where the Jenkins container is also running. In other words, a folder that exists outside the Docker environments.

Please help me. I really can't find an explanation for this, let alone a solution.


问:
Collecting LinkedIn Data about companies and their employment info
I want to do basic company search based on certain keywords and industry tags, find people that work at those organizations and get an overview about job posting of these companies. So basically the employment info you can see at a company profile page.
What LinkedIn-API access do I need to do this? I could not find an answer in the documentation so far and the open access (i.e. 'Share on linkedIn' and 'Sign in with LinkedIn') is not enough do collect this kind of data.

Thanks!

I tried normal GET requests with the open permission access but keep getting error 404 and 403 messages.
I can access the normal v2/me/ endpoint without issues.

This is my code so far:

```<code>#Get the access token manually from LinkedIn website
access_token = '...'
import requests
import json
# Make a request to the LinkedIn API to retrieve my profile data
response = requests.get(
    "https://api.linkedin.com/v2/me",
    headers={
        "Authorization": f"Bearer {access_token}"
    }
)
# Print the user's profile data
print(response.json())
# I tried reaching these two endpoints without luck
endpoint_url = 'https://api.linkedin.com/v2/companiesV2' and 'https://api.linkedin.com/v2/search'
</code>```

Body:
I want to do basic company search based on certain keywords and industry tags, find people that work at those organizations and get an overview about job posting of these companies. So basically the employment info you can see at a company profile page.
What LinkedIn-API access do I need to do this? I could not find an answer in the documentation so far and the open access (i.e. 'Share on linkedIn' and 'Sign in with LinkedIn') is not enough do collect this kind of data.

Thanks!

I tried normal GET requests with the open permission access but keep getting error 404 and 403 messages.
I can access the normal v2/me/ endpoint without issues.

This is my code so far:

#Get the access token manually from LinkedIn website
access_token = '...'
import requests
import json
# Make a request to the LinkedIn API to retrieve my profile data
response = requests.get(
    "https://api.linkedin.com/v2/me",
    headers={
        "Authorization": f"Bearer {access_token}"
    }
)
# Print the user's profile data
print(response.json())
# I tried reaching these two endpoints without luck
endpoint_url = 'https://api.linkedin.com/v2/companiesV2' and 'https://api.linkedin.com/v2/search'


问:
Maven unpack a war keeping its name and extension
I'm trying to unpack some war and ear with maven-dependency-plugin but I want to keep the exact name and extension as destination folder.

For exemple I have a war named mywarapp.war and an ear name myearapp.ear and I want somehing like that :

/target/apps/mywarapp.war/warcontent

/target/apps/myearapp.ear/earcontent

I'm using maven-dependency-plugin 3.4.0 and my execution is as follow :

```<code>                           <execution>
                                <id>unpack-applications-war-ear</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>unpack-dependencies</goal>
                                </goals>
                                <configuration>
                                    <includeArtifactIds>mywarapp,myearapp</includeArtifactIds>
                                    <includeTypes>war,ear</includeTypes>
                                    <outputDirectory>${project.build.directory}/apps</outputDirectory>
                                    <useSubDirectoryPerArtifact>true</useSubDirectoryPerArtifact>
                              </configuration>
                            </execution>
</code>```

But the result is :

/target/apps/mywarapp-war/warcontent

/target/apps/myearapp-ear/earcontent

I tried using fileMappers to replace "-war" and "-ear" by ".war" and ".ear" but the mappers only applies to the content of the unpacked archives, not on the output folder.

If someone have a simple solution for that...

I really want to avoid using an external script for this :s

Body:
I'm trying to unpack some war and ear with maven-dependency-plugin but I want to keep the exact name and extension as destination folder.

For exemple I have a war named mywarapp.war and an ear name myearapp.ear and I want somehing like that :

/target/apps/mywarapp.war/warcontent

/target/apps/myearapp.ear/earcontent

I'm using maven-dependency-plugin 3.4.0 and my execution is as follow :

                           <execution>
                                <id>unpack-applications-war-ear</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>unpack-dependencies</goal>
                                </goals>
                                <configuration>
                                    <includeArtifactIds>mywarapp,myearapp</includeArtifactIds>
                                    <includeTypes>war,ear</includeTypes>
                                    <outputDirectory>${project.build.directory}/apps</outputDirectory>
                                    <useSubDirectoryPerArtifact>true</useSubDirectoryPerArtifact>
                              </configuration>
                            </execution>

But the result is :

/target/apps/mywarapp-war/warcontent

/target/apps/myearapp-ear/earcontent

I tried using fileMappers to replace "-war" and "-ear" by ".war" and ".ear" but the mappers only applies to the content of the unpacked archives, not on the output folder.

If someone have a simple solution for that...

I really want to avoid using an external script for this :s


问:
AWS Cli - Run AWS LakeFormation Blueprint Workflow
I'm trying to run my AWS Blueprint Workflow (https://docs.aws.amazon.com/lake-formation/latest/dg/workflows-about.html) through the command-line using AWS CLI. For that, I was trying to see which command is the best to do it. I was trying to get the command on the following page: https://docs.aws.amazon.com/cli/latest/reference/lakeformation/index.html
And the more similar command that I've found was the was aws start-transaction, however when I ran aws list-transactions I didn't got my blueprint workflows, so maybe I didn't get the desired list of my blueprints jobs.

Anyone knows if it's possible to do this?


问:
Twitchio Pubsub and Routines confusion
I'm trying to create a script that reads each channel point redemption in twitch, alongside a function that runs randomly. Reading through the docs I noticed there is something called Routines, but I have no idea how to implement this. Asynchronous code is not my forté and I'd really like some guidance on where to learn about this.

For example, I'm trying to put this:
`

```<code>
#asynchronous function that prints hello every 5 seconds

from twitchio.ext import routines

@routines.routine(seconds=5.0, iterations=5)
async def hello(arg: str):
    print(f'Hello {arg}!')

hello.start('World')

</code>```

`

Into this:
`

```<code>
#asynchronous function that reads channel point redeems

import twitchio
import asyncio
from twitchio.ext import pubsub

my_token = "..."
users_oauth_token = "..."
users_channel_id = 12345
client = twitchio.Client(token=my_token)
client.pubsub = pubsub.PubSubPool(client)

@client.event()
async def event_pubsub_bits(event: pubsub.PubSubBitsMessage):
    pass # do stuff on bit redemptions

@client.event()
async def event_pubsub_channel_points(event: pubsub.PubSubChannelPointsMessage):
    pass # do stuff on channel point redemptions

async def main():
    topics = [
        pubsub.channel_points(users_oauth_token)[users_channel_id],
        pubsub.bits(users_oauth_token)[users_channel_id]
    ]
    await client.pubsub.subscribe_topics(topics)
    await client.start()

client.loop.run_until_complete(main())
</code>```

`

If anyone has an idea of how to do this, I would love some assistance.
Thank you

I haven't tried much yet, fairly clueless on how to start

Title: Twitchio Pubsub and Routines confusion

Body:
I'm trying to create a script that reads each channel point redemption in twitch, alongside a function that runs randomly. Reading through the docs I noticed there is something called Routines, but I have no idea how to implement this. Asynchronous code is not my forté and I'd really like some guidance on where to learn about this.

For example, I'm trying to put this:
`

#asynchronous function that prints hello every 5 seconds

from twitchio.ext import routines

@routines.routine(seconds=5.0, iterations=5)
async def hello(arg: str):
    print(f'Hello {arg}!')

hello.start('World')

`

Into this:
`

#asynchronous function that reads channel point redeems

import twitchio
import asyncio
from twitchio.ext import pubsub

my_token = "..."
users_oauth_token = "..."
users_channel_id = 12345
client = twitchio.Client(token=my_token)
client.pubsub = pubsub.PubSubPool(client)

@client.event()
async def event_pubsub_bits(event: pubsub.PubSubBitsMessage):
    pass # do stuff on bit redemptions

@client.event()
async def event_pubsub_channel_points(event: pubsub.PubSubChannelPointsMessage):
    pass # do stuff on channel point redemptions

async def main():
    topics = [
        pubsub.channel_points(users_oauth_token)[users_channel_id],
        pubsub.bits(users_oauth_token)[users_channel_id]
    ]
    await client.pubsub.subscribe_topics(topics)
    await client.start()

client.loop.run_until_complete(main())

`

If anyone has an idea of how to do this, I would love some assistance.
Thank you

I haven't tried much yet, fairly clueless on how to start


问:
Google assistant - Rspi 3 - "sounddevice.PortAudioError: Error querying device -1"
Installed google assistant sdk on raspi3, the speaker is a home mini bluetooth, it is paired and connected to raspi, played from youtube and it works! even google says it's connected!

However, when running command in terminal as (env) "googlesamples-assistant-pushtotalk --project-id (not going to paste ID) --device-model-id" I get the following:

```<code> /home/pi/env/lib/python3.5/site-packages/google/auth/crypt/_cryptography_rsa.py:22: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
import cryptography.exceptions
INFO:root:Connecting to embeddedassistant.googleapis.com
Traceback (most recent call last):
File "/home/pi/env/bin/googlesamples-assistant-pushtotalk", line 8, in
sys.exit(main())
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 722, in call
return self.main(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/pushtotalk.py", line 351, in main
flush_size=audio_flush_size
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/audio_helpers.py", line 190, in init
blocksize=int(block_size/2), # blocksize is in number of frames.
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 1345, in init
**_remove_self(locals()))
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 762, in init
samplerate)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 2571, in _get_stream_parameters
info = query_devices(device)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 569, in query_devices
raise PortAudioError('Error querying device {0}'.format(device))
sounddevice.PortAudioError: Error querying device -1

When using arecord -l or aplay -l in terminal, get the same message for both: "aplay: device_list:270: no soundcards found..."

Also, running test in terminal using "speaker-test -t wav", the test runs but no sound is working"
" speaker-test 1.1.3
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
Rate set to 48000Hz (requested 48000Hz)
Buffer size range from 9600 to 4194304
Period size range from 480 to 4096
Using max buffer size 4194304
Periods = 4
was set period_size = 4096
was set buffer_size = 4194304
0 - Front Left
Time per period = 0.339021
0 - Front Left
Time per period = 0.315553
0 - Front Left
Time per period = 0.315577
*Keeps generating but with no sound."

</code>```

Finally, going through sudo nano /home/pi/.asoundrc file, when connected to speaker is:

```<code>pcm.!default {
type plug
slave.pcm {
type bluealsa
device "x❌x❌x:x"
profile "a2dp"
}
}
ctl.!default {
type bluealsa
}
</code>```

AND when going to "sudo nano /etc/asound.conf" it seems that it generates another code, when also connected to same speaker:

```<code>pcm.!default {
type asym
capture.pcm "mic"
playback.pcm "speaker"
}
pcm.mic {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"

  }
}
pcm.speaker {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"
  }
}

</code>```

I tried copy/paste code of /etc/asound.conf into /home/pi/.asoundrc and run speaker-test -t wav, but i get:

```<code>speaker-test 1.1.3

Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
ALSA lib bluealsa-pcm.c:680:(_snd_pcm_bluealsa_open) Couldn't get BlueALSA transport: No such device
Playback open error: -19,No such device"
</code>```

So, whats the deal??

Body:
Installed google assistant sdk on raspi3, the speaker is a home mini bluetooth, it is paired and connected to raspi, played from youtube and it works! even google says it's connected!

However, when running command in terminal as (env) "googlesamples-assistant-pushtotalk --project-id (not going to paste ID) --device-model-id" I get the following:

 /home/pi/env/lib/python3.5/site-packages/google/auth/crypt/_cryptography_rsa.py:22: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
import cryptography.exceptions
INFO:root:Connecting to embeddedassistant.googleapis.com
Traceback (most recent call last):
File "/home/pi/env/bin/googlesamples-assistant-pushtotalk", line 8, in
sys.exit(main())
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 722, in call
return self.main(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/pushtotalk.py", line 351, in main
flush_size=audio_flush_size
File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/audio_helpers.py", line 190, in init
blocksize=int(block_size/2), # blocksize is in number of frames.
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 1345, in init
**_remove_self(locals()))
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 762, in init
samplerate)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 2571, in _get_stream_parameters
info = query_devices(device)
File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 569, in query_devices
raise PortAudioError('Error querying device {0}'.format(device))
sounddevice.PortAudioError: Error querying device -1

When using arecord -l or aplay -l in terminal, get the same message for both: "aplay: device_list:270: no soundcards found..."

Also, running test in terminal using "speaker-test -t wav", the test runs but no sound is working"
" speaker-test 1.1.3
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
Rate set to 48000Hz (requested 48000Hz)
Buffer size range from 9600 to 4194304
Period size range from 480 to 4096
Using max buffer size 4194304
Periods = 4
was set period_size = 4096
was set buffer_size = 4194304
0 - Front Left
Time per period = 0.339021
0 - Front Left
Time per period = 0.315553
0 - Front Left
Time per period = 0.315577
*Keeps generating but with no sound."

Finally, going through sudo nano /home/pi/.asoundrc file, when connected to speaker is:

pcm.!default {
type plug
slave.pcm {
type bluealsa
device "x❌x❌x:x"
profile "a2dp"
}
}
ctl.!default {
type bluealsa
}

AND when going to "sudo nano /etc/asound.conf" it seems that it generates another code, when also connected to same speaker:

pcm.!default {
type asym
capture.pcm "mic"
playback.pcm "speaker"
}
pcm.mic {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"

  }
}
pcm.speaker {
type plug
slave.pcm {
type bluealsa device "x❌x❌x:x"
profile "sco"
  }
}

I tried copy/paste code of /etc/asound.conf into /home/pi/.asoundrc and run speaker-test -t wav, but i get:

speaker-test 1.1.3

Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
WAV file(s)
ALSA lib bluealsa-pcm.c:680:(_snd_pcm_bluealsa_open) Couldn't get BlueALSA transport: No such device
Playback open error: -19,No such device"

So, whats the deal??


问:
Vue 3 - Add props / attrs to slot
I have a question about slots. I want to add props / attrs to a default slot like this:

    // Component.vue
    <template>

Component conten

        <slot :required="required" />
    </template>

```
<p>Without having to do this:</p>
<pre class="lang-html prettyprint-override"><code>    // Parent.vue
    <template>
        <Component required v-slot="{ required }">
             <input :required="required" />
        </Component>
    </template>
</code>```

So the question is, is there a way to do this without passing props back and forth between component and slot?

I hope i made myself clear. If not, let me know!

Thanks in advance!

Title: Vue 3 - Add props / attrs to slot

Body:
I have a question about slots. I want to add props / attrs to a default slot like this:

    // Component.vue
    <template>

Component conten

        <slot :required="required" />
    </template>

Without having to do this:

    // Parent.vue
    <template>
        <Component required v-slot="{ required }">
             <input :required="required" />
        </Component>
    </template>

So the question is, is there a way to do this without passing props back and forth between component and slot?

I hope i made myself clear. If not, let me know!

Thanks in advance!


问:
Tell to linux binary not load specific shared libraries
I have a problem with shared libraries, Command show warning each time when it run's,

PHP Warning:  PHP Startup: Unable to load dynamic library 'xxxx.so'

whereas it run fine with not issues, i want to remove libcrypto.so.1.0.0 => not found this line from list so that it will not look for this shared library.

```<code>ldd ...php/ext/curl.so
        linux-vdso.so.1 =>  (0x00007ffe1a65f000)
        libcurl.so.4 => /lib/libcurl.so.4 (0x00007fb9fdd8f000)
        libssl.so.1.0.0 => /lib/libssl.so.1.0.0 (0x00007fb9fdb1f000)
        libcrypto.so.1.0.0 => not found
        libc.so.6 => /lib64/libc.so.6 (0x00007fb9fd751000)
        libssl.so.1.1 => /lib/libssl.so.1.1 (0x00007fb9fd4c0000)
        libcrypto.so.1.1 => /lib/libcrypto.so.1.1 (0x00007fb9fcff7000)
        libldap-2.4.so.2 => /lib/libldap-2.4.so.2 (0x00007fb9fcdb5000)
        liblber-2.4.so.2 => /lib/liblber-2.4.so.2 (0x00007fb9fcba8000)
        libz.so.1 => /lib/libz.so.1 (0x00007fb9fc990000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fb9fc774000)
        libcrypto.so.1.0.0 => not found
        libdl.so.2 => /lib64/libdl.so.2 (0x00007fb9fc570000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fb9fe22e000)
        libresolv.so.2 => /lib64/libresolv.so.2 (0x00007fb9fc356000)
        libcrypto.so.1.0.0 => not found
</code>```

what to do ?

Body:
I have a problem with shared libraries, Command show warning each time when it run's,

PHP Warning:  PHP Startup: Unable to load dynamic library 'xxxx.so'

whereas it run fine with not issues, i want to remove libcrypto.so.1.0.0 => not found this line from list so that it will not look for this shared library.

ldd ...php/ext/curl.so
        linux-vdso.so.1 =>  (0x00007ffe1a65f000)
        libcurl.so.4 => /lib/libcurl.so.4 (0x00007fb9fdd8f000)
        libssl.so.1.0.0 => /lib/libssl.so.1.0.0 (0x00007fb9fdb1f000)
        libcrypto.so.1.0.0 => not found
        libc.so.6 => /lib64/libc.so.6 (0x00007fb9fd751000)
        libssl.so.1.1 => /lib/libssl.so.1.1 (0x00007fb9fd4c0000)
        libcrypto.so.1.1 => /lib/libcrypto.so.1.1 (0x00007fb9fcff7000)
        libldap-2.4.so.2 => /lib/libldap-2.4.so.2 (0x00007fb9fcdb5000)
        liblber-2.4.so.2 => /lib/liblber-2.4.so.2 (0x00007fb9fcba8000)
        libz.so.1 => /lib/libz.so.1 (0x00007fb9fc990000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007fb9fc774000)
        libcrypto.so.1.0.0 => not found
        libdl.so.2 => /lib64/libdl.so.2 (0x00007fb9fc570000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fb9fe22e000)
        libresolv.so.2 => /lib64/libresolv.so.2 (0x00007fb9fc356000)
        libcrypto.so.1.0.0 => not found

what to do ?


问:
CORS Error in AWS API gateway while accessing the EKS pods
I hope you people are doing well. I have the CORS error in my AWS API gateway. I have some backend services that locate in the EKS cluster. I made one VPC link with my internal NLB. I have some Swagger definitions for my backend services, I import them in my AWS API gateway and enable the cors for all my endpoints. So, it's working fine and I can easily access my backend resources without any cors issues in postman. but when the same API I  try to connect with my frontend react application, it gives the CORS error. I got a positive prelight response with code 200. Below is the error I got while accessing the resource.

Access to fetch at
'https://5yl423946k5.execute-api.ap-south-1.amazonaws.com/mobile-api/getAvailableSubscriptions'
from origin
'http://a40ee71e46345234aa068fabdfbbbfc8-658183s33c9cd7f2.elb.ap-south-1.amazonaws.com'
has been blocked by CORS policy: Request header field
access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response.

If you need some extra information please feel free to ask :)


问:
Is this relevant to hash everything related to finance in a DB?
I'm working on an app with financial informations about users.
I'm wondering if the more secure way is to hash everything that is related to the users finance in the database and just decrypt everything in the application frontend or is it better to anonymise everything related to the user ?

Or are there other options I didn't think about ?

I have searched different solutions but I want to know what are the best practice with securing financial data.


问:
How to parse CEF format with Logstash
My entry message from file test.log

```<code>Dec  8 07:18:23 XXXXXXXX69.XXXX.COM CEF: 0|F-Secure|F-Secure Client Security Premium|15.30|online_safety.harmful_page.block|Harmful website blocked.|10|msg=Harmful website blocked. URL: http://sairuscars.weebly.com suser=XXXX\\mark.markovic domainTreePath=XXXX/Office/TES0PC0677 shost=TESTC0677
</code>```

My actually config file test.config for parse

```<code>input { stdin { } }
output { stdout { codec => rubydebug } }
filter {
    # Manipulate the message
    mutate {
         split => ["message", "|"]
    }
    kv {
        field_split => " "
        value_split => "="
    }
}
</code>```

Result from call command "cat /var/log/test.log  | logstash -f /root/tmp/test.config "

```<code>{
              "host" => "xxxapp0001.test.com",
             "suser" => "XXXX\\\\mark.markovic",
    "domainTreePath" => "XXXX/Office/TTESTC0677",
           "message" => [
        [0] "Dec  8 07:18:23 XXXXXXXX69.XXXX.COM CEF: 0",
        [1] "F-Secure",
        [2] "F-Secure Client Security Premium",
        [3] "15.30",
        [4] "online_safety.harmful_page.block",
        [5] "Harmful website blocked.",
        [6] "10",
        [7] "msg=Harmful website blocked. URL: http://sairuscars.weebly.com suser=XXXX\\\\mark.markovic domainTreePath=XXXX/Office/TTESTC0677 shost=TESTPC0677"
    ],
          "@version" => "1",
               "msg" => "Harmful",
        "@timestamp" => 2022-12-08T10:21:01.355Z,
             "shost" => "TESTPC0677"
}
</code>```

I don't know how to split message[7] to key:value

Title: How to parse CEF format with Logstash

Body:
My entry message from file test.log

Dec  8 07:18:23 XXXXXXXX69.XXXX.COM CEF: 0|F-Secure|F-Secure Client Security Premium|15.30|online_safety.harmful_page.block|Harmful website blocked.|10|msg=Harmful website blocked. URL: http://sairuscars.weebly.com suser=XXXX\\mark.markovic domainTreePath=XXXX/Office/TES0PC0677 shost=TESTC0677

My actually config file test.config for parse

input { stdin { } }
output { stdout { codec => rubydebug } }
filter {
    # Manipulate the message
    mutate {
         split => ["message", "|"]
    }
    kv {
        field_split => " "
        value_split => "="
    }
}

Result from call command "cat /var/log/test.log  | logstash -f /root/tmp/test.config "

{
              "host" => "xxxapp0001.test.com",
             "suser" => "XXXX\\\\mark.markovic",
    "domainTreePath" => "XXXX/Office/TTESTC0677",
           "message" => [
        [0] "Dec  8 07:18:23 XXXXXXXX69.XXXX.COM CEF: 0",
        [1] "F-Secure",
        [2] "F-Secure Client Security Premium",
        [3] "15.30",
        [4] "online_safety.harmful_page.block",
        [5] "Harmful website blocked.",
        [6] "10",
        [7] "msg=Harmful website blocked. URL: http://sairuscars.weebly.com suser=XXXX\\\\mark.markovic domainTreePath=XXXX/Office/TTESTC0677 shost=TESTPC0677"
    ],
          "@version" => "1",
               "msg" => "Harmful",
        "@timestamp" => 2022-12-08T10:21:01.355Z,
             "shost" => "TESTPC0677"
}

I don't know how to split message[7] to key:value


问:
How to batch process RabbitMQ messages in Quarkus
Is it possible to batch process RabbitMQ messages with Quarkus?

Based on their documentation it seems that it's currently not supported and there is no information on if it's planned.


问:
Read binary data response as uint16array using urllib2 in python 3.9
I am trying to get url response in a uint16array buffer where I am using urllib for http communication in python3.9.

I tried np.frombuffer(url.read(),dtype=np.uint16) but its not giving correct array.

ex. array at server = {1000, 2000,3000,4000} //uint16array -> in hexadecimal {0x03E8, 0x07D0, 0x0BB8, 0x0FA0}.

send as binary octat from memory directly using array pointer. received data are correct when I am using requests library as below -

np.frombuffer(response.content,dtype=np.uint16)

Can anyone help with the syntax to be used ?

--Kuldeep


问:
Using attribute_goal/2 the right way in SICStus Prolog
I'm writing a "solver" using the SICStus Prolog attributed variables interface:

```
:- module(attach2, [attach2/2]).
:- use_module(library(atts)).
:- attribute att/2.

attach2(X,Y) :- put_atts(X,att(X,Y)),
                put_atts(Y,att(Y,X)).

verify_attribute(_,_,[]).

attribute_goal(V,(true,G,true,G,true)) :- get_atts(V,att(X,Y)), G = attach2(X,Y).
```

Sample query:

```
| ?- attach2(X,Y), copy_term(X,Xc,Xcc), copy_term(Y,Yc,Ycc), copy_term(X+Y,XYc,XYcc).
Xcc = attach2:(true,attach2(Xc,_A),true,attach2(Xc,_A),true),
Ycc = attach2:(true,attach2(Yc,_B),true,attach2(Yc,_B),true),
XYc = _C+_D,
XYcc = (attach2:attach2(_C,_D),attach2:attach2(_D,_C)),
attach2(X,Y),
attach2(Y,X) ? ;
no
```

If I change attribute_goal/2 to ...

```
attach2(X,Y) :- put_atts(X,att(X,Y)),
                put_atts(Y,<b>att(X,Y)</b>).
```

... the answer get better:

```
| ?- attach2(X,Y), copy_term(X,Xc,Xcc), copy_term(Y,Yc,Ycc), copy_term(X+Y,XYc,XYcc).
Xcc = attach2:(true,attach2(Xc,_A),true,attach2(Xc,_A),true),
Ycc = attach2:(true,attach2(_B,Yc),true,attach2(_B,Yc),true),
XYc = _C+_D,
XYcc = attach2:attach2(_C,_D),
attach2(X,Y) ? ;
no
```

My conclusion from this:

copy_term/3 collects goals from attribute_goal/2 and if it encounters more than one attributed variable, then it removes trivial true and duplicate goals.

It this essentially right?

Body:
I'm writing a "solver" using the SICStus Prolog attributed variables interface:

:- module(attach2, [attach2/2]).
:- use_module(library(atts)).
:- attribute att/2.

attach2(X,Y) :- put_atts(X,att(X,Y)),
                put_atts(Y,att(Y,X)).

verify_attribute(_,_,[]).

attribute_goal(V,(true,G,true,G,true)) :- get_atts(V,att(X,Y)), G = attach2(X,Y).

Sample query:

| ?- attach2(X,Y), copy_term(X,Xc,Xcc), copy_term(Y,Yc,Ycc), copy_term(X+Y,XYc,XYcc).
Xcc = attach2:(true,attach2(Xc,_A),true,attach2(Xc,_A),true),
Ycc = attach2:(true,attach2(Yc,_B),true,attach2(Yc,_B),true),
XYc = _C+_D,
XYcc = (attach2:attach2(_C,_D),attach2:attach2(_D,_C)),
attach2(X,Y),
attach2(Y,X) ? ;
no

If I change attribute_goal/2 to ...

attach2(X,Y) :- put_atts(X,att(X,Y)),
                put_atts(Y,att(X,Y)).

... the answer get better:

| ?- attach2(X,Y), copy_term(X,Xc,Xcc), copy_term(Y,Yc,Ycc), copy_term(X+Y,XYc,XYcc).
Xcc = attach2:(true,attach2(Xc,_A),true,attach2(Xc,_A),true),
Ycc = attach2:(true,attach2(_B,Yc),true,attach2(_B,Yc),true),
XYc = _C+_D,
XYcc = attach2:attach2(_C,_D),
attach2(X,Y) ? ;
no

My conclusion from this:

copy_term/3 collects goals from attribute_goal/2 and if it encounters more than one attributed variable, then it removes trivial true and duplicate goals.

It this essentially right?


问:
Ghostscript not silent print pdf on HP printer
This code slient print on other printers,but on HP LaserJet Pro M402-M403 PCL 6 will popup printer select dialog.

```<code>gsapi_init_with_args(ptr, 12, new string[] {
                    "-empty",
                    "-dPrinted",
                    "-dBATCH",
                    "-dNOPAUSE",
                    "-dNOSAFER",
                    "-dNumCopies=1",
                    "-sDEVICE=mswinpr2",
                    "-dNOPROMPT",
                    "-dNoCancel",
                    "-sOutputFile="%printer%HP LaserJet Pro M402-M403 PCL 6",
                    "-f",
                    "D:\\report.pdf",
                });
</code>```

I want to auto select hp printer when print.

Body:
This code slient print on other printers,but on HP LaserJet Pro M402-M403 PCL 6 will popup printer select dialog.

gsapi_init_with_args(ptr, 12, new string[] {
                    "-empty",
                    "-dPrinted",
                    "-dBATCH",
                    "-dNOPAUSE",
                    "-dNOSAFER",
                    "-dNumCopies=1",
                    "-sDEVICE=mswinpr2",
                    "-dNOPROMPT",
                    "-dNoCancel",
                    "-sOutputFile="%printer%HP LaserJet Pro M402-M403 PCL 6",
                    "-f",
                    "D:\\report.pdf",
                });

I want to auto select hp printer when print.


问:
Is it possible to Scan nearby Bluetooth low energy(BLE) devices without turning on Bluetooth on mobile phone?
I am trying to build location based advertising application in which I want to JUST read the mac addresses of nearby BLE beacons and not connect to those devices while having my Bluetooth off on mobile(either Android or iOS). I wanted to know if it is possible?

I made a flutter application and scanning nearby BLE devices using flutter blue plus package. Is there any other package which can be used to just scan nearby devices without turning the Bluetooth on? Or is there any type of permission which allows me to do this?


问:
Scroll to anchor multiple times using location.hash
I have a ASP.NET page using ValidationGroup. If the validation fails, I want the page to scroll to an anchor (#edit). Here is my code so far:

```<code><div id="edit">This is my anchor area</div>
<div>
  <asp:TextBox runat="server" ID="txtDescription" ValidationGroup="Edit" />
  <asp:TextBox runat="server" ID="txtComment" ValidationGroup="Edit" />
  <asp:Button runat="server" ID="btnSave" OnClick="btnSave_OnClick" OnClientClick="ValidatePage();" ValidationGroup="Edit" CausesValidation="True" />
</div>

<script type="text/javascript">
  function ValidatePage() {
    if (!Page_ClientValidate("Edit")) {
      location.hash = "edit";
    }
  }
</script>
</code>```

First time I click the button, the page scroll to the anchor (#edit) if validation fails. But, If I click the button again, the page does not scroll to the anchor.

How can this be fixed, so that the page allways scroll to the anchor if validation fails? Even if the button is allready clicked (#edit is in the url).

Body:
I have a ASP.NET page using ValidationGroup. If the validation fails, I want the page to scroll to an anchor (#edit). Here is my code so far:

This is my anchor area

  <asp:TextBox runat="server" ID="txtDescription" ValidationGroup="Edit" />
  <asp:TextBox runat="server" ID="txtComment" ValidationGroup="Edit" />
  <asp:Button runat="server" ID="btnSave" OnClick="btnSave_OnClick" OnClientClick="ValidatePage();" ValidationGroup="Edit" CausesValidation="True" />

First time I click the button, the page scroll to the anchor (#edit) if validation fails. But, If I click the button again, the page does not scroll to the anchor.

How can this be fixed, so that the page allways scroll to the anchor if validation fails? Even if the button is allready clicked (#edit is in the url).


问:
iOS : How to upload multiple images to server using multipart using alamofire
I have to upload multiple images to the server through alamofire. I am able to get the images in the form of array, convert them to data but when i upload them to the server only first image is appearing.
I am sharing my code please help.

i am getting image array of this type

image array== [<UIImage:0x2804cb210 anonymous {1170, 2532}
renderingMode=automatic(original)>, <UIImage:0x2804f03f0 anonymous
{1170, 2532} renderingMode=automatic(original)>]

and when i convert it to data from the code i got this response

```<code>print("image array==", self.images)

        self.photoImageData = self.images.compactMap {  $0.pngData() }
        print("====", photoImageData)
</code>```

==== [4074684 bytes, 1353198 bytes]

here is my function

```<code>func hitPostAPIWithprofileImageArray(urlString: String, params: [String: String],imageData: [Data],imageKey: String, completionHandler:@escaping (_ result: [String: Any], _ errorC : Error?) -> Void)
    {
        print("params-> ",params)
        let openUrl : URL
        openUrl = URL(string: baseURL + urlString)!
        print("params-> ",openUrl)
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                for imageData in imageData {
                    multipartFormData.append(imageData, withName: imageKey, fileName: "user.jpg", mimeType: "image/jpeg")
                }
                for (key, value) in params {
                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
            },
            to: openUrl,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                        do{
                            let result = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
                            print(result)
                            let errorC = Error.self
                            completionHandler(result,errorC as? Error)
                        }catch{
                            if let err = response.error {
                                completionHandler(self.resultG,err as? Error);                                return
                            }
                        }                    }
                    upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
                    })
                case .failure(let encodingError):
                    print(encodingError)
                    completionHandler(self.resultG,encodingError as? Error)
                }
            }
        )
    }
</code>```

Body:
I have to upload multiple images to the server through alamofire. I am able to get the images in the form of array, convert them to data but when i upload them to the server only first image is appearing.
I am sharing my code please help.

i am getting image array of this type

image array== [<UIImage:0x2804cb210 anonymous {1170, 2532}
renderingMode=automatic(original)>, <UIImage:0x2804f03f0 anonymous
{1170, 2532} renderingMode=automatic(original)>]

and when i convert it to data from the code i got this response

print("image array==", self.images)

        self.photoImageData = self.images.compactMap {  $0.pngData() }
        print("====", photoImageData)

==== [4074684 bytes, 1353198 bytes]

here is my function

func hitPostAPIWithprofileImageArray(urlString: String, params: [String: String],imageData: [Data],imageKey: String, completionHandler:@escaping (_ result: [String: Any], _ errorC : Error?) -> Void)
    {
        print("params-> ",params)
        let openUrl : URL
        openUrl = URL(string: baseURL + urlString)!
        print("params-> ",openUrl)
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                for imageData in imageData {
                    multipartFormData.append(imageData, withName: imageKey, fileName: "user.jpg", mimeType: "image/jpeg")
                }
                for (key, value) in params {
                    multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                }
            },
            to: openUrl,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        debugPrint(response)
                        do{
                            let result = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
                            print(result)
                            let errorC = Error.self
                            completionHandler(result,errorC as? Error)
                        }catch{
                            if let err = response.error {
                                completionHandler(self.resultG,err as? Error);                                return
                            }
                        }                    }
                    upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
                    })
                case .failure(let encodingError):
                    print(encodingError)
                    completionHandler(self.resultG,encodingError as? Error)
                }
            }
        )
    }


问:
Devexpress, Can't Insert a new row if the database is empty
As the title describes, I have a table in my database, my BootstrapGridView displays a cannot insert new record because some field doesn't allow Null (Despite its not NULL), the weird thing is that if I add a record manually directly in the database, I become able to add new records normally from the BootstrabGridView, so, help me out please.

I cleared the database table, so, if it's empty I cannot add new records to it.
I added the record from SSMS normally, of course with respect to the Foreign keys and all, and it's added well, then I tried adding from the Gridview again and it's working.
I cleared the table again, and it doesn't work again


问:
How to auto add texture coordinate (uv coordinate) to mesh
I need some mesh with texture coordinate (uv coordinate) on each vertices.

I only found blender can generate mesh with texture coordinate.

But there are only some basic meshs like cube or sphere.

I need some complex meshs like bunny, dragon or teapot.

Is there a free dataset of triangular mesh contains texture coordinate (eg. vt in .obj file)?

If not, is there any package (python or c++) or tool can auto generate uv coordinate for vertices?

Like using cylindrical, spherical or cube mapping (or other ways).

If open3d, pyrender, pyopengl or blender can solve this problem, please tell me how.

Thank you.

I solved this problem by using blender smart uv project.

Import model

Click Shading (top)

Choose Edit Mode

Press A (select all vertices)

Click UV

Choose Smart UV Project (I am not sure what each option means, so I just click OK)

Click UV Editing (top, check uv map)

Export model (make sure UV Coordinates is picked)

If you export model as .obj file, you can check out vt tag.

If vt tags are some value between 0.0 and 1.0, everything is good.

If all vt values are 0.0, something goes wrong.

Hope this article helps you.


问:
LinqPad 7 - C# - Microsoft.VisualBasic.Interaction.GetObject
Solved by Comment from Joe Albahari

In LinQPad 7 I try to connect to an open Excel Application.
In  C# .net this is easy done by eg:

public Microsoft.Office.Interop.Excel.Application ExcelApplication; ExcelApplication = (Application)Microsoft.VisualBasic.Interaction.GetObject(Class: "Excel.Application");

With references to Microsoft.Office.Interop.Excel and Microsoft.VisualBasic

In LinQPad 7 I tried the same but ExcelApplication is null (Yes Excel is open!)
References are set and Namespace imported.
It shows no error, just does not connect.

What am I doing wrong?
(The example from LinqPad for Excel creates a new excel application.

thanks for any help


问:
Jquery changing an img element in a string to CroptoFit, is this possible?
is it possible to change the element resize_type=ResizeFitAllFill to resize_type=CroptoFit
via Jquery? I'm building a site the widget doesn't allow to specify this, also I've tried css object-fit: cover; which unfortunately doesn't work.

widget sends imgs out like this.. see below

Any help at all I'd really apperciate guys :)

I've tried css object-fit: cover; which unfortunately doesn't work.