问:
Struts2 REST-API with {id} is not mapped properly when API request sent along with JSON Body
Here my files.

struts.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true"/>

    <!-- restrictToGET to false makes the response to be of JSON type when request if of type POST, PUT, DELETE-->
    <constant name="struts.rest.content.restrictToGET" value="false"/>

    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="action"/>

    <constant name="struts.enable.SlashesInActionNames" value="true"/>
    <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
    <constant name="struts.patternMatcher" value="regex"/>
    <constant name="struts.matcher.appendNamedParameters" value="true"/>

    <package name="action" namespace="/" extends="rest-default,json-default">

        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
            <interceptor-stack name="jsonStack">
                <interceptor-ref name="json"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

        <action name="hello" class="com.wildcard.action.HelloController">
            <interceptor-ref name="jsonStack"/>

            <result type="json">
                <param name="root">uid</param>
            </result>
        </action>

        <action name="hello/*" class="com.wildcard.action.HelloController">
            <interceptor-ref name="jsonStack"/>

            <param name="id">{1}</param>

            <result type="json">
                <param name="root">uid</param>
            </result>
        </action>

    </package>

</struts>
</code>```

HelloController.java

```<code>package com.wildcard.action;

import com.opensymphony.xwork2.ModelDriven;
import com.wildcard.model.Hello;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

public class HelloController implements ModelDriven<Object> {

    private Hello hello = new Hello();
    private String id;
    private String uid;
    private Object model = new Object();

    public HttpHeaders index() {
        hello.setName("index");
        System.out.println("index() : " + hello);
        System.out.println("index() uid: " + uid);
        return new DefaultHttpHeaders("index");
    }

    public HttpHeaders show() {
        hello.setName("show");
        System.out.println("show() : " + hello);
        System.out.println("show() id: " + id);
        System.out.println("show() uid: " + uid);
        return new DefaultHttpHeaders("show");
    }

    public HttpHeaders create() {
        //hello.setName("create");
        System.out.println("create() : " + hello);
        System.out.println("create() id: " + id);
        System.out.println("create() uid: " + uid);
        return new DefaultHttpHeaders("create");
    }

    public HttpHeaders update() {
        hello.setName("update");
        System.out.println("update() : " + hello);
        System.out.println("update() id: " + id);
        System.out.println("update() uid: " + uid);
        return new DefaultHttpHeaders("update");
    }

    public HttpHeaders destroy() {
        hello.setName("destroy");
        System.out.println("destroy() : " + hello);
        System.out.println("destroy() id: " + id);
        System.out.println("destroy() uid: " + uid);
        return new DefaultHttpHeaders("destroy");
    }

    @Override
    public Object getModel() {
        model = hello;
        return model;
    }

    public void setModel(Object model) {
        this.model = model;
    }

    public Hello getHello() {
        return hello;
    }

    public void setHello(Hello hello) {
        this.hello = hello;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }
}
</code>```

Hello.java

```<code>package com.wildcard.model;

public class Hello {
    private String name;

    public Hello() {
    }

    public Hello(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}
</code>```

When I send the requests GET [/hello.json,/hello/{id}.json], POST [/hello.json], PUT [/hello/{id}.json], DELETE [/hello/{id}.json], without JSON Body, it's working fine. When I add JSON Body to the above requests, only the following are working, GET, POST [/hello.json]. And when I add the {id} to the URL path, I am getting the following error.

```<code>> HTTP ERROR: 500 Unable to show problem report:
>
> freemarker.core.InvalidReferenceException: The following has evaluated
> to null or missing:
>
> ==> rootloc.URI  [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column  15]
>
> ---- Tip: It's the step after the last dot that caused this error, not those before it.
> ---- Tip: If the failing expression is known to legally refer to something that's sometimes  null or missing, either specify a default
> value like myOptionalVar!myDefault, or use <#if
> myOptionalVar??>when-present<#else>when-missing</#if>. (These only
> cover the last step of  the expression; to cover the whole expression,
> use parenthesis:  (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
> ----
>
> ---- FTL stack trace ("~" means nesting-related):
> - Failed at: ${rootloc.URI}  [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 13]
> ----
>
> Class: freemarker.core.InvalidReferenceException File:
> InvalidReferenceException.java Method: getInstance Line: 134 -
> freemarker/core/InvalidReferenceException.java:134:-1
> RequestURI=/wildcard_sample/hello/2.json
>
> Powered by Jetty://
</code>```

Java stack trace (for programmers):

freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]
        at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134)
        at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481)
        at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401)
        at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370)
        at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100)
        at freemarker.core.DollarVariable.accept(DollarVariable.java:63)
        at freemarker.core.Environment.visit(Environment.java:334)
        at freemarker.core.Environment.visit(Environment.java:340)
        at freemarker.core.Environment.visit(Environment.java:340)
        at freemarker.core.Environment.process(Environment.java:313)
        at freemarker.template.Template.process(Template.java:383)
        at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:118)
        at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:76)
        at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:923)
        at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:589)
        at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79)
        at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141)
        at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
        at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
        at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
        at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
        at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
        at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
        at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
        at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
        at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
        at org.mortbay.jetty.Server.handle(Server.java:324)
        at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
        at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
        at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
        at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
        at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
        at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
        at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
```

答:
The rest plugin works well along with convention plugin, where configuration is added automatically by convention. To let the convention plugin create the configuration for actions in your application use the following settings

struts.xml:

<constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="action"/>
```
<p><code>web.xml</code>:
The parameter to struts2 filter</p>
```<init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.wildcard.action</param-value>
 </init-param>
```

Body:
Here my files.

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true"/>

    <constant name="struts.rest.content.restrictToGET" value="false"/>

    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="action"/>

    <constant name="struts.enable.SlashesInActionNames" value="true"/>
    <constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
    <constant name="struts.patternMatcher" value="regex"/>
    <constant name="struts.matcher.appendNamedParameters" value="true"/>

    <package name="action" namespace="/" extends="rest-default,json-default">

        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
            <interceptor-stack name="jsonStack">
                <interceptor-ref name="json"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

        <action name="hello" class="com.wildcard.action.HelloController">
            <interceptor-ref name="jsonStack"/>

            <result type="json">
                <param name="root">uid</param>
            </result>
        </action>

        <action name="hello/*" class="com.wildcard.action.HelloController">
            <interceptor-ref name="jsonStack"/>

            <param name="id">{1}</param>

            <result type="json">
                <param name="root">uid</param>
            </result>
        </action>

    </package>

</struts>

HelloController.java

package com.wildcard.action;

import com.opensymphony.xwork2.ModelDriven;
import com.wildcard.model.Hello;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

public class HelloController implements ModelDriven<Object> {

    private Hello hello = new Hello();
    private String id;
    private String uid;
    private Object model = new Object();

    public HttpHeaders index() {
        hello.setName("index");
        System.out.println("index() : " + hello);
        System.out.println("index() uid: " + uid);
        return new DefaultHttpHeaders("index");
    }

    public HttpHeaders show() {
        hello.setName("show");
        System.out.println("show() : " + hello);
        System.out.println("show() id: " + id);
        System.out.println("show() uid: " + uid);
        return new DefaultHttpHeaders("show");
    }

    public HttpHeaders create() {
        //hello.setName("create");
        System.out.println("create() : " + hello);
        System.out.println("create() id: " + id);
        System.out.println("create() uid: " + uid);
        return new DefaultHttpHeaders("create");
    }

    public HttpHeaders update() {
        hello.setName("update");
        System.out.println("update() : " + hello);
        System.out.println("update() id: " + id);
        System.out.println("update() uid: " + uid);
        return new DefaultHttpHeaders("update");
    }

    public HttpHeaders destroy() {
        hello.setName("destroy");
        System.out.println("destroy() : " + hello);
        System.out.println("destroy() id: " + id);
        System.out.println("destroy() uid: " + uid);
        return new DefaultHttpHeaders("destroy");
    }

    @Override
    public Object getModel() {
        model = hello;
        return model;
    }

    public void setModel(Object model) {
        this.model = model;
    }

    public Hello getHello() {
        return hello;
    }

    public void setHello(Hello hello) {
        this.hello = hello;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }
}

Hello.java

package com.wildcard.model;

public class Hello {
    private String name;

    public Hello() {
    }

    public Hello(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "name='" + name + '\'' +
                '}';
    }
}

When I send the requests GET [/hello.json,/hello/{id}.json], POST [/hello.json], PUT [/hello/{id}.json], DELETE [/hello/{id}.json], without JSON Body, it's working fine. When I add JSON Body to the above requests, only the following are working, GET, POST [/hello.json]. And when I add the {id} to the URL path, I am getting the following error.

> HTTP ERROR: 500 Unable to show problem report:
>
> freemarker.core.InvalidReferenceException: The following has evaluated
> to null or missing:
>
> ==> rootloc.URI  [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column  15]
>
> ---- Tip: It's the step after the last dot that caused this error, not those before it.
> ---- Tip: If the failing expression is known to legally refer to something that's sometimes  null or missing, either specify a default
> value like myOptionalVar!myDefault, or use <#if
> myOptionalVar??>when-present<#else>when-missing</#if>. (These only
> cover the last step of  the expression; to cover the whole expression,
> use parenthesis:  (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
> ----
>
> ---- FTL stack trace ("~" means nesting-related):
> - Failed at: ${rootloc.URI}  [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 13]
> ----
>
> Class: freemarker.core.InvalidReferenceException File:
> InvalidReferenceException.java Method: getInstance Line: 134 -
> freemarker/core/InvalidReferenceException.java:134:-1
> RequestURI=/wildcard_sample/hello/2.json
>
> Powered by Jetty://

Java stack trace (for programmers):

freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]
        at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134)
        at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481)
        at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401)
        at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370)
        at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100)
        at freemarker.core.DollarVariable.accept(DollarVariable.java:63)
        at freemarker.core.Environment.visit(Environment.java:334)
        at freemarker.core.Environment.visit(Environment.java:340)
        at freemarker.core.Environment.visit(Environment.java:340)
        at freemarker.core.Environment.process(Environment.java:313)
        at freemarker.template.Template.process(Template.java:383)
        at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:118)
        at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:76)
        at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:923)
        at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:589)
        at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79)
        at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141)
        at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
        at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
        at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
        at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
        at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726)
        at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
        at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206)
        at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
        at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
        at org.mortbay.jetty.Server.handle(Server.java:324)
        at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
        at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
        at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:648)
        at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
        at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
        at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
        at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)

Body:
The rest plugin works well along with convention plugin, where configuration is added automatically by convention. To let the convention plugin create the configuration for actions in your application use the following settings

struts.xml:

<constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="action"/>

web.xml:
The parameter to struts2 filter

<init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.wildcard.action</param-value>
 </init-param>


来源: stackexchange

问:
excel formula to select column values based on two conditions
I want to select the values column values corresponding to 0% and Bravo, so I want the values 0.939958, 0,067266 etc. Could someone help me out to select the values? I have tried this:

```<code>=CHOOSE(MATCH((L2=B2:J2)*(L3=B3:J3);0);B4:B21;C4:C21;D4:D21;E4:E21;F4:F21;G4:G21;H4:H21;I4:I21;J4:J21)
</code>```

But this did not work..

Kind regards.

答:
With ms365, try:

Formula in K3:

```<code>=INDEX(FILTER(A3:I12,A2:I2=K2),0,1+K1*2)
</code>```

Note that I just used RANDARRAY() to fill the matrix with sample data.

ContentLicense: CC BY-SA 4.0

Body:
I want to select the values column values corresponding to 0% and Bravo, so I want the values 0.939958, 0,067266 etc. Could someone help me out to select the values? I have tried this:

=CHOOSE(MATCH((L2=B2:J2)*(L3=B3:J3);0);B4:B21;C4:C21;D4:D21;E4:E21;F4:F21;G4:G21;H4:H21;I4:I21;J4:J21)

But this did not work..

Kind regards.

Body:
With ms365, try:

Formula in K3:

=INDEX(FILTER(A3:I12,A2:I2=K2),0,1+K1*2)

Note that I just used RANDARRAY() to fill the matrix with sample data.


问:
How to count sequential repeats of a value (allowing for one skip)
I am trying to produce a variable that counts how many times a "1" appeared sequentially in the preceding rows for a different variable. However, I need the count to persist even if there is one row missing a 1. (i.e., 10111011 should register as an 8). The code I use to count sequential 1s is:

The following code provides an example of the kind of thing I'm trying to do:

```<code>input <- c(1,0,1,1,0,1,1,0,1,0,1)
dfseq <- data.frame(input)
dfseq$seq <- sequence(rle(as.character(dfseq$input))$lengths)
</code>```

which produces the following dataframe:

```<code>data_struc <-
  structure(list(
    input = c(1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1),
    seq = c(1L,
            1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L)
  ),
  row.names = c(NA,-11L),
  class = "data.frame")
</code>```

However, I want the sequence to allow for one row of "failure" on the sequence, such that it continues to count consecutive ones even if one row contains a 0 and then the 1s continue. It should only stop counting once two 0s appear consecutively

答:
Not sure if we all understood the question right and the sample data clarifies not much and blurs any possible mistakes as it all follows the sequence according to OP. To be sure OP could provide a desired outcome and one based on a sample set that includes records that would break the sequence according to his criteria.

I changed the sample data a bit and this is how I interpretted the question.

```<code>dt <- data.frame(
  input = c(1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1)
)

library(data.table)
setDT(dt)

dt[, seq_count := 1:.N, by = rleid(input == 1 | (lag(input) == 1 & lead(input) != 0))]
dt[input == 0 & (lead(input) == 0 | lag(input) == 0), seq_count := NA]

dt

#     input seq_count
#  1:     1         1
#  2:     0         2
#  3:     1         3
#  4:     1         4
#  5:     0        NA
#  6:     0        NA
#  7:     1         1
#  8:     0         2
#  9:     1         3
# 10:     1         4
# 11:     0         5
# 12:     1         6
</code>```

Body:
I am trying to produce a variable that counts how many times a "1" appeared sequentially in the preceding rows for a different variable. However, I need the count to persist even if there is one row missing a 1. (i.e., 10111011 should register as an 8). The code I use to count sequential 1s is:

The following code provides an example of the kind of thing I'm trying to do:

input <- c(1,0,1,1,0,1,1,0,1,0,1)
dfseq <- data.frame(input)
dfseq$seq <- sequence(rle(as.character(dfseq$input))$lengths)

which produces the following dataframe:

data_struc <-
  structure(list(
    input = c(1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1),
    seq = c(1L,
            1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L)
  ),
  row.names = c(NA,-11L),
  class = "data.frame")

However, I want the sequence to allow for one row of "failure" on the sequence, such that it continues to count consecutive ones even if one row contains a 0 and then the 1s continue. It should only stop counting once two 0s appear consecutively

Body:
Not sure if we all understood the question right and the sample data clarifies not much and blurs any possible mistakes as it all follows the sequence according to OP. To be sure OP could provide a desired outcome and one based on a sample set that includes records that would break the sequence according to his criteria.

I changed the sample data a bit and this is how I interpretted the question.

dt <- data.frame(
  input = c(1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1)
)

library(data.table)
setDT(dt)

dt[, seq_count := 1:.N, by = rleid(input == 1 | (lag(input) == 1 & lead(input) != 0))]
dt[input == 0 & (lead(input) == 0 | lag(input) == 0), seq_count := NA]

dt

#     input seq_count
#  1:     1         1
#  2:     0         2
#  3:     1         3
#  4:     1         4
#  5:     0        NA
#  6:     0        NA
#  7:     1         1
#  8:     0         2
#  9:     1         3
# 10:     1         4
# 11:     0         5
# 12:     1         6


问:
How to update the future in FutureBuilder to get new data while using GetX
I am using GetX and FutureBuilder to build a list of Cards from my DB.
Lets say I have 10 products in DB then 10 cards are shown. When I add one more product, the Cards on the HomeScreen aren't updated and I have to Navigate in and Out of page to show the 11th product.

How can I force the update i.e. probably make a "Refresh" button that may load the latest data.

PS: I do not want to use STREAM-BUILDER as I don't wish to listen to all changes actively but only when needed. I also cannot use SetState() as I am using GetX hence no StatefulWidget.

Here is my Card class:

```<code>FutureBuilder(
                future: databaseController.getData()
                builder: (context, snapshot) {
                   return StaggeredGridView.countBuilder(
                      itemCount: snapshot.data.length,
                      crossAxisCount: 2,
                      itemBuilder: (BuildContext context, int index) =>
                          GetX<FindDeviceLocation>(builder: (controller) {
                        return CreateTheCard(
                            lindex: index,
                            location: snapshot.data[index]["location"],
                            summary: snapshot.data[index]["summary"],
                            description: snapshot.data[index]["description"],
                            category: snapshot.data[index]["category"],
                            imageURL: snapshot.data[index]["adImage"],

                            onTapFunction: () => Get.to(DetailPage(
                                  post: snapshot.data[index],
                                )));
                      }),
</code>```

This is my method that fetches data from DB:

```<code>Future getData() async {
    QuerySnapshot _firebaseDb = await FirebaseFirestore.instance
        .collection("items")
        .where("status", isEqualTo: true)
        .orderBy("postTime", descending: true)
        .get();

    return _firebaseDb.docs;
  }
</code>```

答: The databaseController has a method call update(),so you can call databaseController.update() when you need to update your data.

Body:
I am using GetX and FutureBuilder to build a list of Cards from my DB.
Lets say I have 10 products in DB then 10 cards are shown. When I add one more product, the Cards on the HomeScreen aren't updated and I have to Navigate in and Out of page to show the 11th product.

How can I force the update i.e. probably make a "Refresh" button that may load the latest data.

PS: I do not want to use STREAM-BUILDER as I don't wish to listen to all changes actively but only when needed. I also cannot use SetState() as I am using GetX hence no StatefulWidget.

Here is my Card class:

FutureBuilder(
                future: databaseController.getData()
                builder: (context, snapshot) {
                   return StaggeredGridView.countBuilder(
                      itemCount: snapshot.data.length,
                      crossAxisCount: 2,
                      itemBuilder: (BuildContext context, int index) =>
                          GetX<FindDeviceLocation>(builder: (controller) {
                        return CreateTheCard(
                            lindex: index,
                            location: snapshot.data[index]["location"],
                            summary: snapshot.data[index]["summary"],
                            description: snapshot.data[index]["description"],
                            category: snapshot.data[index]["category"],
                            imageURL: snapshot.data[index]["adImage"],

                            onTapFunction: () => Get.to(DetailPage(
                                  post: snapshot.data[index],
                                )));
                      }),

This is my method that fetches data from DB:

Future getData() async {
    QuerySnapshot _firebaseDb = await FirebaseFirestore.instance
        .collection("items")
        .where("status", isEqualTo: true)
        .orderBy("postTime", descending: true)
        .get();

    return _firebaseDb.docs;
  }


问:
LdapConnection SearchRequest throwing object does not exist error - revisited
I have the same question as in LdapConnection SearchRequest throwing object does not exist error. The answer over there doesn't seem to work for me.

Whenever these two lines of code are executed (Winforms app, C#)...

```<code>var request = new SearchRequest(DN, "(objectClass=*)", SearchScope.Subtree, null);
var response = (SearchResponse)LdapConnection.SendRequest(request);
</code>```

...and DN points to an existing distinguished name, everything works fine.
If DN does not point to an existing distinguished name, I get an "Object does not exist" error instead of a valid SearchResponse object with .Entries.Count == 0.
I cannot change the filter parameter, this has to be "(objectClass=*)" (in case that would make any difference; it is different the Stackoverflow post that I refer to).

Anyone any ideas?

答:
That's expected behaviour.

The DN you're providing is the search root: the location in the directory to start the search. If that is invalid, then it can't perform the search, which is why you get an exception.

That is different than a case where the search is successfully performed, but no results are found.

If you can't verify ahead of time if the DN exists, then just catch that exception.

Body:
I have the same question as in LdapConnection SearchRequest throwing object does not exist error. The answer over there doesn't seem to work for me.

Whenever these two lines of code are executed (Winforms app, C#)...

var request = new SearchRequest(DN, "(objectClass=*)", SearchScope.Subtree, null);
var response = (SearchResponse)LdapConnection.SendRequest(request);

...and DN points to an existing distinguished name, everything works fine.
If DN does not point to an existing distinguished name, I get an "Object does not exist" error instead of a valid SearchResponse object with .Entries.Count == 0.
I cannot change the filter parameter, this has to be "(objectClass=*)" (in case that would make any difference; it is different the Stackoverflow post that I refer to).

Anyone any ideas?


问:
Multi-targetted Library (monoandroid, xamarinios) issue with System.ComponentModel.DataAnnotations
I'm converting a (working) .netstandard library project into a multi-targetted project that will target:

<targetframeworks>netstandard2.1;xamarinios10;monoandroid10.0;monoandroid12.0;</targetframeworks>

I'm having issues with the System.ComponentModel.DataAnnotations reference.  Sepcifically I get this error (for eveything except the .netstandard target):

The type 'DataType' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.ComponentModel.DataAnnotations, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

After a bit of searching I tried adding the System.ComponentModel.Annotations (4.7.0) nuget package.  This gave the same error.

In the nuget directory for this I noticed that where the .dll would normally live it had a file '.' - I didn't know if that was important (.nuget\packages\system.componentmodel.annotations\4.7.0\ref\MonoAndroid10) - the .netstandard dll was there as expected.

I've also noticed that (a separate) Xamarin.Android project seems to use the System.ComponentModel.DataAnnotations.dll which lives in C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\Xamarin.iOS\v1.0

I'm not sure if the right version of Mono.Android (or ios equivalant) is being targetted or I have to specify a specific assembly version, or whether I'm down the wrong track completely?

Thanks in advance,
Paul.

答: As the comment above mentions, to workaround this issue, I moved the bit of offending code (that used the System.ComponentModel.DataAnnotations) into a seperate project that targetted .netstandard2.1 and then referenced this project from my multi-targetted project.</p>


问:
How to count total receipts by date
Would like to know why do I keep getting the error message?

Created query with SQL Server Management Studio, my output to display correctly has parameters, and I have tried the following with my query.

What I really would like is to have a specific start and end dates and change selected dates with any other combination of MinDate, MaxDate as follows:

```<code>@MinDate DATE = '2020-01-01',
@MaxDate DATE = '2020-02-01';
</code>```

Totals:

```<code>COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
SUM(Receipt_Amount) AS 'Total_Amount'
</code>```

This is the error I get:

Msg 102, Level 15, State 1, Line 5

Incorrect syntax near '.'.

Msg 8158, Level 16, State 1, Line 5

'Receipt_Date' has more columns than were specified in the column list.

Query:

```<code>DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(day) AS
(
    SELECT,
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        receipts AS r
    WHERE
        CAST(DATEADD(day, 1, day) AS Date) < @MaxDate
)
SELECT *
FROM receipts AS r
</code>```

答:
Based on your requirements, you can approach the solution by using a recursive CTE to help generate the list of dates which fall between a MinDate and MaxDate.

```<code>DECLARE @MinDate DATE = '2020-01-01', @MaxDate DATE = '2020-02-01';

;WITH Receipts_CTE(receipt_date) AS
(
    SELECT @MinDate
    UNION ALL
    SELECT DATEADD(DAY, 1, receipt_date)
    FROM Receipts_CTE
    WHERE receipt_date < @MaxDate
)
</code>```

This will recursively call itself to add 1 day to the running receipt_date column until it reaches the specified MaxDate.

With this CTE building out all the necessary dates, you can then use the dates from this CTE to JOIN against your source table to build out the necessary aggregate.

Without knowing the schema of the receipts table in question, the below is merely used for illustration purposes:

```<code>SELECT receipts.Receipt_Date,
       COUNT(receipts.Receipt_ID) AS TotalReceipts,
       SUM(receipts.Receipt_Amount) AS TotalAmount
FROM Receipts receipts
INNER JOIN Reciepts_CTE cte ON cte.receipt_date = receipts.Receipt_Date
GROUP BY receipts.Receipt_Date
</code>```

Title: How to count total receipts by date

Body:
Would like to know why do I keep getting the error message?

Created query with SQL Server Management Studio, my output to display correctly has parameters, and I have tried the following with my query.

What I really would like is to have a specific start and end dates and change selected dates with any other combination of MinDate, MaxDate as follows:

@MinDate DATE = '2020-01-01',
@MaxDate DATE = '2020-02-01';

Totals:

COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
SUM(Receipt_Amount) AS 'Total_Amount'

This is the error I get:

Msg 102, Level 15, State 1, Line 5

Incorrect syntax near '.'.

Msg 8158, Level 16, State 1, Line 5

'Receipt_Date' has more columns than were specified in the column list.

Query:

DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(day) AS
(
    SELECT,
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        receipts AS r
    WHERE
        CAST(DATEADD(day, 1, day) AS Date) < @MaxDate
)
SELECT *
FROM receipts AS r

Body:
Based on your requirements, you can approach the solution by using a recursive CTE to help generate the list of dates which fall between a MinDate and MaxDate.

DECLARE @MinDate DATE = '2020-01-01', @MaxDate DATE = '2020-02-01';

;WITH Receipts_CTE(receipt_date) AS
(
    SELECT @MinDate
    UNION ALL
    SELECT DATEADD(DAY, 1, receipt_date)
    FROM Receipts_CTE
    WHERE receipt_date < @MaxDate
)

This will recursively call itself to add 1 day to the running receipt_date column until it reaches the specified MaxDate.

With this CTE building out all the necessary dates, you can then use the dates from this CTE to JOIN against your source table to build out the necessary aggregate.

Without knowing the schema of the receipts table in question, the below is merely used for illustration purposes:

SELECT receipts.Receipt_Date,
       COUNT(receipts.Receipt_ID) AS TotalReceipts,
       SUM(receipts.Receipt_Amount) AS TotalAmount
FROM Receipts receipts
INNER JOIN Reciepts_CTE cte ON cte.receipt_date = receipts.Receipt_Date
GROUP BY receipts.Receipt_Date


问:
How to select next word after certain phrase? - Redshift SQL
Suppose I have a field with text that resembles:

```<code>{random text here} ABC DEF {my_variable_length_keyword} {random text here}
</code>```

What's the simplest way to select {my_variable_length_keyword}?

I've tried something like:

```<code>select
substring(my_field, charindex('ABC DEF', my_field) + len('ABC DEF'),
        len(my_field) - (charindex('ABC DEF', my_field) + len('ABC DEF')))
from my_table
</code>```

Any help would be amazing.

答:
Use substring with a regular expression.

select substring(my_field from 'ABC DEF ([a-zA-Z]+)') from my_table;
```
<p>Here is an illustration.</p>
<pre class="lang-sql prettyprint-override"><code>select substring
(
  '{random text here} ABC DEF MyVarLenKwd {random text here}'
  from 'ABC DEF ([a-zA-Z]+)'
);

-- Result: MyVarLenKwd
</code>```

Body:
Suppose I have a field with text that resembles:

{random text here} ABC DEF {my_variable_length_keyword} {random text here}

What's the simplest way to select {my_variable_length_keyword}?

I've tried something like:

select
substring(my_field, charindex('ABC DEF', my_field) + len('ABC DEF'),
        len(my_field) - (charindex('ABC DEF', my_field) + len('ABC DEF')))
from my_table

Any help would be amazing.

Body:
Use substring with a regular expression.

select substring(my_field from 'ABC DEF ([a-zA-Z]+)') from my_table;

Here is an illustration.

select substring
(
  '{random text here} ABC DEF MyVarLenKwd {random text here}'
  from 'ABC DEF ([a-zA-Z]+)'
);

-- Result: MyVarLenKwd


问:
Weird result of using recursion to concat array in javascript
I want to use recursion to build list to array function but the expected result is reversed to real solution. How could I improve the function of listToArray(list)

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return [list.value].concat(listToArray(list.rest));
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]```

答:
The simplest solution is to concat the other way around, so replace

```<code>[list.value].concat(listToArray(list.rest));
</code>```

with

```<code>(listToArray(list.rest)).concat([list.value]);
</code>```

See the snippet below

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return (listToArray(list.rest)).concat([list.value]);
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]```

Body:
The simplest solution is to concat the other way around, so replace

[list.value].concat(listToArray(list.rest));

with

(listToArray(list.rest)).concat([list.value]);

See the snippet below

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return (listToArray(list.rest)).concat([list.value]);
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]


问:
I want to select all the records of current page only
I am using igx-grid. When I am clicking on select all using rowSelection, it selecting all the records present in grid, not of current page. I want to enable something by which when I click on select all of igx-grid checkbox, it should select only current page record, not all. Is there any way to do the same? Because I am trying it from last 3 days but not getting any solution. Thanks in Advance!!!

答:
You can use this.grid.deselectRows([1,2,5]) as @Toxy said but as arguments you can use the property dataView of IgxGridComponent that is an array of only row data displayed in the grid.

```<code>onRowSelectionChange(event) {
    this.grid.selectRows(this.grid.dataView.map(x => x.id), true);
    this.currentSelection = this.grid.selectedRows;
}
</code>```

This not have problem with filters because dataView change when filters are applied. Now in this.currentSelection there are only the page id data. Only little problem is that, graphical, the row data of other pages appears selected (despite they are not presente in this.grid.selectedRows); I resolved this issue using (pageChange)="onPageChange($event)" and when page changes this.grid.deselectAllRows(false); false argument let you to deselect all rows in the grid regardless of filters.

Body:
You can use this.grid.deselectRows([1,2,5]) as @Toxy said but as arguments you can use the property dataView of IgxGridComponent that is an array of only row data displayed in the grid.

onRowSelectionChange(event) {
    this.grid.selectRows(this.grid.dataView.map(x => x.id), true);
    this.currentSelection = this.grid.selectedRows;
}

This not have problem with filters because dataView change when filters are applied. Now in this.currentSelection there are only the page id data. Only little problem is that, graphical, the row data of other pages appears selected (despite they are not presente in this.grid.selectedRows); I resolved this issue using (pageChange)="onPageChange($event)" and when page changes this.grid.deselectAllRows(false); false argument let you to deselect all rows in the grid regardless of filters.


问:
Write clojure macro
I want to program a macro in clojure. The macro is called like this (FORI from to task) e.g. (FORI 1 10 (println i)) and should print the numbers from 1 to 10. So far i have

```<code>(defmacro FORI [from to task]
  `(let [i# (range ~from ~to)]
     ~task))
</code>```

I don´t know how do get the list i# into the (print i).

Thanks for help.

答:
You can use any symbol in hygienic forms if you unquote their quoted form:

(defmacro fori [from to task]
  `(doseq [~'i (range ~from ~to)]
      ~task))
```

So here in the expanded form, symbol i will be substituted without change.

Note, using fixed symbols in macros is usually not a good practice, because now i will shadow other vars with the same name.

Title: Write clojure macro

Body:
I want to program a macro in clojure. The macro is called like this (FORI from to task) e.g. (FORI 1 10 (println i)) and should print the numbers from 1 to 10. So far i have

(defmacro FORI [from to task]
  `(let [i# (range ~from ~to)]
     ~task))

I don´t know how do get the list i# into the (print i).

Thanks for help.

Body:
You can use any symbol in hygienic forms if you unquote their quoted form:

(defmacro fori [from to task]
  `(doseq [~'i (range ~from ~to)]
      ~task))

So here in the expanded form, symbol i will be substituted without change.

Note, using fixed symbols in macros is usually not a good practice, because now i will shadow other vars with the same name.


问:
Json data stored in a string type column, how to interact with it
I have a column of type String where json data is stored, I am not able to interact with this column.

```<code>    id                          active  indicators
0   617f27ad9df9b10b633d5850    True    [{'_id': '617abc32fe562a3281b4448d', 'column': 'created_at', 'indicatorId': '61088233be3a2e04a2d3d8f8', 'value': '00-00-00', 'key': '****'}, {'_id': '617abc32fe562a4441b2268e', 'column': 'hash', 'indicatorId': '61088233be3a2e04a2d3d8fc', 'value': '14fsdfsd44*', 'key': '****'}
</code>```

The column types

```<code>df_raw_nps.dtypes
id                               string
active                           boolean
indicators                       string
dtype: object
</code>```

I'm trying to access to create new columns according to the values of the fields "column" and "value" of this json.

```<code>d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])

TypeError: string indices must be integers
</code>```

The result was to be like this:

```<code>    id                          active  created_at  hash
0   617f27ad9df9b10b633d5850    True    00-00-00    14fsdfsd44*
</code>```

Does anyone know what I'm doing wrong? I've tried to convert the column to a json object but without success.

答:
As you have shown that the columns contains a string (which BTW is not a valid Json because it uses simple quotes...), you must literal_eval it:

```<code>d2 = pd.DataFrame([{n['column']:n['value'] for n in ast.literal_eval(i)}
                   for i in df['indicators']], index = df.index)
</code>```

From there you have just to horizontaly concat it:

```<code>pd.concat((df.drop(columns='indicators'), d2), axis = 1).to_string()
</code>```

to get as expected:

```<code>                         id  active created_at         hash
0  617f27ad9df9b10b633d5850    True   00-00-00  14fsdfsd44*
</code>```

Body:
I have a column of type String where json data is stored, I am not able to interact with this column.

    id                          active  indicators
0   617f27ad9df9b10b633d5850    True    [{'_id': '617abc32fe562a3281b4448d', 'column': 'created_at', 'indicatorId': '61088233be3a2e04a2d3d8f8', 'value': '00-00-00', 'key': '****'}, {'_id': '617abc32fe562a4441b2268e', 'column': 'hash', 'indicatorId': '61088233be3a2e04a2d3d8fc', 'value': '14fsdfsd44*', 'key': '****'}

The column types

df_raw_nps.dtypes
id                               string
active                           boolean
indicators                       string
dtype: object

I'm trying to access to create new columns according to the values of the fields "column" and "value" of this json.

d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 d2 = pd.DataFrame([{n['column']:n['value'] for n in i}for i in df['indicators']])

TypeError: string indices must be integers

The result was to be like this:

    id                          active  created_at  hash
0   617f27ad9df9b10b633d5850    True    00-00-00    14fsdfsd44*

Does anyone know what I'm doing wrong? I've tried to convert the column to a json object but without success.

Body:
As you have shown that the columns contains a string (which BTW is not a valid Json because it uses simple quotes...), you must literal_eval it:

d2 = pd.DataFrame([{n['column']:n['value'] for n in ast.literal_eval(i)}
                   for i in df['indicators']], index = df.index)

From there you have just to horizontaly concat it:

pd.concat((df.drop(columns='indicators'), d2), axis = 1).to_string()

to get as expected:

                         id  active created_at         hash
0  617f27ad9df9b10b633d5850    True   00-00-00  14fsdfsd44*


问:
Color selector with 12 predefined colors
How to insert in a HTML/Bootstrap form a color picker or color selector with 12 predefined colors ,
Thank you</p>

答:
You can create simple color picker with predefined colors in few steps:

Create list with colors: datalist id="colors";

Attach list to input type="color" by setting list="colors";

(Optional) Customize colorpicker, see style section of Code Snippet.

Note that datalist for input[type=color] only accepts the hex color
values (ex. "#ff0000") and values such as "#f00" or "red" won’t work.

See Code Snippet:

.colorpicker-wrapper {
  display: flex;
  align-items: center;
  column-gap: .5rem;
}

.colorpicker {
  padding: 0;
  border: none;
  width: 1.5rem;
  height: 1.5rem;
}

.colorpicker::-webkit-color-swatch-wrapper {
  padding: 0;
}

.colorpicker::-webkit-color-swatch {
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Define list of color options -->
<datalist id="colors">
  <option value="#e66465">
  <option value="#ffffff">
  <option value="#000000">
  <option value="#c5c500">
  <option value="#c54100">
  <option value="#c50000">
  <option value="#729901">
  <option value="#01995b">
  <option value="#015999">
  <option value="#012f99">
  <option value="#3d0566">
  <option value="#7b0199">
</datalist>

<!-- attach options to color picker 'list="colors"' -->
<div class="colorpicker-wrapper">
  <input type="color" id="head" class="colorpicker" name="head" value="#e66465" list="colors">
  <label for="head">Check color</label>
</div></code>```

For more details you can take a look at this article

It will show you how to use colorpicker without libraries.

Body:
You can create simple color picker with predefined colors in few steps:

Create list with colors: datalist id="colors";

Attach list to input type="color" by setting list="colors";

(Optional) Customize colorpicker, see style section of Code Snippet.

Note that datalist for input[type=color] only accepts the hex color
values (ex. "#ff0000") and values such as "#f00" or "red" won’t work.

See Code Snippet:

.colorpicker-wrapper {
  display: flex;
  align-items: center;
  column-gap: .5rem;
}

.colorpicker {
  padding: 0;
  border: none;
  width: 1.5rem;
  height: 1.5rem;
}

.colorpicker::-webkit-color-swatch-wrapper {
  padding: 0;
}

.colorpicker::-webkit-color-swatch {
  border: none;
}

<!-- Define list of color options -->
<datalist id="colors">
  <option value="#e66465">
  <option value="#ffffff">
  <option value="#000000">
  <option value="#c5c500">
  <option value="#c54100">
  <option value="#c50000">
  <option value="#729901">
  <option value="#01995b">
  <option value="#015999">
  <option value="#012f99">
  <option value="#3d0566">
  <option value="#7b0199">
</datalist>

<!-- attach options to color picker 'list="colors"' -->
<div class="colorpicker-wrapper">
  <input type="color" id="head" class="colorpicker" name="head" value="#e66465" list="colors">
  <label for="head">Check color</label>
</div>

For more details you can take a look at this article

It will show you how to use colorpicker without libraries.


问:
smtplib sometimes can't send a string variable from sqlite concatenated to a string literal
I am trying to send a message in Python with smtplib.  I have a sendEmail(message) function:

```<code>def sendEmail(message)
    server = smtplib.SMTP_SSL('mailserver.example.com', 465)
    server.ehlo()
    server.login("username", "password")
    print message
    msg = message
    fromaddr = "myaddr@someplace.com"
    toaddr = "theiraddr@someotherplace.com"
    server.sendmail(fromaddr, toaddr, msg)
    server.quit()
</code>```

I am trying to do something like this:

```<code>myMessage = "A String Literal" + someString
sendEmail(myMessage)
</code>```

But when I do that I sometimes receive an empty email message.  someString is a unicode string pulled from sqlite.  I have tried various string concatenations combining literals with literals, sqlite strings with sqlite strings, sqlite strings with literals, each by themselves.  I have used + and .join and anything else I can think of to join the strings.  It seems like everything works sometimes but nothing works every time.

The "print message" inside sendEmail function always prints the string I expect.  smtplib always sends the email message to the correct email address without complaining, it is just sometimes an empty message.

Since I have had everything work and also not work, I don't really trust any solution I come up with if I don't fully understand what is going on.  Can anybody help me understand what is happening with these strings so I can construct my message in the most appropriate way and be confident that my application will work reliably?

Here is a more detailed example of what I am trying to do:

```<code>#connect to the database
dbconn = sqlite3.connect(config["database"])
dbconn.row_factory = sqlite3.Row
dbc = dbconn.cursor()

while true:
    #step 1: Check the things and set alarm status in the alarms table
    #this step reads from and writes to the database

    #step 2: Check each alarm and send a message if necessary
    dbc.execute('SELECT * FROM alarms')
    theAlarms = dbc.fetchall()

    for theAlarm in theAlarms:
        if bool(theAlarm['alertShouldBeSent'):
            sendEmail('ALARM!!: ' + theAlarm['message'])
            dbc.execute('UPDATE alarms SET alertShouldBeSent=0 WHERE id=?',(theAlarm['id']),)
        elif bool(theAlarm['allClearShouldBeSent']):
            sendEmail('NORMAL: ' + theAlarm['message'])
            dbc.execute('UPDATE alarms SET allClearShouldBeSent=0 WHERE id=?',(theAlarm['id'],))

    dbconn.commit()
</code>```

Each row in the alarm table defines a condition that should trigger an alarm and has a field that indicates whether the alarm condition is met making the alarm active

theAlarm['message'] from the database is something like "The batteries are on fire" or "Somebody left the door open." There are currently only 4 or 5 rows in the alarms table.  The logic that determines theAlarm['alertShouldBeSent'] makes sure an alert is only sent once per alarm condition and won't be continuously sent if the alarm doesn't first reset. The same is true for theAlarm['allClearShouldBeSent'].  The loop runs continuously but emails are sent infrequently.  In testing, I set one row into an alarm state. I can verify that the code to send the email is triggered when it should be.

答:
Had the same problem as you, so I went googling and I found your post. As I was reading I realised it must be the damn parser smtplib is using. It doesn't know how to parse ":".

There may be other characters it can't parse, but I haven't found any.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send a message in Python with smtplib.  I have a sendEmail(message) function:

def sendEmail(message)
    server = smtplib.SMTP_SSL('mailserver.example.com', 465)
    server.ehlo()
    server.login("username", "password")
    print message
    msg = message
    fromaddr = "myaddr@someplace.com"
    toaddr = "theiraddr@someotherplace.com"
    server.sendmail(fromaddr, toaddr, msg)
    server.quit()

I am trying to do something like this:

myMessage = "A String Literal" + someString
sendEmail(myMessage)

But when I do that I sometimes receive an empty email message.  someString is a unicode string pulled from sqlite.  I have tried various string concatenations combining literals with literals, sqlite strings with sqlite strings, sqlite strings with literals, each by themselves.  I have used + and .join and anything else I can think of to join the strings.  It seems like everything works sometimes but nothing works every time.

The "print message" inside sendEmail function always prints the string I expect.  smtplib always sends the email message to the correct email address without complaining, it is just sometimes an empty message.

Since I have had everything work and also not work, I don't really trust any solution I come up with if I don't fully understand what is going on.  Can anybody help me understand what is happening with these strings so I can construct my message in the most appropriate way and be confident that my application will work reliably?

Here is a more detailed example of what I am trying to do:

#connect to the database
dbconn = sqlite3.connect(config["database"])
dbconn.row_factory = sqlite3.Row
dbc = dbconn.cursor()

while true:
    #step 1: Check the things and set alarm status in the alarms table
    #this step reads from and writes to the database

    #step 2: Check each alarm and send a message if necessary
    dbc.execute('SELECT * FROM alarms')
    theAlarms = dbc.fetchall()

    for theAlarm in theAlarms:
        if bool(theAlarm['alertShouldBeSent'):
            sendEmail('ALARM!!: ' + theAlarm['message'])
            dbc.execute('UPDATE alarms SET alertShouldBeSent=0 WHERE id=?',(theAlarm['id']),)
        elif bool(theAlarm['allClearShouldBeSent']):
            sendEmail('NORMAL: ' + theAlarm['message'])
            dbc.execute('UPDATE alarms SET allClearShouldBeSent=0 WHERE id=?',(theAlarm['id'],))

    dbconn.commit()

Each row in the alarm table defines a condition that should trigger an alarm and has a field that indicates whether the alarm condition is met making the alarm active

theAlarm['message'] from the database is something like "The batteries are on fire" or "Somebody left the door open." There are currently only 4 or 5 rows in the alarms table.  The logic that determines theAlarm['alertShouldBeSent'] makes sure an alert is only sent once per alarm condition and won't be continuously sent if the alarm doesn't first reset. The same is true for theAlarm['allClearShouldBeSent'].  The loop runs continuously but emails are sent infrequently.  In testing, I set one row into an alarm state. I can verify that the code to send the email is triggered when it should be.


问:
How to iterate through all keys of json node
I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes

The code I'm using is :

```<code>    Dim streamData As Stream = Nothing
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"

        Dim t As Task(Of Stream) = http.GetStreamAsync(url)
        streamData = t.Result
    End Using

    Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
    Dim jsonData As JsonNode = jsonResponse("result")

    Dim c As String = String.Empty

    For Each jsonCurrency As JsonNode In jsonData.AsObject
        c += jsonCurrency("last").ToString + " "
    Next
</code>```

but I get the error:

Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode

What Am I doing wrong?
Thanks

答:
I solved using</p>
```<code> Dim result As JsonObject = jsonResponse("result").AsObject

 For Each kvp In result.AsEnumerable
     c &= kvp.Value("last").ToString & ", "
 Next
</code>```

Body:
I'm trying to scrap the key values from this website API and it seems the json format it's not an array.
I'm working with console .Net core 6.0 using System.Text.Json.Nodes

The code I'm using is :

    Dim streamData As Stream = Nothing
    Using http As HttpClient = New HttpClient
        Dim url As String = "https://api.hotbit.io/api/v1/market.status24h"

        Dim t As Task(Of Stream) = http.GetStreamAsync(url)
        streamData = t.Result
    End Using

    Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
    Dim jsonData As JsonNode = jsonResponse("result")

    Dim c As String = String.Empty

    For Each jsonCurrency As JsonNode In jsonData.AsObject
        c += jsonCurrency("last").ToString + " "
    Next

but I get the error:

Cannot convert type 'KeyValuePair(Of String, JsonNode)' in JsonNode

What Am I doing wrong?
Thanks

Body:
I solved using

 Dim result As JsonObject = jsonResponse("result").AsObject

 For Each kvp In result.AsEnumerable
     c &= kvp.Value("last").ToString & ", "
 Next


问:
Non suspend function is not executed after suspend function
I have a suspend function userRepo.updateUserWithNewPersonalDetails(details) and after executing this function I want to execute success() function which is a call back.

but the issue is success() is not getting executed.

any suggestions on how to get this to work.

this sequence does not work

```<code>  SUCCESS -> {
                        progress.postValue(GONE)
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                        success() // NOT EXECUTED
                    }
</code>```

if I change it to call success() first then save to repo, it works fine. but this is not the right way of doing it I think.

could you suggest please

```<code>  SUCCESS -> {
                        progress.postValue(GONE)
                        success() // EXECUTED
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                    }
</code>```

Fragment call

```<code>viewModel.save(personalDetails) { activity?.onBackPressed() }
</code>```

ViewModel

```<code>fun save(details: PersonalDetails, success: () -> Unit) {
    viewModelScope.launch {
        userRepo.savePersonalDetails(details).collect {
            when (it.status) {
                LOADING -> {
                    progress.postValue(VISIBLE)
                }
                SUCCESS -> {
                    progress.postValue(GONE)
                    userRepo.updateUserWithNewPersonalDetails(details)
                    success() // THIS IS NOT EXECUTED
                }
                ERROR -> {
                    progress.postValue(GONE)
                    error.postValue(ErrorResult(errorCode = SNACKBAR_ID_USER_DETAILS_SAVE_FAIL))
                }
            }
        }
    }
}
</code>```

userRepository

```<code>suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        userDao.get().collect { cachedUser ->
            val updatedCachedUser = UserDB(cachedUser.id, etc..)
            userDao.save(updatedCachedUser)
        }
    }
</code>```

答: Can you please show me the function that you call?, did you already use the breakpoint to make sure the function it self was called?. cause if you dont, i think you might use nullable variable and the value will retrieved after the suspend function (userRepo.blabla()) finished, if yes. maybe you can call .invokeOnCompletion { /your Success Function/ success() }

Body:
I have a suspend function userRepo.updateUserWithNewPersonalDetails(details) and after executing this function I want to execute success() function which is a call back.

but the issue is success() is not getting executed.

any suggestions on how to get this to work.

this sequence does not work

  SUCCESS -> {
                        progress.postValue(GONE)
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                        success() // NOT EXECUTED
                    }

if I change it to call success() first then save to repo, it works fine. but this is not the right way of doing it I think.

could you suggest please

  SUCCESS -> {
                        progress.postValue(GONE)
                        success() // EXECUTED
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                    }

Fragment call

viewModel.save(personalDetails) { activity?.onBackPressed() }

ViewModel

fun save(details: PersonalDetails, success: () -> Unit) {
    viewModelScope.launch {
        userRepo.savePersonalDetails(details).collect {
            when (it.status) {
                LOADING -> {
                    progress.postValue(VISIBLE)
                }
                SUCCESS -> {
                    progress.postValue(GONE)
                    userRepo.updateUserWithNewPersonalDetails(details)
                    success() // THIS IS NOT EXECUTED
                }
                ERROR -> {
                    progress.postValue(GONE)
                    error.postValue(ErrorResult(errorCode = SNACKBAR_ID_USER_DETAILS_SAVE_FAIL))
                }
            }
        }
    }
}

userRepository

suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        userDao.get().collect { cachedUser ->
            val updatedCachedUser = UserDB(cachedUser.id, etc..)
            userDao.save(updatedCachedUser)
        }
    }


问:
HTTP status code for an expired confirmation code
I have an endpoint in my REST API that sends a code the user received per email to verify the email address.

What status code should I better use to return that this code has expired?

Is it 401, 410 or 498?

答:
HTTP status codes are metadata of the transfer of documents over a network domain.  They are a token that instructs general purpose HTTP clients how to interpret the response (especially the other meta data fields).

When considering an unassigned status code (like 498), you want to keep in mind that general purpose components that don't recognize the code are going to treat the response as though it had the x00 response code of the same class (so 498 --> 400, 298 --> 200, and so on).

That said, if your expected context includes clients that do understand the semantics of 498, then this is less of a concern.

I have an endpoint in my REST API that sends a code the user received per email to verify the email address.

What status code should I better use to return that this code has expired?

You can make a good case for either 200 or 410, I think.

In either case, the important thing to the client is going to be the representation in the payload, which is going to be some kind of "so sorry" message and maybe hypermedia controls to restart the process.

The 410 response is primarily intended to assist the task of web  maintenance by notifying the recipient that the resource is intentionally unavailable and that the server owners desire that remote links to that resource be removed.

So that could be a reasonable choice, given that you don't particularly want this URI to be reused


问:
Save authenticated users to database coming from Azure AD
I am working on a simple web app for learning purposes using Angular for the frontend and Java Spring for the backend. I don't have a particular problem that I want you guys to help me out with, instead I have a question about OAuth2 authentication.

I have registered my Angular SPA in Azure AD (Authorization Code Flow + PKCE), I set up roles and everything is working okay. My question is what do I do when authenticated users ping my backend? My backend has no information about the users.

I thought of a solution to make a web filter, and every time an authenticated user pings any endpoint requiring the user to be authenticated, to check the database if the user exists (through the username), and save him if he does not exist. I'm pretty sure this will work, but I don't think this is the best solution, considering my web filter will have to read from the databases for every single HTTP request that comes in, and write to the database occasionally (if the user logs in for the first time).

I shouldn't be worried about performance issues because I'm building this strictly for learning purposes, but nevertheless I want to do this the right way. I tried googling this in multiple ways, but I guess I'm not using the right keywords to find what I'm looking for. Any opinion or advice would be much appreciated! Thanks!

EDIT: I followed this article to achieve the OAuth2 + OIDC authentication and authorization, my security config in the backend is the same: https://ordina-jworks.github.io/security/2020/08/18/Securing-Applications-Azure-AD.html

答:
Post the discussion with clarity on the requirements. If you want to use have the following:

Accept an Azure AD logged in user to consumer your web service

You would want to check if the user exists in your application database with minimal network latency.

With the requirement of not always hitting your Database, one option is to use a cache.

The ideal solution for this cache to work is:

Ensure the cache is checked for every HTTP Request using Web Filter

Make sure the cache is always updated with the latest users being logged in via Azure AD

Example:

Implement a CacheService.java

```<code>package com.example.springboot;

import java.util.Collections;

import org.apache.catalina.User;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class CacheService {

  @Bean
  public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("users")));
    return cacheManager;
  }

  @Cacheable(cacheNames = "users")
  public User getUser(String username) {
    // Code below will not execute after the first calling for the given username.
    // So if one username is already cached, it would not invoke for the same user again from the DB.

    // Get or Create a new user based on the Database call
    return null;
  }
}
</code>```

Then implement a web filter like:

```<code>package com.example.springboot;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Component
public class CredentialsInjectionFilter extends GenericFilterBean {

  @Autowired
  private CacheService cacheService;

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {

    cacheService.getUser("my_username");

    filterChain.doFilter(servletRequest, servletResponse);
  }
}
</code>```

More on Caching with Springboot: https://www.javadevjournal.com/spring/spring-caching/

Body:
Post the discussion with clarity on the requirements. If you want to use have the following:

Accept an Azure AD logged in user to consumer your web service

You would want to check if the user exists in your application database with minimal network latency.

With the requirement of not always hitting your Database, one option is to use a cache.

The ideal solution for this cache to work is:

Ensure the cache is checked for every HTTP Request using Web Filter

Make sure the cache is always updated with the latest users being logged in via Azure AD

Example:

Implement a CacheService.java

package com.example.springboot;

import java.util.Collections;

import org.apache.catalina.User;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class CacheService {

  @Bean
  public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("users")));
    return cacheManager;
  }

  @Cacheable(cacheNames = "users")
  public User getUser(String username) {
    // Code below will not execute after the first calling for the given username.
    // So if one username is already cached, it would not invoke for the same user again from the DB.

    // Get or Create a new user based on the Database call
    return null;
  }
}

Then implement a web filter like:

package com.example.springboot;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Component
public class CredentialsInjectionFilter extends GenericFilterBean {

  @Autowired
  private CacheService cacheService;

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {

    cacheService.getUser("my_username");

    filterChain.doFilter(servletRequest, servletResponse);
  }
}

More on Caching with Springboot: https://www.javadevjournal.com/spring/spring-caching/


问:
DBD::SQLite Placeholder for integer value in HAVING clause
Since similar statements using DBD::mysql seem to work fine, where is my mistake in using a placeholder for an integer in a HAVING clause, when using DBD::SQLite as DBI driver?

#!/usr/bin/perl

use 5.012;
use warnings;

use DBI;

my $dbh = DBI->connect("dbi:SQLite:dbname=/tmp/test.sqlite","","", {
    RaiseError => 1,
    sqlite_allow_multiple_statements => 1,
});

$dbh->do( <<'EOT' );
CREATE TABLE cd (
    id    INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT
);

CREATE TABLE artist (
    id   INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    cd   INTEGER,
    FOREIGN KEY (cd) REFERENCES cd (id)
);

INSERT INTO cd (title) VALUES ('foo');
INSERT INTO cd (title) VALUES ('bar');

INSERT INTO artist (name, cd) VALUES ('max fob', 1);
INSERT INTO artist (name, cd) VALUES ('max baz', 1);
EOT

my $sth1 = $dbh->prepare(<<'EOT');
   SELECT cd.title
     FROM cd
LEFT JOIN artist ON artist.cd = cd.id
    WHERE artist.name LIKE ?
 GROUP BY cd.title
   HAVING count( artist.cd ) = 2
EOT

my $sth2 = $dbh->prepare(<<'EOT');
   SELECT cd.title
     FROM cd
LEFT JOIN artist ON artist.cd = cd.id
    WHERE artist.name LIKE ?
 GROUP BY cd.title
   HAVING count( artist.cd ) = ?
EOT

$sth1->execute('max%');
# says 'hit'
say 'sth1: hit' if $sth1->fetch;

$sth2->execute('max%', 2);
# stays silent
say 'sth2: hit' if $sth2->fetch;
```

Thank you, DDL.

答:
A ? placeholder is always replaced in the prepared statement by a string (like '2'), which for SQLite has no affinity.

From Datatypes In SQLite/Affinity Of Expressions is derived that an expression like count(artist.cd), although it is documented that it returns an integer, has no affinity.

Also, from Datatypes In SQLite/Type Conversions Prior To Comparison is derived that 2 operands with no affinity are compared without any implicit data type conversion.

For SQLite the expression 2 = '2' returns false.

This is why you must apply data type conversion to the ? placeholder to convert it to a numeric value, which you can do with:

```<code>HAVING count( artist.cd ) = ? + 0
</code>```

Also, not related to your problem, the WHERE clause in your query makes the LEFT join behave like an INNER join, because it is applied to a column of the right table and filters out any non matching rows.

Body:
Since similar statements using DBD::mysql seem to work fine, where is my mistake in using a placeholder for an integer in a HAVING clause, when using DBD::SQLite as DBI driver?

#!/usr/bin/perl

use 5.012;
use warnings;

use DBI;

my $dbh = DBI->connect("dbi:SQLite:dbname=/tmp/test.sqlite","","", {
    RaiseError => 1,
    sqlite_allow_multiple_statements => 1,
});

$dbh->do( <<'EOT' );
CREATE TABLE cd (
    id    INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT
);

CREATE TABLE artist (
    id   INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    cd   INTEGER,
    FOREIGN KEY (cd) REFERENCES cd (id)
);

INSERT INTO cd (title) VALUES ('foo');
INSERT INTO cd (title) VALUES ('bar');

INSERT INTO artist (name, cd) VALUES ('max fob', 1);
INSERT INTO artist (name, cd) VALUES ('max baz', 1);
EOT

my $sth1 = $dbh->prepare(<<'EOT');
   SELECT cd.title
     FROM cd
LEFT JOIN artist ON artist.cd = cd.id
    WHERE artist.name LIKE ?
 GROUP BY cd.title
   HAVING count( artist.cd ) = 2
EOT

my $sth2 = $dbh->prepare(<<'EOT');
   SELECT cd.title
     FROM cd
LEFT JOIN artist ON artist.cd = cd.id
    WHERE artist.name LIKE ?
 GROUP BY cd.title
   HAVING count( artist.cd ) = ?
EOT

$sth1->execute('max%');
# says 'hit'
say 'sth1: hit' if $sth1->fetch;

$sth2->execute('max%', 2);
# stays silent
say 'sth2: hit' if $sth2->fetch;

Thank you, DDL.

Body:
A ? placeholder is always replaced in the prepared statement by a string (like '2'), which for SQLite has no affinity.

From Datatypes In SQLite/Affinity Of Expressions is derived that an expression like count(artist.cd), although it is documented that it returns an integer, has no affinity.

Also, from Datatypes In SQLite/Type Conversions Prior To Comparison is derived that 2 operands with no affinity are compared without any implicit data type conversion.

For SQLite the expression 2 = '2' returns false.

This is why you must apply data type conversion to the ? placeholder to convert it to a numeric value, which you can do with:

HAVING count( artist.cd ) = ? + 0

Also, not related to your problem, the WHERE clause in your query makes the LEFT join behave like an INNER join, because it is applied to a column of the right table and filters out any non matching rows.


问:
What's an example of Ruby code that's "too clever"?
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?</p>

答:
```<code>class Tree
  def initialize*d;@d,=d;end
  def to_s;@l||@r?"<#{@d},<#{@l}>,<#{@r}>>":@d;end
  def total;(@d.is_a?(Numeric)?@d:0)+(@l?@l.total: 0)+(@r?@r.total: 0);end
  def insert d
    alias g instance_variable_get
    p=lambda{|s,o|d.to_s.send(o,@d.to_s)&&
      (g(s).nil??instance_variable_set(s,Tree.new(d)):g(s).insert(d))}
    @d?p[:@l,:<]||p[:@r,:>]:@d=d
  end
end
</code>```

OwnerDisplayName: amsterdam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: amsterdam


问:
Difference between object reference declaration and object construction?
Consider a class named Calculator with the following code:

```<code>class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}
</code>```

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?

答:
Calculator calculator;- its the definition of the variable calculator.. you tell the compiler that it can hold variable of type Calculator and nothing else. and it has null now and nothing is assigned..

Calculator calculator = new Calculator();--this actually stores reference to Calculatore object created in heap to calculator variable. and now it stores a variable which is called initialisation.

Body:
Consider a class named Calculator with the following code:

class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?


问:
Divide integers with floor, ceil and outwards rounding modes in C++
Recently, I saw this question which asks how you can divide integers with ceil rounding (towards positive infinity). Unfortunately the answers either don't work for signed integers or have problems with underflows and overflows.

For instance, the accepted answer has this solution:

q = 1 + ((x - 1) / y);
```

When x is zero, there is an underflow to ~0 and the result is incorrect.

How can you implement ceil rounding correctly for signed and unsigned integers and how do you implement other rounding modes like floor (towards negative infinity) and outwards (away from zero)?

答:
I would simplify and use homogeneous argument type and let the users to make explicit type casts for heterogeneous inputs, if necessary. This way possible under- and overflows are moved outside these functions. Of course normal UB cases apply, eg. divide by zero and std::numeric_limits<T>::min() divided by -1  for signed T.</p>
```<code>#include <type_traits>

//Division round up, aka take the ceiling, aka round toward positive infinity, eg. -1.5 -> -1, 1.5 -> 2
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndUp(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b + (a % b != 0);
    else
        return a / b + (a % b != 0 && ((a < 0) == (b < 0)));
}

//Division round down, aka take the floor, aka round toward negative infinity, eg. -1.5 -> -2, 1.5 -> 1
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndDwn(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b;
    else
        return a / b - (a % b != 0 && ((a < 0) != (b < 0)));
}

//Division round out, aka round out away from zero, aka round toward infinity, eg. -1.5 -> -2, 1.5 -> 2
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndOut(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b + (a % b != 0);
    else
        return a / b + (a % b != 0 && ((a < 0) == (b < 0))) - (a % b != 0 && ((a < 0) != (b < 0)));
}

//Division round in, aka truncate, aka round in toward zero, aka round away from infinity, eg. -1.5 -> -1, 1.5 -> 1
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndIn(T a, T b) noexcept
{
    return a / b;
}
</code>```

Body:
Recently, I saw this question which asks how you can divide integers with ceil rounding (towards positive infinity). Unfortunately the answers either don't work for signed integers or have problems with underflows and overflows.

For instance, the accepted answer has this solution:

q = 1 + ((x - 1) / y);

When x is zero, there is an underflow to ~0 and the result is incorrect.

How can you implement ceil rounding correctly for signed and unsigned integers and how do you implement other rounding modes like floor (towards negative infinity) and outwards (away from zero)?

Body:
I would simplify and use homogeneous argument type and let the users to make explicit type casts for heterogeneous inputs, if necessary. This way possible under- and overflows are moved outside these functions. Of course normal UB cases apply, eg. divide by zero and std::numeric_limits<T>::min() divided by -1  for signed T.

#include <type_traits>

//Division round up, aka take the ceiling, aka round toward positive infinity, eg. -1.5 -> -1, 1.5 -> 2
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndUp(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b + (a % b != 0);
    else
        return a / b + (a % b != 0 && ((a < 0) == (b < 0)));
}

//Division round down, aka take the floor, aka round toward negative infinity, eg. -1.5 -> -2, 1.5 -> 1
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndDwn(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b;
    else
        return a / b - (a % b != 0 && ((a < 0) != (b < 0)));
}

//Division round out, aka round out away from zero, aka round toward infinity, eg. -1.5 -> -2, 1.5 -> 2
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndOut(T a, T b) noexcept
{
    if constexpr (std::is_unsigned_v<T>)
        return a / b + (a % b != 0);
    else
        return a / b + (a % b != 0 && ((a < 0) == (b < 0))) - (a % b != 0 && ((a < 0) != (b < 0)));
}

//Division round in, aka truncate, aka round in toward zero, aka round away from infinity, eg. -1.5 -> -1, 1.5 -> 1
template<typename T>
    requires std::is_integral_v<T>
constexpr T divRndIn(T a, T b) noexcept
{
    return a / b;
}


问:
I'm keep getting an error that says the column of the range is too small
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

```<code>var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```
```<code>const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```

But it works here

```<code>    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }

</code>```

答: If you are using Visual Studio Code try to reopen the Program because it happened to me to so its kinda of a glitch.</p>

Body:
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

var cellCup = ss.getRange(ctCup, 0).activate().getValue();

const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();

But it works here

    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }


问:
'React' must be in scope when using JSX react/react-in-jsx-scope
I am new in MERN Stack. I am following my prof's session videos in this project but suddenly I come across this error while she doesn't have any issues on her side.
I also tried to use the methods I found as I was searching but it still won't work.
This is my very first time in asking here, I don't know if any of you will reach me out soon but I'm just hoping.
Anyway, here's my snippet of codes.

This is the product.js

ProductScreen

App.js

HomeScreen

P.S. I already did two says that suggested here also in stackoverflow. The first one is to capitalize the React when you import it like this

import React from 'react';

The other one is to modify the rules in .eslintrc.json

```<code>    "react/jsx-uses-react": "off",
    "react/react-in-jsx-scope": "off"
</code>```

答: have you tried to add import React from 'react' on top of ALL your components (ProductScreen, App, Homescreen, and every other component) ?

Body:
I am new in MERN Stack. I am following my prof's session videos in this project but suddenly I come across this error while she doesn't have any issues on her side.
I also tried to use the methods I found as I was searching but it still won't work.
This is my very first time in asking here, I don't know if any of you will reach me out soon but I'm just hoping.
Anyway, here's my snippet of codes.

This is the product.js

ProductScreen

App.js

HomeScreen

P.S. I already did two says that suggested here also in stackoverflow. The first one is to capitalize the React when you import it like this

import React from 'react';

The other one is to modify the rules in .eslintrc.json

    "react/jsx-uses-react": "off",
    "react/react-in-jsx-scope": "off"


问:
Python Pandas: How to find element in a column with a matching string object of other column
I have this string object:

```<code>code = '1002'
</code>```

And i also have the following Pandas Data Frame:

```<code>pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})
</code>```

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

Body:
I have this string object:

code = '1002'

And i also have the following Pandas Data Frame:

pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

What i need is to match the code i hace as a stirng with the column 'Code' and get the element in the same row from the column 'Place'.

Body:
Try:

df = pd.DataFrame({'Code':['1001','1002','1003','1004'],
              'Place':['Chile','Peru','Colombia','Argentina']})

code = '1002'
df.loc[df['Code'] == code, 'Place'].iloc[0]

Peru

Or

df[df['Code'] == code]['Place']


问:
how to fix Error: export 'ɵsupportsWebAnimations'
im trying to replicate this component:

stackblitz.com/edit/angular-material-star-rating?file=package.json

however, on my project im unable to run it due to the following errors:

```<code>./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:9-31 - Error: export 'ɵsupportsWebAnimations' (imported as 'ɵsupportsWebAnimations') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:69-88 - Error: export 'ɵCssKeyframesDriver' (imported as 'ɵCssKeyframesDriver') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)
</code>```

i have already did the

```<code>npm install --save @angular/material @angular/cdk @angular/animations --force
</code>```

答:
If you already had a package.json file in your project all you needed to do is run:

npm i to install all the declared dependencies on the project

npm run serve to serve your Angular application.

I can also see that project is quite old (Angular 5, we're currently on Angular 13) so perhaps you'll need to migrate some code to the current version you're using

Body:
im trying to replicate this component:

stackblitz.com/edit/angular-material-star-rating?file=package.json

however, on my project im unable to run it due to the following errors:

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:9-31 - Error: export 'ɵsupportsWebAnimations' (imported as 'ɵsupportsWebAnimations') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

./node_modules/@angular/platform-browser/fesm2015/animations.mjs:533:69-88 - Error: export 'ɵCssKeyframesDriver' (imported as 'ɵCssKeyframesDriver') was not found in '@angular/animations/browser' (possible exports: AnimationDriver, ɵAnimation, ɵAnimationEngine, ɵAnimationStyleNormalizer, ɵNoopAnimationDriver, ɵNoopAnimationStyleNormalizer, ɵWebAnimationsDriver, ɵWebAnimationsPlayer, ɵWebAnimationsStyleNormalizer, ɵallowPreviousPlayerStylesMerge, ɵcontainsElement, ɵinvokeQuery, ɵvalidateStyleProperty)

i have already did the

npm install --save @angular/material @angular/cdk @angular/animations --force


问:
How do you plot density curves on top of the data to show distribution in R
I am looking to plot the density curves within the distribution of my data. I have heard (not not expert) on something called lognormal distribution?
My data is the following:

```<code>data<- data.frame(
      Day=c(1,2,3,4,5,6,7,8,9,10),
      Variable=c(3,5,20,10,8,18,23,21,16,12))

ggplot(data)  +
  geom_bar(aes(y=Variable, x=Day),stat="identity", colour="black")+
  labs(title= "",x="",y=expression('Variable'))+  theme_classic()
</code>```

And would like something like this:

答:
I think you're getting a bit confused between a bar chart and a histogram. You have a bar chart, which in your case is showing the change in one variable on the y axis against time on the x axis.

A histogram looks like a bar chart, but it shows the distribution of a single variable throughout its range. This has the value of the variable on the x axis, and the frequency with which that variable was found on the y axis. It makes sense to plot a density curve over a histogram, but not over a time series. If you are looking for a similar visual effect to the plot shown, the best you can get is probably to plot a moving average along with the bars, perhaps something like this:

ggplot(data, aes(Day, Variable))  +
  geom_col(colour = "black") +
  geom_smooth(se = FALSE, color = "black") +
  labs(title = "", x = "", y = expression('Variable')) +
  theme_classic()
```

Body:
I am looking to plot the density curves within the distribution of my data. I have heard (not not expert) on something called lognormal distribution?
My data is the following:

data<- data.frame(
      Day=c(1,2,3,4,5,6,7,8,9,10),
      Variable=c(3,5,20,10,8,18,23,21,16,12))

ggplot(data)  +
  geom_bar(aes(y=Variable, x=Day),stat="identity", colour="black")+
  labs(title= "",x="",y=expression('Variable'))+  theme_classic()

And would like something like this:


问:
Please how can i position my navbar fixed and transform scale function working
When position of my navbar fixed with class top, my transform property scale doesn't work on my div element I applied. The only way the hover effect on the box works is when I remove the position on the navbar.

My html:

Lower Usuma Dam

Home

About

Services

Photos

```
<p>CSS styles:</p>
<pre class="lang-css prettyprint-override"><code>.box-1:hover,
.box-2:hover,
.box-3:hover,
.box-4:hover {
    transform: scale(1.1);
    transition: 0.9s;
}

.top {
    /* position: fixed;
    left: 0;
    top: 0;
    z-index: 1; */
    display: flex;
    justify-content: space-between;
    align-content: center;
    width: 100%;
    height: 100%;
    line-height: 4em;
}
</code>```

答:
The transition is used on main div not in hover css.
I have created an example. I hope, it will help you. You can ask me for any doubt.

.box-common{width: 50px;height: 50px;background: #fff;border: 3px solid #000;margin: 10px;display: inline-block; transition: all 0.9s ease-in-out;}
.box-1:hover,
.box-2:hover,
.box-3:hover,
.box-4:hover {
    transform: scale(1.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-common box-1"></div>
<div class="box-common box-2"></div>
<div class="box-common box-3"></div>
<div class="box-common box-4"></div></code>```

Body:
When position of my navbar fixed with class top, my transform property scale doesn't work on my div element I applied. The only way the hover effect on the box works is when I remove the position on the navbar.

My html:

Lower Usuma Dam

Home

About

Services

Photos

CSS styles:

.box-1:hover,
.box-2:hover,
.box-3:hover,
.box-4:hover {
    transform: scale(1.1);
    transition: 0.9s;
}

.top {
    /* position: fixed;
    left: 0;
    top: 0;
    z-index: 1; */
    display: flex;
    justify-content: space-between;
    align-content: center;
    width: 100%;
    height: 100%;
    line-height: 4em;
}

Body:
The transition is used on main div not in hover css.
I have created an example. I hope, it will help you. You can ask me for any doubt.

.box-common{width: 50px;height: 50px;background: #fff;border: 3px solid #000;margin: 10px;display: inline-block; transition: all 0.9s ease-in-out;}
.box-1:hover,
.box-2:hover,
.box-3:hover,
.box-4:hover {
    transform: scale(1.5);
}

<div class="box-common box-1"></div>
<div class="box-common box-2"></div>
<div class="box-common box-3"></div>
<div class="box-common box-4"></div>