问:
SMARTGWT DataSource (GWT-RPC-DATASource) LISTGRID
I have a problem with datasource binding in ListGrid with smartGWT. I have GWT-RPC-DataSource and i have set it as my datasource

```<code>grid.setDataSource(ds);
</code>```

On one button click I have some changes in my datasource and I am generating new datasource and rebinding with smartgwt's grid. but it fails. I have tried grid.redraw() function to redraw the grid.

Below is my class for GWTRPCDATASOURCE

```<code>public abstract class GwtRpcDataSource extends DataSource {

    /**
     * Creates new data source which communicates with server by GWT RPC. It is
     * normal server side SmartClient data source with data protocol set to
     * <code>DSProtocol.CLIENTCUSTOM</code> ("clientCustom" - natively supported
     * by SmartClient but should be added to smartGWT) and with data format
     * <code>DSDataFormat.CUSTOM</code>.
     */
    public GwtRpcDataSource() {
        setDataProtocol(DSProtocol.CLIENTCUSTOM);
        setDataFormat(DSDataFormat.CUSTOM);
        setClientOnly(false);
    }

    /**
     * Executes request to server.
     *
     * @param request
     *            <code>DSRequest</code> being processed.
     * @return <code>Object</code> data from original request.
     */
    @Override
    protected Object transformRequest(DSRequest request) {
        String requestId = request.getRequestId();
        DSResponse response = new DSResponse();
        response.setAttribute("clientContext",
                request.getAttributeAsObject("clientContext"));
        // Asume success
        response.setStatus(0);
        switch (request.getOperationType()) {
        case FETCH:
            executeFetch(requestId, request, response);
            break;
        case ADD:
            executeAdd(requestId, request, response);
            break;
        case UPDATE:
            executeUpdate(requestId, request, response);
            break;
        case REMOVE:
            executeRemove(requestId, request, response);
            break;
        default:
            // Operation not implemented.
            break;
        }
        return request.getData();
    }

    /**
     * Executed on <code>FETCH</code> operation.
     * <code>processResponse (requestId, response)</code> should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            <code>String</code> extracted from
     *            <code>DSRequest.getRequestId ()</code>.
     * @param request
     *            <code>DSRequest</code> being processed.
     * @param response
     *            <code>DSResponse</code>. <code>setData (list)</code> should be
     *            called on successful execution of this method.
     *            <code>setStatus (<0)</code> should be called on failure.
     */
    protected abstract void executeFetch(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on <code>ADD</code> operation.
     * <code>processResponse (requestId, response)</code> should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            <code>String</code> extracted from
     *            <code>DSRequest.getRequestId ()</code>.
     * @param request
     *            <code>DSRequest</code> being processed.
     *            <code>request.getData ()</code> contains record should be
     *            added.
     * @param response
     *            <code>DSResponse</code>. <code>setData (list)</code> should be
     *            called on successful execution of this method. Array should
     *            contain single element representing added row.
     *            <code>setStatus (<0)</code> should be called on failure.
     */
    protected abstract void executeAdd(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on <code>UPDATE</code> operation.
     * <code>processResponse (requestId, response)</code> should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            <code>String</code> extracted from
     *            <code>DSRequest.getRequestId ()</code>.
     * @param request
     *            <code>DSRequest</code> being processed.
     *            <code>request.getData ()</code> contains record should be
     *            updated.
     * @param response
     *            <code>DSResponse</code>. <code>setData (list)</code> should be
     *            called on successful execution of this method. Array should
     *            contain single element representing updated row.
     *            <code>setStatus (<0)</code> should be called on failure.
     */
    protected abstract void executeUpdate(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on <code>REMOVE</code> operation.
     * <code>processResponse (requestId, response)</code> should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            <code>String</code> extracted from
     *            <code>DSRequest.getRequestId ()</code>.
     * @param request
     *            <code>DSRequest</code> being processed.
     *            <code>request.getData ()</code> contains record should be
     *            removed.
     * @param response
     *            <code>DSResponse</code>. <code>setData (list)</code> should be
     *            called on successful execution of this method. Array should
     *            contain single element representing removed row.
     *            <code>setStatus (<0)</code> should be called on failure.
     */
    protected abstract void executeRemove(String requestId, DSRequest request,
            DSResponse response);

    private ListGridRecord getEditedRecord(DSRequest request) {
        // Retrieving values before edit
        JavaScriptObject oldValues = request
                .getAttributeAsJavaScriptObject("oldValues");
        // Creating new record for combining old values with changes
        ListGridRecord newRecord = new ListGridRecord();
        // Copying properties from old record
        JSOHelper.apply(oldValues, newRecord.getJsObj());
        // Retrieving changed values
        JavaScriptObject data = request.getData();
        // Apply changes
        JSOHelper.apply(data, newRecord.getJsObj());
        return newRecord;
    }

}
</code>```

I have implemented this abstract class to my own datasource class named NTDatasource.

```<code>public class NTDataSource extends GwtRpcDataSource {

    public static int total = 991;
    Record[] records;
    public NTDataSource() {
    }

    public void setData(List<NTListGridField> lstFields, Record[] records) {
//      setTestData(records);
        for (NTListGridField lstField : lstFields) {
            if (lstField.getType() == ListGridFieldType.DATE) {
                DataSourceDateField dateField = new DataSourceDateField(
                        lstField.getName());
                dateField.setHidden(lstField.getAttributeAsBoolean("visible"));
                if (lstField.getName().equals("id")) {
                    dateField.setHidden(true);
                }

                addField(dateField);

            } else {
                DataSourceTextField textField = new DataSourceTextField(
                        lstField.getName());
                textField.setHidden(lstField.getAttributeAsBoolean("visible"));
                if (lstField.getName().equals("id")) {
                    textField.setHidden(true);
                    textField.setPrimaryKey(true);
                }
                addField(textField);
            }
        }
        total = records.length;
        this.records = records;
    }

    @Override
    protected void executeFetch(String requestId, DSRequest request,
            DSResponse response) {
        // assume we have 1000 items.
        response.setTotalRows(total);
        int end = request.getEndRow();
        if (end > total) {
            end = total;
        }
        Record returnRecords[] = new Record[end
                - request.getStartRow()];
        for (int i = request.getStartRow(); i < end; i++) {
            ListGridRecord r = new ListGridRecord();
            r = (ListGridRecord) records[i];
            returnRecords[i - request.getStartRow()] = r;
        }
        GWT.log(" called from " + request.getStartRow() + " to "
                + request.getEndRow() + " result " + returnRecords.length, null);
        response.setData(returnRecords);
        processResponse(requestId, response);
    }

    @Override
    protected void executeAdd(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void executeUpdate(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void executeRemove(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }
}
</code>```

答: Try grid.invalidateCache() .This call will clear the current data in the grid and executes the NTDataSource.executeFetch method.

ContentLicense: CC BY-SA 2.5

Body:
I have a problem with datasource binding in ListGrid with smartGWT. I have GWT-RPC-DataSource and i have set it as my datasource

grid.setDataSource(ds);

On one button click I have some changes in my datasource and I am generating new datasource and rebinding with smartgwt's grid. but it fails. I have tried grid.redraw() function to redraw the grid.

Below is my class for GWTRPCDATASOURCE

public abstract class GwtRpcDataSource extends DataSource {

    /**
     * Creates new data source which communicates with server by GWT RPC. It is
     * normal server side SmartClient data source with data protocol set to
     * DSProtocol.CLIENTCUSTOM ("clientCustom" - natively supported
     * by SmartClient but should be added to smartGWT) and with data format
     * DSDataFormat.CUSTOM.
     */
    public GwtRpcDataSource() {
        setDataProtocol(DSProtocol.CLIENTCUSTOM);
        setDataFormat(DSDataFormat.CUSTOM);
        setClientOnly(false);
    }

    /**
     * Executes request to server.
     *
     * @param request
     *            DSRequest being processed.
     * @return Object data from original request.
     */
    @Override
    protected Object transformRequest(DSRequest request) {
        String requestId = request.getRequestId();
        DSResponse response = new DSResponse();
        response.setAttribute("clientContext",
                request.getAttributeAsObject("clientContext"));
        // Asume success
        response.setStatus(0);
        switch (request.getOperationType()) {
        case FETCH:
            executeFetch(requestId, request, response);
            break;
        case ADD:
            executeAdd(requestId, request, response);
            break;
        case UPDATE:
            executeUpdate(requestId, request, response);
            break;
        case REMOVE:
            executeRemove(requestId, request, response);
            break;
        default:
            // Operation not implemented.
            break;
        }
        return request.getData();
    }

    /**
     * Executed on FETCH operation.
     * processResponse (requestId, response) should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            String extracted from
     *            DSRequest.getRequestId ().
     * @param request
     *            DSRequest being processed.
     * @param response
     *            DSResponse. setData (list) should be
     *            called on successful execution of this method.
     *            setStatus (<0) should be called on failure.
     */
    protected abstract void executeFetch(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on ADD operation.
     * processResponse (requestId, response) should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            String extracted from
     *            DSRequest.getRequestId ().
     * @param request
     *            DSRequest being processed.
     *            request.getData () contains record should be
     *            added.
     * @param response
     *            DSResponse. setData (list) should be
     *            called on successful execution of this method. Array should
     *            contain single element representing added row.
     *            setStatus (<0) should be called on failure.
     */
    protected abstract void executeAdd(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on UPDATE operation.
     * processResponse (requestId, response) should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            String extracted from
     *            DSRequest.getRequestId ().
     * @param request
     *            DSRequest being processed.
     *            request.getData () contains record should be
     *            updated.
     * @param response
     *            DSResponse. setData (list) should be
     *            called on successful execution of this method. Array should
     *            contain single element representing updated row.
     *            setStatus (<0) should be called on failure.
     */
    protected abstract void executeUpdate(String requestId, DSRequest request,
            DSResponse response);

    /**
     * Executed on REMOVE operation.
     * processResponse (requestId, response) should be called when
     * operation completes (either successful or failure).
     *
     * @param requestId
     *            String extracted from
     *            DSRequest.getRequestId ().
     * @param request
     *            DSRequest being processed.
     *            request.getData () contains record should be
     *            removed.
     * @param response
     *            DSResponse. setData (list) should be
     *            called on successful execution of this method. Array should
     *            contain single element representing removed row.
     *            setStatus (<0) should be called on failure.
     */
    protected abstract void executeRemove(String requestId, DSRequest request,
            DSResponse response);

    private ListGridRecord getEditedRecord(DSRequest request) {
        // Retrieving values before edit
        JavaScriptObject oldValues = request
                .getAttributeAsJavaScriptObject("oldValues");
        // Creating new record for combining old values with changes
        ListGridRecord newRecord = new ListGridRecord();
        // Copying properties from old record
        JSOHelper.apply(oldValues, newRecord.getJsObj());
        // Retrieving changed values
        JavaScriptObject data = request.getData();
        // Apply changes
        JSOHelper.apply(data, newRecord.getJsObj());
        return newRecord;
    }

}

I have implemented this abstract class to my own datasource class named NTDatasource.

public class NTDataSource extends GwtRpcDataSource {

    public static int total = 991;
    Record[] records;
    public NTDataSource() {
    }

    public void setData(List<NTListGridField> lstFields, Record[] records) {
//      setTestData(records);
        for (NTListGridField lstField : lstFields) {
            if (lstField.getType() == ListGridFieldType.DATE) {
                DataSourceDateField dateField = new DataSourceDateField(
                        lstField.getName());
                dateField.setHidden(lstField.getAttributeAsBoolean("visible"));
                if (lstField.getName().equals("id")) {
                    dateField.setHidden(true);
                }

                addField(dateField);

            } else {
                DataSourceTextField textField = new DataSourceTextField(
                        lstField.getName());
                textField.setHidden(lstField.getAttributeAsBoolean("visible"));
                if (lstField.getName().equals("id")) {
                    textField.setHidden(true);
                    textField.setPrimaryKey(true);
                }
                addField(textField);
            }
        }
        total = records.length;
        this.records = records;
    }

    @Override
    protected void executeFetch(String requestId, DSRequest request,
            DSResponse response) {
        // assume we have 1000 items.
        response.setTotalRows(total);
        int end = request.getEndRow();
        if (end > total) {
            end = total;
        }
        Record returnRecords[] = new Record[end
                - request.getStartRow()];
        for (int i = request.getStartRow(); i < end; i++) {
            ListGridRecord r = new ListGridRecord();
            r = (ListGridRecord) records[i];
            returnRecords[i - request.getStartRow()] = r;
        }
        GWT.log(" called from " + request.getStartRow() + " to "
                + request.getEndRow() + " result " + returnRecords.length, null);
        response.setData(returnRecords);
        processResponse(requestId, response);
    }

    @Override
    protected void executeAdd(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void executeUpdate(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void executeRemove(String requestId, DSRequest request,
            DSResponse response) {
        // TODO Auto-generated method stub

    }
}


来源: stackexchange

问:
net/http: http: ContentLength=222 with Body length 0
I'm trying to retry a request if there is a connection/proxy error. For some reasons I keep getting this error which doesn't seem to recover regardless the attepts to retry the request:

```<code>    Post https://m.somewebsite.co.uk/api/di/34433: http: ContentLength=222  with Body length 0
</code>```

Am I doing something wrong? My first suspicion is that the http.Request is consumed somehow so on the next attempts it's no longer good. Should I manage a copy?

```<code>func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
    req, err := http.NewRequest("POST", URL, strings.NewReader(form.Encode()))
    if err != nil {
        log.Error(err)
        return nil, err
    }
    req.Header.Set("User-Agent", ua)
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    rsp, err := do(cl, req)

    if err != nil {
        return nil, err
    }
    defer rsp.Body.Close()
    b, err := ioutil.ReadAll(rsp.Body)
    if err != nil {
        log.Error(err)
        return nil, err
    }

    return b, nil
}

func do(cl *http.Client, req *http.Request)(*http.Response, error){
    rsp, err := cl.Do(req)
    for i := 0; IsErrProxy(err); i++ {
        log.Errorf("Proxy is slow or down ")
        time.Sleep(6 * time.Second)
5t      rsp, err = cl.Do(&ncp)
        if err == nil{
            return rsp, nil
        }
        if i > 10 {

            return nil, fmt.Errorf("after %v tries error: %v", i, err)
        }
    }
    return rsp, err
}
</code>```

答:
Let's see what does http.NewRequest do

```<code>rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
    rc = ioutil.NopCloser(body)
}
// The host's colon:port should be normalized. See Issue 14836.
u.Host = removeEmptyPort(u.Host)
req := &Request{
    Method:     method,
    URL:        u,
    Proto:      "HTTP/1.1",
    ProtoMajor: 1,
    ProtoMinor: 1,
    Header:     make(Header),
    Body:       rc,
    Host:       u.Host,
}
</code>```

body is type of io.Reader, and convert to io.ReaderCloser by ioutil.NopCloser. As @Cerise Limón said, the Request.Body had been read and the stream is closer, so when you Do() again, the Body Length is 0.

So, we could reset the Request.Body before invoke Do.

```<code>func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
    requestBodyString := form.Encode()
    req, err := http.NewRequest("POST", URL, strings.NewReader(requestBodyString))
    // ...

    rsp, err := do(cl, req, requestBodyString)

    //...
    return b, nil
}

func do(cl *http.Client, req *http.Request, requestBodyString string)(*http.Response, error){
    rsp, err := cl.Do(req)
    for i := 0; IsErrProxy(err); i++ {
        log.Errorf("Proxy is slow or down ")
        time.Sleep(6 * time.Second)
        // reset Request.Body
        req.Body = ioutil.NopCloser(strings.NewReader(requestBodyString))
        rsp, err = cl.Do(&req)
        if err == nil{
            return rsp, nil
        }
        if i > 10 {

            return nil, fmt.Errorf("after %v tries error: %v", i, err)
        }
    }
    return rsp, err
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to retry a request if there is a connection/proxy error. For some reasons I keep getting this error which doesn't seem to recover regardless the attepts to retry the request:

    Post https://m.somewebsite.co.uk/api/di/34433: http: ContentLength=222  with Body length 0

Am I doing something wrong? My first suspicion is that the http.Request is consumed somehow so on the next attempts it's no longer good. Should I manage a copy?

func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
    req, err := http.NewRequest("POST", URL, strings.NewReader(form.Encode()))
    if err != nil {
        log.Error(err)
        return nil, err
    }
    req.Header.Set("User-Agent", ua)
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    rsp, err := do(cl, req)

    if err != nil {
        return nil, err
    }
    defer rsp.Body.Close()
    b, err := ioutil.ReadAll(rsp.Body)
    if err != nil {
        log.Error(err)
        return nil, err
    }

    return b, nil
}

func do(cl *http.Client, req *http.Request)(*http.Response, error){
    rsp, err := cl.Do(req)
    for i := 0; IsErrProxy(err); i++ {
        log.Errorf("Proxy is slow or down ")
        time.Sleep(6 * time.Second)
5t      rsp, err = cl.Do(&ncp)
        if err == nil{
            return rsp, nil
        }
        if i > 10 {

            return nil, fmt.Errorf("after %v tries error: %v", i, err)
        }
    }
    return rsp, err
}

Body:
Let's see what does http.NewRequest do

rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
    rc = ioutil.NopCloser(body)
}
// The host's colon:port should be normalized. See Issue 14836.
u.Host = removeEmptyPort(u.Host)
req := &Request{
    Method:     method,
    URL:        u,
    Proto:      "HTTP/1.1",
    ProtoMajor: 1,
    ProtoMinor: 1,
    Header:     make(Header),
    Body:       rc,
    Host:       u.Host,
}

body is type of io.Reader, and convert to io.ReaderCloser by ioutil.NopCloser. As @Cerise Limón said, the Request.Body had been read and the stream is closer, so when you Do() again, the Body Length is 0.

So, we could reset the Request.Body before invoke Do.

func Post(URL string, form url.Values, cl *http.Client) ([]byte, error) {
    requestBodyString := form.Encode()
    req, err := http.NewRequest("POST", URL, strings.NewReader(requestBodyString))
    // ...

    rsp, err := do(cl, req, requestBodyString)

    //...
    return b, nil
}

func do(cl *http.Client, req *http.Request, requestBodyString string)(*http.Response, error){
    rsp, err := cl.Do(req)
    for i := 0; IsErrProxy(err); i++ {
        log.Errorf("Proxy is slow or down ")
        time.Sleep(6 * time.Second)
        // reset Request.Body
        req.Body = ioutil.NopCloser(strings.NewReader(requestBodyString))
        rsp, err = cl.Do(&req)
        if err == nil{
            return rsp, nil
        }
        if i > 10 {

            return nil, fmt.Errorf("after %v tries error: %v", i, err)
        }
    }
    return rsp, err
}


问:
calling operators of base class... safe?
Is following pattern ok/safe ? Or are there any shortcomings ?
(I also use it for equality operators)</p>

```<code>Derived& operator=(const Derived& rhs)
{
    static_cast<Base&>(*this) = rhs;
    // ... copy member variables of Derived
    return *this;
}
</code>```

答:
This is fine, but it's a lot more readable IMHO to call the base-class by name:</p>

```<code>Base::operator = (rhs);
</code>```

Body:
Is following pattern ok/safe ? Or are there any shortcomings ?
(I also use it for equality operators)

Derived& operator=(const Derived& rhs)
{
    static_cast<Base&>(*this) = rhs;
    // ... copy member variables of Derived
    return *this;
}

Body:
This is fine, but it's a lot more readable IMHO to call the base-class by name:

Base::operator = (rhs);


问:
How can I make my animation transition smoothly?
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div></code>```

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

答:
Maybe something like this?

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50%{
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div></code>```

Body:
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}

    Test Panel

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

Body:
Maybe something like this?

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50%{
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100%{
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}

<div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div>


问:
JPA Criteria in clause with tuple expression
Looking to translate an HQL query into it's JPA Criteria API equivalent.

In HQL I have the following which seems to work.

```<code>WHERE (x, y) IN (
    ... sub query which selects two columns
)
</code>```

In JPA Criteria API I don't see how I can match a tuple value, only a single value. For example, I know how to convert the following to JPA Criteria.

```<code>WHERE (x) IN (
    ... sub query which selects single column
)
</code>```

Is this even possible using the criteria api?

答:
It's not possible in JPQL to try to match two fields with the IN.

By the way, you can't do it in JPA Criteria neither.

Body:
Looking to translate an HQL query into it's JPA Criteria API equivalent.

In HQL I have the following which seems to work.

WHERE (x, y) IN (
    ... sub query which selects two columns
)

In JPA Criteria API I don't see how I can match a tuple value, only a single value. For example, I know how to convert the following to JPA Criteria.

WHERE (x) IN (
    ... sub query which selects single column
)

Is this even possible using the criteria api?


问:
How to deal with different file types in HTML
I've a simple code for downloading a simple gif image.

```<code><a href="file://<path_to_gif>/screenshot.gif" download > <button >Download Source Code</button></a>
</code>```

Above code works smoothly in chrome browser in windows. But same code isn't working in Mac. In case of Mac, I should change the code to

```<code><a href="smb://<path_to_gif>/screenshot.gif" download > <button >Download Source Code</button></a>
</code>```

How can I make sure that it can be downloaded regardless of file system being used?

答:
Add the file locally to your site, so you can then use the absolute path from you page.

e.g.

```<code>images/
index.html

index.html = "images/mygif.gif"
</code>```

Body:
I've a simple code for downloading a simple gif image.

<a href="file://<path_to_gif>/screenshot.gif" download > <button >Download Source Code</button>

Above code works smoothly in chrome browser in windows. But same code isn't working in Mac. In case of Mac, I should change the code to

<a href="smb://<path_to_gif>/screenshot.gif" download > <button >Download Source Code</button>

How can I make sure that it can be downloaded regardless of file system being used?

Body:
Add the file locally to your site, so you can then use the absolute path from you page.

e.g.

images/
index.html

index.html = "images/mygif.gif"


问:
Subscription protocol to Outlook REST API rich notification fails to create secure SSL channel
I have a web app which subscribes to rich notifications with Outlook REST API v2.0.

It was working well since several months, but as of 18 days ago it started to send back HTTP 400 codes when updating or creating subscriptions. I am issuing a POST to:

```<code>https://outlook.office.com/api/v2.0/users/{id}/subscriptions
</code>```

The error code sent back in the response body of the API is the following :

Notification URL verification failed. System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.

From my server, the POST request with token is still received and sends back an HTTP 200. It is an HTTPS website with an SSL certificate.

Is there an update about SSL version with the Outlook REST API? Or about the protocol (the documentation doesn't mention it yet) ? What could be the reason of these sudden failures ?

Outlook webhooks subscription protocol still works on Microsoft Graph API with same parameters.

Edit : it was a problem of SSL configuration between Heroku and Cloudflare that triggers the 400 error, but only on the Outlook REST API...

答:
This means there is a mismatch in supported SSL/TLS protocols between your server and the Outlook REST API. Try ssllabs.com to see which protocols either side supports.

Is your web app written in .NET? On versions prior to 4.6, the latest TLS protocol versions aren't enabled by default.

Body:
I have a web app which subscribes to rich notifications with Outlook REST API v2.0.

It was working well since several months, but as of 18 days ago it started to send back HTTP 400 codes when updating or creating subscriptions. I am issuing a POST to:

https://outlook.office.com/api/v2.0/users/{id}/subscriptions

The error code sent back in the response body of the API is the following :

Notification URL verification failed. System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.

From my server, the POST request with token is still received and sends back an HTTP 200. It is an HTTPS website with an SSL certificate.

Is there an update about SSL version with the Outlook REST API? Or about the protocol (the documentation doesn't mention it yet) ? What could be the reason of these sudden failures ?

Outlook webhooks subscription protocol still works on Microsoft Graph API with same parameters.

Edit : it was a problem of SSL configuration between Heroku and Cloudflare that triggers the 400 error, but only on the Outlook REST API...


问:
Unable to get Expected output using spring-data Mongodb
Problem

I have to search user by name,contact whatever user types i.e if he types name he gets name only and if he type contact he gets contact only etc instead I am getting all user results.

Solution -

1st Approach

I have applied or query i.e findByNameOrContactOrLocation etc using spring data MongoDb.Below is my code.

```<code>public class Search {
private String searchKey;
private double[] location;
private List<Gender> gender;
private List<String> profession;
private List<INTERESTS> interests;
private int minAge;
private int maxAge;
private double[] height;

 @PutMapping(value = "/searchByEndUser")
ApiResponse<List<Employee>> searchEndUserBasedOnKeyWord(@RequestBody Search params) {
    return ApiResponse.success().object(employeeService.getByWord(params));
}

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Override
public List<Employee> getByWord(Search params) {
    return employeeRepository.findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween(params.getSearchKey(), params.getSearchKey(), params.getLocation(), params.getGender(), params.getProfession(), params.getInterests(), params.getHeight(), params.getMinAge(), params.getMaxAge());
}

public interface EmployeeRepository extends MongoRepository<Employee, String> {
List<Employee> findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween(String searchKey, String searchKey1, double[] location, List<Gender> gender, List<String> profession, List<INTERESTS> interests, double[] height, int minAge, int maxAge);
</code>```

}

Input Supplied

```<code>{
"searchKey": "98111648642"
}
</code>```

Output Expected

```<code> {
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510303944245,
  "lastModifiedAt": 1510303944245,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "98111648642",
  "email": null,
  "address": "13",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jack",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0568c879eb192b872592b3"
 }
 ]
 }
</code>```

Below I am showing only 2 outputs

Output Shown

```<code>{
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510228467303,
  "lastModifiedAt": 1510228467303,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "9811164864",
  "email": null,
  "address": "32",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jui",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0441f379eb1930d9f961b2"
},
{
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510303944245,
  "lastModifiedAt": 1510303944245,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "98111648642",
  "email": null,
  "address": "13",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jack",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0568c879eb192b872592b3"
}
]
}

**2nd Approach**
</code>```

1)I can check if the data is coming from user set it or set a random data.Though I have not implemented it.I am looking for alternate approach for this.

Can anyone guide for what am I doing wrong or any alternate approach?

答:
findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween in your case effectively means

```<code>Get_me_documents_where {
    firstname : "98111648642"
      or
     contact : "98111648642"
      or
    location : null
      or
    gender : null
      or
   ......
}
</code>```

Since you are using OR,  it will fetch all the records. Because there might be some property which is null for all the records.

As @Niel suggested, it is not a good idea to have such a long query statement. spring-data-mongodb can handle this, but you will lose clarity.

Body:
Problem

I have to search user by name,contact whatever user types i.e if he types name he gets name only and if he type contact he gets contact only etc instead I am getting all user results.

Solution -

1st Approach

I have applied or query i.e findByNameOrContactOrLocation etc using spring data MongoDb.Below is my code.

public class Search {
private String searchKey;
private double[] location;
private List<Gender> gender;
private List<String> profession;
private List<INTERESTS> interests;
private int minAge;
private int maxAge;
private double[] height;

 @PutMapping(value = "/searchByEndUser")
ApiResponse<List<Employee>> searchEndUserBasedOnKeyWord(@RequestBody Search params) {
    return ApiResponse.success().object(employeeService.getByWord(params));
}

@Service
public class EmployeeServiceImpl implements EmployeeService {

@Override
public List<Employee> getByWord(Search params) {
    return employeeRepository.findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween(params.getSearchKey(), params.getSearchKey(), params.getLocation(), params.getGender(), params.getProfession(), params.getInterests(), params.getHeight(), params.getMinAge(), params.getMaxAge());
}

public interface EmployeeRepository extends MongoRepository<Employee, String> {
List<Employee> findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween(String searchKey, String searchKey1, double[] location, List<Gender> gender, List<String> profession, List<INTERESTS> interests, double[] height, int minAge, int maxAge);

}

Input Supplied

{
"searchKey": "98111648642"
}

Output Expected

 {
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510303944245,
  "lastModifiedAt": 1510303944245,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "98111648642",
  "email": null,
  "address": "13",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jack",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0568c879eb192b872592b3"
 }
 ]
 }

Below I am showing only 2 outputs

Output Shown

{
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510228467303,
  "lastModifiedAt": 1510228467303,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "9811164864",
  "email": null,
  "address": "32",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jui",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0441f379eb1930d9f961b2"
},
{
  "createdBy": "anonymousUser",
  "lastModifiedBy": "anonymousUser",
  "version": 0,
  "createdAt": 1510303944245,
  "lastModifiedAt": 1510303944245,
  "imageIds": null,
  "concerns": null,
  "summary": null,
  "likings": null,
  "occupation": null,
  "religion": null,
  "education": null,
  "height": null,
  "location": null,
  "interests": null,
  "fcmId": null,
  "connections": null,
  "declined": null,
  "pending": null,
  "likes": 0,
  "dislikes": 0,
  "review": null,
  "ratings": null,
  "favourites": null,
  "disConnReason": null,
  "employee_status": null,
  "employee_role": null,
  "age": 0,
  "notification": false,
  "contact": "98111648642",
  "email": null,
  "address": "13",
  "gender": null,
  "imageId": null,
  "firstName": null,
  "lastName": null,
  "middleName": null,
  "dob": null,
  "username": "jack",
  "country": null,
  "designation": null,
  "aboutMe": null,
  "profession": null,
  "sos": null,
  "secret": null,
  "socialProfile": null,
  "socialProfileLink": null,
  "socialToken": null,
  "socialProfilePicture": null,
  "referralCode": null,
  "refCons": 0,
  "referredUserId": null,
  "choice": null,
  "id": "5a0568c879eb192b872592b3"
}
]
}

**2nd Approach**

1)I can check if the data is coming from user set it or set a random data.Though I have not implemented it.I am looking for alternate approach for this.

Can anyone guide for what am I doing wrong or any alternate approach?

Body:
findByFirstNameOrContactOrLocationOrGenderInOrProfessionInOrInterestsInOrHeightOrAgeBetween in your case effectively means

Get_me_documents_where {
    firstname : "98111648642"
      or
     contact : "98111648642"
      or
    location : null
      or
    gender : null
      or
   ......
}

Since you are using OR,  it will fetch all the records. Because there might be some property which is null for all the records.

As @Niel suggested, it is not a good idea to have such a long query statement. spring-data-mongodb can handle this, but you will lose clarity.


问:
How to activate found cell with find function?
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:</p>

```<code>  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop
</code>```

答:
You're actually pretty close. Here's how to make it work, with some minor "not necessary but still good to have" improvements:

```<code>Sub test()
    Dim rng As Range
    Do
        Set rng = Cells.Find(What:="b")
        If Not rng Is Nothing Then
            rng.EntireRow.Delete
        Else
            MsgBox ("All headers deleted")
            Exit Do
        End If
    Loop
End Sub
</code>```

The reason I added a Range object and declare it before we even enter the If loop is mostly for readability but also so we don't attempt to use .Find several times. It's unlikely this has any major impact - the compiler probably fixes this by itself. Regardless, it doesn't hurt to make it explicit in the code.

The reason you get an error after the last instance is deleted is because the code tries to .Activate an empty range. This operation isn't permitted. One solution, namely the one I've gone for here, is to check whether the range object is valid before attempting to call any of its members. If the object isn't valid, the loop will skip it altogether and we don't get any errors. The way this works is, Range.Find returns Nothing (which is a valid object state) if it doesn't find anything. You'll see in my code that I am telling the compiler to enter the loop only if rng doesn't contain Nothing.

I also removed all .Select calls, because it's not good practice. Best practice is to declare all variables explicitly and working directly on ranges. The resulting code is also shorter and easier to read.

The final edit is adding Exit Do in your Else clause. This is highly necessary since you didn't add any break condition to your Do ... Loop. Without an Exit Do somewhere, the program would toss MsgBox at you forever.

It's also possible to move from Exit Do to a more robust Do ... Loop with conditions - it could look like this:

```<code>Sub test()
    Dim rng As Range
    Do
        Set rng = Cells.Find(What:="b")
        If Not rng Is Nothing Then
            rng.EntireRow.Delete
        Else
            MsgBox ("All headers deleted")
        End If
    Loop While (Not rng Is Nothing)
End Sub
</code>```

Body:
I am trying to create a Macro that will find each cell that contains a specific value (e.g.:Location) then deletes the whole row of that cell. There will be multiple cells that contain that value and I want all of them deleted so I have created a loop but because of the way I've done it, it breaks after the last one and it doesn't carry on with the last bit of the macro. I cannot find another way around so I am hoping someone will be smarter than me and can help me out with this one. The code looks like this now:

  Do
   If Cells.Find(What:="Location").Activate Then
    ActiveCell.EntireRow.Select
    Selection.Delete
   Else MsgBox ("All headers deleted")
   End If
  Loop

Body:
You're actually pretty close. Here's how to make it work, with some minor "not necessary but still good to have" improvements:

Sub test()
    Dim rng As Range
    Do
        Set rng = Cells.Find(What:="b")
        If Not rng Is Nothing Then
            rng.EntireRow.Delete
        Else
            MsgBox ("All headers deleted")
            Exit Do
        End If
    Loop
End Sub

The reason I added a Range object and declare it before we even enter the If loop is mostly for readability but also so we don't attempt to use .Find several times. It's unlikely this has any major impact - the compiler probably fixes this by itself. Regardless, it doesn't hurt to make it explicit in the code.

The reason you get an error after the last instance is deleted is because the code tries to .Activate an empty range. This operation isn't permitted. One solution, namely the one I've gone for here, is to check whether the range object is valid before attempting to call any of its members. If the object isn't valid, the loop will skip it altogether and we don't get any errors. The way this works is, Range.Find returns Nothing (which is a valid object state) if it doesn't find anything. You'll see in my code that I am telling the compiler to enter the loop only if rng doesn't contain Nothing.

I also removed all .Select calls, because it's not good practice. Best practice is to declare all variables explicitly and working directly on ranges. The resulting code is also shorter and easier to read.

The final edit is adding Exit Do in your Else clause. This is highly necessary since you didn't add any break condition to your Do ... Loop. Without an Exit Do somewhere, the program would toss MsgBox at you forever.

It's also possible to move from Exit Do to a more robust Do ... Loop with conditions - it could look like this:

Sub test()
    Dim rng As Range
    Do
        Set rng = Cells.Find(What:="b")
        If Not rng Is Nothing Then
            rng.EntireRow.Delete
        Else
            MsgBox ("All headers deleted")
        End If
    Loop While (Not rng Is Nothing)
End Sub


问:
Error when running composer install An error occurred when executing the \"'cache:clear --no-warmup'\" command:
I am trying to boot up a Vagrant machine(with ansible) that is throwing an error when it gets to the task of "composer install".  I searched this problem and tried multiple solutions that did not work(explained below).

I believe it has to do with vagrant user not having permission to write to app/cache and app/log even if I change the permission on VM and local.  Not sure what the fix would be.

Error:

failed: [default] (item=composer install) => {"changed": true, "cmd":
  ["composer", "install"], "delta": "0:00:06.144861", "end": "2017-11-16
  12:03:03.366269", "failed": true, "item": "composer install", "rc": 1,
  "start": "2017-11-16 12:02:57.221408", "stderr": "Loading composer
  repositories with package information\nInstalling dependencies
  (including require-dev) from lock file\nNothing to install or
  update\nGenerating autoload files\n>
  Incenteev\ParameterHandler\ScriptHandler::buildParameters\n>
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap\n>
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache\nScript
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache
  handling the symfony-scripts event terminated with an exception\n\n

  \n  [RuntimeException]

  \n  An error occurred when executing the \"'cache:clear --no-warmup'\"
  command:

  \n   // Clearing the cache for the dev environment with debug true

  \n

  \n    [Symfony\Component\Filesystem\Exception\IOException]

  \n    Failed to remove directory
  \"/var/www/fisher.dev/app/cache/de~/annotations\": .

  \n

  \n  cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-s|--shell] [--process-isolation] [-e|--env
  ENV] [--no-debug] [--]   \n  .

  \n

Composer.json file:

```<code>{
"name": "fostermadeco/fisher",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "symfony/symfony": "2.8.*",
    "doctrine/orm": "^2.4.8",
    "doctrine/doctrine-bundle": "~1.4",
    "symfony/swiftmailer-bundle": "~2.3",
    "symfony/monolog-bundle": "~2.11.3",
    "sensio/distribution-bundle": "~5.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "incenteev/composer-parameter-handler": "~2.0",
    "snc/redis-bundle": "^2.0",
    "predis/predis": "^1.1",
    "doctrine/doctrine-migrations-bundle": "1.2.1",
    "alcaeus/mongo-php-adapter": "^1.0",
    "doctrine/mongodb-odm": "^1.2",
    "doctrine/mongodb-odm-bundle": "^3.2",
    "ocramius/package-versions": "^1.1",
    "ircmaxell/random-lib": "^1.2",
    "jms/serializer-bundle": "^1.1",
    "nelmio/api-doc-bundle": "^2.13",
    "maba/webpack-bundle": "^0.6.4",
    "stripe/stripe-php": "^4.3",
    "doctrine/annotations": "^1.3",
    "bugsnag/bugsnag-symfony": "^1.0",
    "stof/doctrine-extensions-bundle": "^1.2",
    "danielstjules/stringy": "^2.3",
    "doctrine/migrations": "1.4.1",
    "beberlei/DoctrineExtensions": "1.0.*"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "symfony/phpunit-bridge": "~2.7",
    "doctrine/data-fixtures": "^1.2",
    "hautelook/alice-bundle": "^1.4"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "bin-dir": "bin"
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "public",
    "symfony-assets-install": "relative",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": null
},
"minimum-stability": "dev"
}
</code>```

I am able to clear the cache using both 'php app/console cache:clear' and 'php app/console cache:clear --no-warmup'

I am also able to 'rm -rf app/cache/*' and I have changed the permission on the cache folder 'sudo chmod -R 777 app/cache'

I am using ansible which sets the date.timezone='America/New_York'

Any help would be really appreciated! Thanks!

答:
the problem seems to come from how VMs deal with mapped paths.

Change the ownership and permissions on files in the project directory from within the VM would execute without error - but upon further investigation, You could see that the ownership and permissions hadn't actually been changed.

Body:
I am trying to boot up a Vagrant machine(with ansible) that is throwing an error when it gets to the task of "composer install".  I searched this problem and tried multiple solutions that did not work(explained below).

I believe it has to do with vagrant user not having permission to write to app/cache and app/log even if I change the permission on VM and local.  Not sure what the fix would be.

Error:

failed: [default] (item=composer install) => {"changed": true, "cmd":
  ["composer", "install"], "delta": "0:00:06.144861", "end": "2017-11-16
  12:03:03.366269", "failed": true, "item": "composer install", "rc": 1,
  "start": "2017-11-16 12:02:57.221408", "stderr": "Loading composer
  repositories with package information\nInstalling dependencies
  (including require-dev) from lock file\nNothing to install or
  update\nGenerating autoload files\n>
  Incenteev\ParameterHandler\ScriptHandler::buildParameters\n>
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap\n>
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache\nScript
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache
  handling the symfony-scripts event terminated with an exception\n\n

  \n  [RuntimeException]

  \n  An error occurred when executing the \"'cache:clear --no-warmup'\"
  command:

  \n   // Clearing the cache for the dev environment with debug true

  \n

  \n    [Symfony\Component\Filesystem\Exception\IOException]

  \n    Failed to remove directory
  \"/var/www/fisher.dev/app/cache/de~/annotations\": .

  \n

  \n  cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-s|--shell] [--process-isolation] [-e|--env
  ENV] [--no-debug] [--]   \n  .

  \n

Composer.json file:

{
"name": "fostermadeco/fisher",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "symfony/symfony": "2.8.*",
    "doctrine/orm": "^2.4.8",
    "doctrine/doctrine-bundle": "~1.4",
    "symfony/swiftmailer-bundle": "~2.3",
    "symfony/monolog-bundle": "~2.11.3",
    "sensio/distribution-bundle": "~5.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "incenteev/composer-parameter-handler": "~2.0",
    "snc/redis-bundle": "^2.0",
    "predis/predis": "^1.1",
    "doctrine/doctrine-migrations-bundle": "1.2.1",
    "alcaeus/mongo-php-adapter": "^1.0",
    "doctrine/mongodb-odm": "^1.2",
    "doctrine/mongodb-odm-bundle": "^3.2",
    "ocramius/package-versions": "^1.1",
    "ircmaxell/random-lib": "^1.2",
    "jms/serializer-bundle": "^1.1",
    "nelmio/api-doc-bundle": "^2.13",
    "maba/webpack-bundle": "^0.6.4",
    "stripe/stripe-php": "^4.3",
    "doctrine/annotations": "^1.3",
    "bugsnag/bugsnag-symfony": "^1.0",
    "stof/doctrine-extensions-bundle": "^1.2",
    "danielstjules/stringy": "^2.3",
    "doctrine/migrations": "1.4.1",
    "beberlei/DoctrineExtensions": "1.0.*"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "symfony/phpunit-bridge": "~2.7",
    "doctrine/data-fixtures": "^1.2",
    "hautelook/alice-bundle": "^1.4"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "bin-dir": "bin"
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "public",
    "symfony-assets-install": "relative",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": null
},
"minimum-stability": "dev"
}

I am able to clear the cache using both 'php app/console cache:clear' and 'php app/console cache:clear --no-warmup'

I am also able to 'rm -rf app/cache/*' and I have changed the permission on the cache folder 'sudo chmod -R 777 app/cache'

I am using ansible which sets the date.timezone='America/New_York'

Any help would be really appreciated! Thanks!


问:
Get ListView items from other windows
I'm doing some project on c#.
I need to get i item from ListView window, handle of it I got by doing something like this

```<code>IntPtr par_hWnd = API.FindWindow(null, "Form1");
IntPtr child1 = API.FindWindowEx(par_hWnd, (IntPtr)0, null, null);
</code>```

API is my static class with lots of dllimports from "user32.dll"
I am able to get count of items in this ListView:

```<code>IntPtr count = API.SendMessage(child1, API.LVM_GETITEMCOUNT, 0, 0);
</code>```

Now i need to get the text of item, but the result somehow must be placed in the LVITEM Structure, I don't know how to call SendMessage correctly, and how to implement LVITEM in c#. Can't find examples for c#. Any help?

答:
I found a C# wrapper for WinAPIs that seems to provide access to the contents of an LV from any window.

ManagedWinapi

```<code>using ManagedWinapi.Windows;
using System;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a SystemWindow object from the HWND of the ListView
            SystemWindow lvWindow = new SystemWindow((IntPtr)0x6d1d38);

            // Create a ListView object from the SystemWindow object
            var lv = SystemListView.FromSystemWindow(lvWindow);

            // Read text from a row
            var text = lv[0].Title;
        }
    }
}
</code>```

Also, I have also forked mwapi here and am trying to add some new functionality - Mainly centred around colouring ListView rows, but also adding some missing p/invokes etc.

Title: Get ListView items from other windows

Body:
I'm doing some project on c#.
I need to get i item from ListView window, handle of it I got by doing something like this

IntPtr par_hWnd = API.FindWindow(null, "Form1");
IntPtr child1 = API.FindWindowEx(par_hWnd, (IntPtr)0, null, null);

API is my static class with lots of dllimports from "user32.dll"
I am able to get count of items in this ListView:

IntPtr count = API.SendMessage(child1, API.LVM_GETITEMCOUNT, 0, 0);

Now i need to get the text of item, but the result somehow must be placed in the LVITEM Structure, I don't know how to call SendMessage correctly, and how to implement LVITEM in c#. Can't find examples for c#. Any help?

Body:
I found a C# wrapper for WinAPIs that seems to provide access to the contents of an LV from any window.

ManagedWinapi

using ManagedWinapi.Windows;
using System;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a SystemWindow object from the HWND of the ListView
            SystemWindow lvWindow = new SystemWindow((IntPtr)0x6d1d38);

            // Create a ListView object from the SystemWindow object
            var lv = SystemListView.FromSystemWindow(lvWindow);

            // Read text from a row
            var text = lv[0].Title;
        }
    }
}

Also, I have also forked mwapi here and am trying to add some new functionality - Mainly centred around colouring ListView rows, but also adding some missing p/invokes etc.


问:
amazon-dynamodb and filtering by date
I have a dynamodb table which has a GlobalSecondaryIndex with a date field as attribute of keytype "range". Values are stored in ISO-format "YYYY-MM-DD".
I want to access in node only records with dates greater than a certain date.
It seems to work with a parameter for my query:

```<code>KeyConditionExpression: 'myDate >= :myDate',
ExpressionAttributeValues: {
    ':myDate': '2017-11-17'
}
</code>```

However I do not quite understand. The date is technically speaking a string. Is it reliable to trust the string comparison or should it be done in a different way?

答:
Yes, you can relay on this as long as the date is stored in YYYY-MM-DD format.

DynamoDB doesn't have a separate data type for Date. Date can be stored either as String or Number.

```<code>Date    S (string type). The Date values are stored as ISO-8601 formatted strings.
</code>```

Storing date as String:-

You can use the string data type to represent a date or a time stamp.
  One way to do this is by using ISO 8601 strings, as shown in these
  examples:

2016-02-15

2015-12-21T17:42:34Z

20150311T122706Z

Storing date as Number:-

You can use the number data type to represent a date or a time stamp.
  One way to do this is by using epoch time—the number of seconds since
  00:00:00 UTC on 1 January 1970. For example, the epoch time 1437136300
  represents 12:31:40 UTC on 17 July 2015.

Data types

Title: amazon-dynamodb and filtering by date

Body:
I have a dynamodb table which has a GlobalSecondaryIndex with a date field as attribute of keytype "range". Values are stored in ISO-format "YYYY-MM-DD".
I want to access in node only records with dates greater than a certain date.
It seems to work with a parameter for my query:

KeyConditionExpression: 'myDate >= :myDate',
ExpressionAttributeValues: {
    ':myDate': '2017-11-17'
}

However I do not quite understand. The date is technically speaking a string. Is it reliable to trust the string comparison or should it be done in a different way?

Body:
Yes, you can relay on this as long as the date is stored in YYYY-MM-DD format.

DynamoDB doesn't have a separate data type for Date. Date can be stored either as String or Number.

Date    S (string type). The Date values are stored as ISO-8601 formatted strings.

Storing date as String:-

You can use the string data type to represent a date or a time stamp.
  One way to do this is by using ISO 8601 strings, as shown in these
  examples:

2016-02-15

2015-12-21T17:42:34Z

20150311T122706Z

Storing date as Number:-

You can use the number data type to represent a date or a time stamp.
  One way to do this is by using epoch time—the number of seconds since
  00:00:00 UTC on 1 January 1970. For example, the epoch time 1437136300
  represents 12:31:40 UTC on 17 July 2015.

Data types


答:
Yes, it's safe.

A different syntax to do the same thing could be:

```<code>Base::operator=( rhs );
</code>```

Title: calling operators of base class... safe?

Body:
Is following pattern ok/safe ? Or are there any shortcomings ?
(I also use it for equality operators)

Derived& operator=(const Derived& rhs)
{
    static_cast<Base&>(*this) = rhs;
    // ... copy member variables of Derived
    return *this;
}

Body:
Yes, it's safe.

A different syntax to do the same thing could be:

Base::operator=( rhs );


问:
Error while uploading existing file to google drive using Laravel 5.4
I'm using Laravel 5.4. I'm trying to upload file to google drive using

Storage::disk('google')->put('file.txt', 'hello world')

using above method file named 'file.txt' is created in Google Drive folder. but i have to upload an existing zip file.

I'm using the below code to upload the zip file in google drive.

Storage::disk('google')->put('RandomFileName.zip', storage_path('app/backup.zip'));

Zip file is created but with corrupted file having size in 50 byte sometimes.

答:
As per the documentation for Laravel File Storage you should use the copy or move method, not put.

So your code should be something like:

```<code>Storage::disk('google')->move(storage_path('app/backup.zip'), 'RandomFileName.zip');
</code>```

Body:
As per the documentation for Laravel File Storage you should use the copy or move method, not put.

So your code should be something like:

Storage::disk('google')->move(storage_path('app/backup.zip'), 'RandomFileName.zip');


问:
How to Deal with Temporary NSManagedObject instances?
I need to create NSManagedObject instances, do some stuff with them and then trash them or store to sqlite db. The problem is, I cannot create instances of NSManagedObject unconnected to NSManagedObjectContext and this means I have to clear up somehow  after I decide that I don't need some of the objects in my db.

To deal with it, I have created an in-memory store using the same coordinator and I'm placing temporary objects there by using assignObject:toPersistentStore. Now, how do I ensure that these temporary objects don't get to the data, which I fetch from the common to both stores context? Or do I have to create separate contexts for such a task?

UPD:

Now I'm thinking about making separate context for in-memory store. How do I move objects from one context to another? Just using [context insertObject:]? Will it work OK in this setup? If I insert one object from the graph of objects, does the whole graph also get inserted into context?

答:
I am rewriting this answer for Swift as all similar questions for swift redirect to this question.

You can declare the object without any ManagedContext using the following code.

```<code>let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: myContext)
let unassociatedObject = NSManagedObject.init(entity: entity!, insertInto: nil)
</code>```

Later on, to save the object you can insert it into the context and save it.

```<code>myContext.insert(unassociatedObject)
// Saving the object
do {
    try self.stack.saveContext()
    } catch {
        print("save unsuccessful")
    }
}
</code>```

Body:
I am rewriting this answer for Swift as all similar questions for swift redirect to this question.

You can declare the object without any ManagedContext using the following code.

let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: myContext)
let unassociatedObject = NSManagedObject.init(entity: entity!, insertInto: nil)

Later on, to save the object you can insert it into the context and save it.

myContext.insert(unassociatedObject)
// Saving the object
do {
    try self.stack.saveContext()
    } catch {
        print("save unsuccessful")
    }
}


问:
Update DLL reference
I wanted to update some DLLs used in my .NET project to the latest version and I've noticed that, if I replace the DLLs on the file system with their new versions, VS 2012 updates the DLL version number in the Properties window.

Is this some new feature of VS 2012? I don't remember seeing it in VS 2010 (I expected it would need more manual handling).

Is this working right, or should I remove and re-add the DLLs manually from the references, just to be sure?

Anyway, my project compiles and runs fine, so I guess it works...

EDIT:

I guess it works because the DLLs are not strongly named (http://msdn.microsoft.com/en-us/library/wd40t7ad.aspx)?
Perhaps I should re-add them if they were...
Inside the project file I saw it had the old version number, but in the properties window I saw the new one...

Thanks!

答: better option is to de refrence the dll and refrence again but make sure for safety purpse you keep the backup of your previous dll... </p>

Title: Update DLL reference


问:
Knockout.js get dom object associated with data
I'm working with knockout.js to build dynamic lists and I'm trying to figure out how I can get the DOM object associated with an object in my observable array.  Specifically I want to get the jQuery for a row.

Example:

```<code><ul data-bind="foreach: Item">
    <li data-bind="events: {click: getDomObject}, text: 'text: ' + text">
    </li>
</ul>
</code>```

in the getDomObject function, I would like to be able to get the specific

 DOM object so that I can do some jQuery manipulation with it.

I've thought about adding an id member to the Item ViewModel and then add the id as the line item's html id and then select based on that, but I feel that there should be an easier way.

What is the proper way to reference the dynamic HTML generated by knockout.js?

答:
My solution (valid for "value" binding)

```<code> ko.bindingHandlers.value.preprocess = function(val, name, cb) {
    /* every time I set a data-bind="value: xxxx" with an
     * observable xxxx add also a data-bind="domElement: xxxx" */
    cb('domElement', val );
    return val;
}

ko.bindingHandlers.domElement = {
    /* For each data-bind="domElement: xxxx" add an extension "element" */
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
      valueAccessor().extend({element: element });
    }
  };

ko.extenders.element = function (target, element) {
    /* element extension add el and $el to observable xxxx */
    target.el = element;
    target.$el = $(element);
}
</code>```

Now you have yourobservable.$el and yourobservable.el which bind to jquery and DOM element.

Body:
I'm working with knockout.js to build dynamic lists and I'm trying to figure out how I can get the DOM object associated with an object in my observable array.  Specifically I want to get the jQuery for a row.

Example:

in the getDomObject function, I would like to be able to get the specific

 DOM object so that I can do some jQuery manipulation with it.

I've thought about adding an id member to the Item ViewModel and then add the id as the line item's html id and then select based on that, but I feel that there should be an easier way.

What is the proper way to reference the dynamic HTML generated by knockout.js?

Body:
My solution (valid for "value" binding)

 ko.bindingHandlers.value.preprocess = function(val, name, cb) {
    /* every time I set a data-bind="value: xxxx" with an
     * observable xxxx add also a data-bind="domElement: xxxx" */
    cb('domElement', val );
    return val;
}

ko.bindingHandlers.domElement = {
    /* For each data-bind="domElement: xxxx" add an extension "element" */
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
      valueAccessor().extend({element: element });
    }
  };

ko.extenders.element = function (target, element) {
    /* element extension add el and $el to observable xxxx */
    target.el = element;
    target.$el = $(element);
}

Now you have yourobservable.$el and yourobservable.el which bind to jquery and DOM element.


问:
flask render_template with url parameter
I use pdf.js to render pdf in web. The format of the target url like this:

```<code>http://www.example.com/book?file=abc.pdf
</code>```

My problem is:
I use flask template to generate page using:

```<code>return render_template('book.html', paraKey=paraValue)
</code>```

But how to attach url parameter "file=abc.pdf" to url?
The parameter will be read by viewer.js(included in book.html) that uses it to read file for rendering pdf.

I'm new to flask, hoping guys giving me some help!

答:
You can get the parameter that have been passed in the request url by using the request object. </p>

```<code>    @app.route("/book", methods=["GET"])
    def get_book():
        file = request.args.get("file")
        if file:
            return render_template('book.html', file=file)
        abort(401, description="Missing file parameter in request url")
</code>```

Body:
I use pdf.js to render pdf in web. The format of the target url like this:

http://www.example.com/book?file=abc.pdf

My problem is:
I use flask template to generate page using:

return render_template('book.html', paraKey=paraValue)

But how to attach url parameter "file=abc.pdf" to url?
The parameter will be read by viewer.js(included in book.html) that uses it to read file for rendering pdf.

I'm new to flask, hoping guys giving me some help!

Body:
You can get the parameter that have been passed in the request url by using the request object.

    @app.route("/book", methods=["GET"])
    def get_book():
        file = request.args.get("file")
        if file:
            return render_template('book.html', file=file)
        abort(401, description="Missing file parameter in request url")


问:
SQL Select on priority of not exist
I'm quite confused as to how I'd structure a query I need:

```<code>select distinct NodeID from GroupsTable
                    where GroupID in
                    (
                        select GroupID from UserGroupsTable
                        where UserID = @UserID
                    )
</code>```

I need to select NodeID from GroupsTable where the User belongs to multiple groups, UNLESS any group that the user belongs to does not have that NodeID.

The above code only selects a NodeID from GroupsTable where it apears in any one of the users groups.

So:

Group|Node

1|A

  1|B

  2|A

I need only B to be selected for example.

Any Ideas?

答:
```<code>declare @UserID int
select G.NodeID
from GroupsTable G
inner join
(
    select GroupID, count(*) over () GroupCount
    from UserGroupsTable
    where UserID = @UserID
) UG on UG.GroupID = G.GroupID
GROUP BY G.NodeID, UG.GroupCount
HAVING COUNT(*) != UG.GroupCount OR UG.GroupCount = 1
-- count=1 is special. it will always equal groupcount, but let it through
</code>```

(assuming this is SQL Server and version >= 2005 for using the count(*) over)

@answer HAVING condition changed following comments

Title: SQL Select on priority of not exist

Body:
I'm quite confused as to how I'd structure a query I need:

select distinct NodeID from GroupsTable
                    where GroupID in
                    (
                        select GroupID from UserGroupsTable
                        where UserID = @UserID
                    )

I need to select NodeID from GroupsTable where the User belongs to multiple groups, UNLESS any group that the user belongs to does not have that NodeID.

The above code only selects a NodeID from GroupsTable where it apears in any one of the users groups.

So:

Group|Node

1|A

  1|B

  2|A

I need only B to be selected for example.

Any Ideas?

Body:
declare @UserID int
select G.NodeID
from GroupsTable G
inner join
(
    select GroupID, count(*) over () GroupCount
    from UserGroupsTable
    where UserID = @UserID
) UG on UG.GroupID = G.GroupID
GROUP BY G.NodeID, UG.GroupCount
HAVING COUNT(*) != UG.GroupCount OR UG.GroupCount = 1
-- count=1 is special. it will always equal groupcount, but let it through

(assuming this is SQL Server and version >= 2005 for using the count(*) over)

@answer HAVING condition changed following comments


问:
How do we change AppPool idle timeout in Plesk WebAdmin (Shared Hosting)?
I have a website that is hosted on Plesk in Shared Hosting. The session keeps on timing out because the app pool recycles after 5 minutes (even though session timeout is set to 30 min). The effect of session timeout is exaggerated because current user activity is quite low and for users testing the app, the session keeps on timing out every 5 minutes.

On plesk web hosting panel, I can see the AppPool settings but they are disabled. Is there a way to change this setting?

答:
It's possible in Plesk for Plesk admin and customers/resellers:

Permissions to manage IIS pool settings are granted on a service plan level. Contact Plesk admin to change permissions on a service plan that your domain is assigned.

If you login to Plesk under an 'admin' user, make sure your Plesk is opened in a Service Provider view as this view allows editing Service Plans.


问:
Retrieve cookie right after set in javascript
What is the best way to retrieve cookie right after the Google Analytics set it '_ga'? I need to save cookie value locally in the database.

Sample code:

```<code><!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-281681-2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
gtag('config', 'UA-TRACKING-ID');

// retrieve _ga cookie:
  function getCookie(name){
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
  }
  var cidLong = getCookie('_ga');
  var cid="NA";
  if (cidLong) {
   var tmp = cidLong.split('.');
   cid = tmp[2] + '.' + tmp[3];
  }
  // Will return 'NA' if _ga cookie is set first time
  console.log("cid: "+cid);

</script>
</code>```

It is possible to use setTimeout function to check if the cookie is set but is there a better way like using events?

答:
There is no direct event you can add on the document.cookies object. You can write your own event handler, a function that periodically searches for a change in the document.cookies. Based on this answer, I tried to rewrite the cookieHandler using ES6 syntax with arrow. You can proceed this way:

var lastCookie = document.cookie;

var cookieHandler = () => {
  var currentCookie = document.cookie;

  if(  currentCookie !== lastCookie){
    console.log("something changed")
    lastCookie = currentCookie
  }
}

setInterval(cookieHandler, 1000); // the function is run after each 1s
```

Body:
What is the best way to retrieve cookie right after the Google Analytics set it '_ga'? I need to save cookie value locally in the database.

Sample code:

It is possible to use setTimeout function to check if the cookie is set but is there a better way like using events?


问:
CUDA compiler (nvcc) macro
Is there a #define compiler (nvcc) macro of CUDA which I can use? (Like _WIN32 for Windows and so on.)

I need this for header code that will be common between nvcc and VC++ compilers. I know I can go ahead and define my own and pass it as an argument to the nvcc compiler (-D), but it would be great if there is one already defined.

答: I know it has been long time now, but you might also find  <code>__CUDA_ARCH__</code> useful. </p>

OwnerDisplayName: Ash

Title: CUDA compiler (nvcc) macro

LastEditorDisplayName: Ash

Body: I know it has been long time now, but you might also find  __CUDA_ARCH__ useful.


问:
TYPO3 : Automated TCA Generation for dynamic Domain-Model-Properties
I have built some Domain-Model-Objects, that represent DataRecords coming from an XML-Interface. To keep those Objects versatile, they are being set up using dynamic properties during __construct, using Records of an own Object-Property-Model => This allows me to add Properties via simple Backend-Module.
My problem is, that I would like to dynamically generate TCA settings (columns etc) for those properties. I have the necessary info like datatype for those columns available - Is it possible to set up functions in TCA files, that read data via DB-Connection-Pool or Records coming from a Repository to extend column data based on that dynamic data?
Best regards, Oliver</p>

答:
This may work with TCA overrides or the tcaIsBeingBuilt signal emitted by ExtensionManagementUtility.

You can also have a look at the extension autoloader which does something similar with its Smart Objects.


问:
Angular 2, can't get data after subscribe in ngOnInit
I have a problem, maybe I don't understand how to do but when I try to catch data from an HttpRequest during angular ngOnInit, my console.log return me an "undefined" value.
The thing is that when I use this value in my template view it works !

Here is my Component

```<code>export class ReferentielFormComponent implements OnInit {
  id: number;
  currentUser;
  referentiel;
  progressValue: number;
  formGroup: FormGroup;
  isNew: boolean;

  constructor(private service: AppService,
          private referentiels: ReferentielService,
          private router: ActivatedRoute,
          private config: NgbTabsetConfig) {
  }

  ngOnInit() {
    this.router.params.subscribe((params: Params) => this.id = params['id']);
    if (this.id) {
      this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
    } else {
      this.referentiel = {};
    }
    this.isNew = !this.referentiel;

    console.log(this.referentiel);
    console.log(this.isNew);
    this.progressValue = 20;

    this.formGroup = new FormGroup({
      titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
        Validators.required,
      ]),
      description: new FormControl(!this.isNew ? this.referentiel.description : '', [
        Validators.required,
      ])
    });
  }
}
</code>```

The variable this.referentiel return me an undefined so I can't bind my Form whith existing value because of that...

Any suggestions ?

答:
```<code>this.referentiel is undefined till the subscribe completes. I think you have to move the formbuilder code to subscribe.

  ngOnInit() {
        this.router.params.subscribe((params: Params) => this.id = params['id']);
        if (this.id) {
            this.referentiels.getReferentiel(this.id).subscribe(data => {
                    this.referentiel = data;
                    this.buildForm(););
            }
            else {
                this.buildForm();
                this.referentiel = {};
            }
        }
        //Build form function
        buildForm() {
            this.isNew = !this.referentiel;
            this.formGroup = new FormGroup({
                titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
                    Validators.required,
                ]),
                description: new FormControl(!this.isNew ? this.referentiel.description : '', [
                    Validators.required,
                ])
            });
        }
</code>```

Body:
I have a problem, maybe I don't understand how to do but when I try to catch data from an HttpRequest during angular ngOnInit, my console.log return me an "undefined" value.
The thing is that when I use this value in my template view it works !

Here is my Component

export class ReferentielFormComponent implements OnInit {
  id: number;
  currentUser;
  referentiel;
  progressValue: number;
  formGroup: FormGroup;
  isNew: boolean;

  constructor(private service: AppService,
          private referentiels: ReferentielService,
          private router: ActivatedRoute,
          private config: NgbTabsetConfig) {
  }

  ngOnInit() {
    this.router.params.subscribe((params: Params) => this.id = params['id']);
    if (this.id) {
      this.referentiels.getReferentiel(this.id).subscribe(data => this.referentiel = data);
    } else {
      this.referentiel = {};
    }
    this.isNew = !this.referentiel;

    console.log(this.referentiel);
    console.log(this.isNew);
    this.progressValue = 20;

    this.formGroup = new FormGroup({
      titre: new FormControl(!this.isNew ? this.referentiel.titre : '', [
        Validators.required,
      ]),
      description: new FormControl(!this.isNew ? this.referentiel.description : '', [
        Validators.required,
      ])
    });
  }
}

The variable this.referentiel return me an undefined so I can't bind my Form whith existing value because of that...

Any suggestions ?


问:
Automatic open table on phpMyAdmin-login
I want phpMyAdmin to automatically open a table, when I log in to it.
Is there a way to do this?

My reason:
In 90% of the cases I'm working in the same table in phpMyAdmin.
So the two clicks in the nav each time I start phpMyAdmin are often useless.
But I of course want the possibility to change to other tables.

答: Bookmark the url to view this specific table. You will be redirected to login, and back to that specific view afterwards</p>


问:
Remove sub array of object from main array in JavaScript with reference to object value in ie9
I need to remove set of item from main array. I have a pick list, when i select and add item from this add to another array and remove from main array.

var mainArray = [
  {
    "name": "abcd"
  },
  {
    "name": "cdf"
  },
  {
    "name": "vdf"
  },
  {
    "name": "ajj"
  },
  {
    "name": "asdf"
  },
  {
    "name": "utyt"
  },
  {
    "name": "adada"
  }
];
var subArray = [
{
    "name": "utyt"
  },
  {
    "name": "adada"
  }
];
  //need main array with out subarray```

Also I use underscore js. Please help me out

答:
You don't need underscore for that, just use array.prototype.filter :

var mainArray = [
  {
    "name": "abcd"
  },
  {
    "name": "cdf"
  },
  {
    "name": "vdf"
  },
  {
    "name": "ajj"
  },
  {
    "name": "asdf"
  },
  {
    "name": "utyt"
  },
  {
    "name": "adada"
  }
];
var subArray = [{
    "name": "utyt"
  },
  {
    "name": "adada"
  }];

 mainArray = mainArray.filter(function(e) {
     return !subArray.some(function(s) {
         return s.name === e.name;
     });
 });
 console.log(mainArray);```

Body:
I need to remove set of item from main array. I have a pick list, when i select and add item from this add to another array and remove from main array.

var mainArray = [
  {
    "name": "abcd"
  },
  {
    "name": "cdf"
  },
  {
    "name": "vdf"
  },
  {
    "name": "ajj"
  },
  {
    "name": "asdf"
  },
  {
    "name": "utyt"
  },
  {
    "name": "adada"
  }
];
var subArray = [
{
    "name": "utyt"
  },
  {
    "name": "adada"
  }
];
  //need main array with out subarray

Also I use underscore js. Please help me out


问:
How to let two docker containers can ping each other
I have two docker containers A & B, I want to do is in both containers can ping the other container. How should I do? And in one container, what's ip address should I use to ping the other container?

My OS is ubuntu:14.04, docker version is 1.6.2

答:
You can get the ip-address of containers from bridge by using
"docker network inspect bridge"
then from one container ping the other with the ip address using
"ping -w3 ip-address"</p>


问:
Get the Directory of $(ProjectDir) in VC++
In vcproj Property, there exists a list of build macro properties. Among them are $(OutDir), $(ProjectName) and $(ProjectDir).

Question, what is the macro ( or the command to get the directory of $(ProjectDir)?

This is because I want to write the output dll to the parent directory of $(ProjectDir), or a folder inside the parent folder.

答:
simply set Settings->General->Output Directory ( == OutputDirectory element under  section in the vcproj file) to $(ProjectDir)..

alternatively if you want just the executable there, not the pdb etc, change the General->OutputFile to $(ProjectDir)..\$(TargetFileName)

edit: since this doesn't seeem to work for you, but it does for me, maybe you're missing a slash? Can you post the value of your $(ProjectDir)?

for example, I have these macro values in a dll project:

```<code>$(ProjectDir) d:\path\to\project\core\
$(ProjectPath) d:\path\to\project\core\core.vcproj
</code>```

consequently, setting the OutputDirectory to $(ProjectDir)..\xxx, my dll goes here: d:\path\to\project\core.dll

Body:
simply set Settings->General->Output Directory ( == OutputDirectory element under  section in the vcproj file) to $(ProjectDir)..

alternatively if you want just the executable there, not the pdb etc, change the General->OutputFile to $(ProjectDir)..\$(TargetFileName)

edit: since this doesn't seeem to work for you, but it does for me, maybe you're missing a slash? Can you post the value of your $(ProjectDir)?

for example, I have these macro values in a dll project:

$(ProjectDir) d:\path\to\project\core\
$(ProjectPath) d:\path\to\project\core\core.vcproj

consequently, setting the OutputDirectory to $(ProjectDir)..\xxx, my dll goes here: d:\path\to\project\core.dll


问:
Prometheus in k8s (metrics)
I deploy prometheus in kubernetes on this manual

As a storage scheme was invented:
Prometeus in kubernetes stores the metrics within 24 hours.
Prometheus not in kubernetes stores the metrics in 1 week.
A federation is set up between them.

Who faced with the fact that after removing the pods after a certain period of time (much less than 24 hours) metrics are missing on it.

答: This is perfectly normal if you do not have a persistent storage configured for your prometheus pod. You should use PV/PVC to define a stable place where you keep your prometheus data, otherwise if your pod is recreated, it starts with a clean slate.</p>

ContentLicense: CC BY-SA 4.0

Title: Prometheus in k8s (metrics)