问:
Issue with html tag alignment
I am new to html,css and unable to figure out how to align like,comment span element to the bottom left of the parent div and share bottom to the bottom right. and make the p element in the middle of the parent div. I have attached the css and html code. please help

React Code

```<code> render() {
        return (
            <div className="container-fluid">
                <div className="row justify-content-center">
                    <div className="post-holder shadow-sm p-3 mb-5 bg-white rounded">
                        <h4>I am a data scientist and yes, you did r</h4>
                        <div className='m-2'>
                        <span className="username ">@username</span>
                        <span className="postdate float-right">1 Day ago</span>
                        </div>

                        <p className="align-self-center">
                        But the truth is that data scientists typically “spend 1–2 hours a week looking for a new job” as stated in this article by the Financial Times. Furthermore, the article also states that “Machine learning specialists topped its list of deve
                        </p>
                        <div className ="post-actions">
                        <span className="fa fa-heart fa-lg post-like"> 299</span>
                        <span className="fa fa-comment fa-lg post-comment"> 299</span>
                        <span className="fa fa-share fa-lg post-share"> 299</span>
                        </div>

                    </div>

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

css code

```<code>body {
  background-color: #fdfdfd;
}

.post-holder {
  width: 400px;
  height: 400px;
  margin: 0px 10px;
  position: relative;
}
.username {
  font-size: 16px;
  color: #899bb4;
}

.post-actions {
  position: absolute;
  bottom: 2rem;
}

.post-share {
  right: 2rem;
}
</code>```

答:
You can enclose both the like and comment spans inside one
 and share span in another div and provide float:right to the latter div.

```<code>   <div className="post-actions">
    <div>
      <span className="fa fa-heart fa-lg post-like"> 299</span>
      <span className="fa fa-comment fa-lg post-comment"> 299</span>
    </div>
    <div style={{ "float": "right" }}>
       <span className="fa fa-share fa-lg post-share"> 299</span>
    </div>
   </div>
</code>```

To keep the
 at the center use a certain width and margin:"0 auto" .

```<code> <p className="align-self-center" style={{width:"50%",margin:"0 auto"}}>
   But the truth is that data scientists typically “spend 1–2 hours a week looking for a new job” as stated in this article by the Financial Times. Furthermore, the article also states that “Machine learning specialists topped its list of deve
 </p>
</code>```

Title: Issue with html tag alignment

Body:
I am new to html,css and unable to figure out how to align like,comment span element to the bottom left of the parent div and share bottom to the bottom right. and make the p element in the middle of the parent div. I have attached the css and html code. please help

React Code

 render() {
        return (

I am a data scientist and yes, you did r

                        @username
                        1 Day ago

                        But the truth is that data scientists typically “spend 1–2 hours a week looking for a new job” as stated in this article by the Financial Times. Furthermore, the article also states that “Machine learning specialists topped its list of deve

                         299
                         299
                         299

        );
    }

css code

body {
  background-color: #fdfdfd;
}

.post-holder {
  width: 400px;
  height: 400px;
  margin: 0px 10px;
  position: relative;
}
.username {
  font-size: 16px;
  color: #899bb4;
}

.post-actions {
  position: absolute;
  bottom: 2rem;
}

.post-share {
  right: 2rem;
}

Body:
You can enclose both the like and comment spans inside one <div> and share span in another div and provide float:right to the latter div.

   <div className="post-actions">
    <div>
      <span className="fa fa-heart fa-lg post-like"> 299</span>
      <span className="fa fa-comment fa-lg post-comment"> 299</span>
    </div>
    <div style={{ "float": "right" }}>
       <span className="fa fa-share fa-lg post-share"> 299</span>
    </div>
   </div>

To keep the <p> at the center use a certain width and margin:"0 auto" .

 <p className="align-self-center" style={{width:"50%",margin:"0 auto"}}>
   But the truth is that data scientists typically “spend 1–2 hours a week looking for a new job” as stated in this article by the Financial Times. Furthermore, the article also states that “Machine learning specialists topped its list of deve
 </p>


来源: stackexchange

问:
How do i write a script that keeps reloading and making requests to an endpoint until a specific item is added
Im trying to write a script that continuously makes requests to an endpoint  until a certain item im looking for is added to the list located at that endpoint  . So far I have made a promise that , when resolved, returns that item - which is what im hoping happens. However, if it doesnt and the promise is rejected, i need to be able to  rerun the script . How would i do this? Is it a recursive thing ?  Can anyone help? </p>

```<code>const search = (color)=>{

     let promise = new Promise(function(resolve, reject) {

         const info = (products) => {
                    let arr = []
                     products.map( p => {
                            if (p.color == `${color}`){
                            arr.push(p)

                            }
                         })
                      arr.length > 0?  resolve(arr[0]):reject("failed")

                }

///api call makes a request that returns all items in the "hats" section
        const getProducts =  api.getItems("hats", info)

       promise.then(
        res => console.log(res),
        rej=> console.log(rej)
        )
}

async function trySearch(color)  {
   while (true) {
      try {
         return  await search(color);
      } catch (err) {

        await new Promise(resolve => setTimeout(resolve, 500));
      }

   }
}

trySearch('Gold')

</code>```

答:
You can easily keep your function as is and reject it with some legitimate error. Then it's easy to extract a retry method on top of this one</p>

```<code>const trySearch = async color => {
   while (true) {
      try {
        return await search(color);
      } catch (err) {
        //wait for 0.5s before another attempt, or your computer will cook
        await new Promise(resolve => setTimeout(resolve, 500));
      }
   }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying to write a script that continuously makes requests to an endpoint  until a certain item im looking for is added to the list located at that endpoint  . So far I have made a promise that , when resolved, returns that item - which is what im hoping happens. However, if it doesnt and the promise is rejected, i need to be able to  rerun the script . How would i do this? Is it a recursive thing ?  Can anyone help?

const search = (color)=>{

     let promise = new Promise(function(resolve, reject) {

         const info = (products) => {
                    let arr = []
                     products.map( p => {
                            if (p.color == `${color}`){
                            arr.push(p)

                            }
                         })
                      arr.length > 0?  resolve(arr[0]):reject("failed")

                }

///api call makes a request that returns all items in the "hats" section
        const getProducts =  api.getItems("hats", info)

       promise.then(
        res => console.log(res),
        rej=> console.log(rej)
        )
}

async function trySearch(color)  {
   while (true) {
      try {
         return  await search(color);
      } catch (err) {

        await new Promise(resolve => setTimeout(resolve, 500));
      }

   }
}

trySearch('Gold')

Body:
You can easily keep your function as is and reject it with some legitimate error. Then it's easy to extract a retry method on top of this one

const trySearch = async color => {
   while (true) {
      try {
        return await search(color);
      } catch (err) {
        //wait for 0.5s before another attempt, or your computer will cook
        await new Promise(resolve => setTimeout(resolve, 500));
      }
   }
};


问:
Color of captions becames fgcolor (knitr, Rnw)
When using knitr with Rnw files, color of the font of captions created inside a chunk becames fgcolor.

This problem is similar to knitr kable: Text color in PDF from RNW is grey. This solution is not useful in this case.

Is there any way to solve this problem? Hacking knit_hooks$set(plot = myfunction)? How to?
Thank you.

```<code>% Minimal.Rnw
\documentclass{tufte-book}
\begin{document}
Color of normal font is black.
<<fig.env='marginfigure',fig.cap="The color of the font of the caption is fgcolor">>=
plot(1:10)
@
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}
</code>```

EDIT I:

I publish a working solution for future reference. Benoit pointed out the key tick fig.show='hide'. Unfortunately, it does not write the figure environment. So I create a new hook called colorcaption, that solves this problem. Call this option with your desired color (black, red, green,...).

```<code>% Minimal.Rnw
\documentclass{tufte-book}
\begin{document}
<<echo=FALSE>>=
library(knitr)
knit_hooks$set(colorcaption = function(before, options, envir){
    ## Hacked from hook_plot_custom
    if (before) return() # run hook after the chunk
    ext = "pdf" #  original: options$fig.ext %n% dev2ext(options$dev)
    hook = knit_hooks$get('plot')
    ##
    n = options$fig.num
    if (n == 0L) n = options$fig.num = 1L # make sure fig.num is at least 1
    res = unlist(lapply(seq_len(n), function(i) {
        options$fig.cur = i
        hook(fig_path(ext, options, i), knitr:::reduce_plot_opts(options))
    }), use.names = FALSE)
    res <- paste(res, collapse = '')
    ## My hack. Put the color after the end of kframe
    sub("\\end{kframe}",paste0("\\end{kframe}\\color{",options$colorcaption, "}"),res,fixed=TRUE)
})
@
Color of normal font is black.
<<colorcaption='red',fig.show='hide',fig.env='marginfigure',fig.cap="The color of the font of the caption is colorcaption",>>=
1:10
plot(1:10)
10:1
@
Hello
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}
</code>```

答:
This should do what you want, provided that the plots produced by your R code chunks are stored in a figure folder:

```<code>\documentclass{tufte-book}
\begin{document}
Color of normal font is black.
<<test1, fig.show = 'hide'>>=
plot(1:10)
@

\begin{marginfigure}
\includegraphics[width = \textwidth]{figure/test1-1}
\caption{this is now the correct color}
\end{marginfigure}

\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}
</code>```

Or you could (re)define fgcolor in your preamble:

```<code>\documentclass{tufte-book}
\definecolor{fgcolor}{RGB}{0,0,0}
\begin{document}
Color of normal font is black.
<<fig.env='marginfigure',fig.cap="The color of the font of the caption is fgcolor">>=
plot(1:10)
@
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}
</code>```

Body:
When using knitr with Rnw files, color of the font of captions created inside a chunk becames fgcolor.

This problem is similar to knitr kable: Text color in PDF from RNW is grey. This solution is not useful in this case.

Is there any way to solve this problem? Hacking knit_hooks$set(plot = myfunction)? How to?
Thank you.

% Minimal.Rnw
\documentclass{tufte-book}
\begin{document}
Color of normal font is black.
<<fig.env='marginfigure',fig.cap="The color of the font of the caption is fgcolor">>=
plot(1:10)
@
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}

EDIT I:

I publish a working solution for future reference. Benoit pointed out the key tick fig.show='hide'. Unfortunately, it does not write the figure environment. So I create a new hook called colorcaption, that solves this problem. Call this option with your desired color (black, red, green,...).

% Minimal.Rnw
\documentclass{tufte-book}
\begin{document}
<<echo=FALSE>>=
library(knitr)
knit_hooks$set(colorcaption = function(before, options, envir){
    ## Hacked from hook_plot_custom
    if (before) return() # run hook after the chunk
    ext = "pdf" #  original: options$fig.ext %n% dev2ext(options$dev)
    hook = knit_hooks$get('plot')
    ##
    n = options$fig.num
    if (n == 0L) n = options$fig.num = 1L # make sure fig.num is at least 1
    res = unlist(lapply(seq_len(n), function(i) {
        options$fig.cur = i
        hook(fig_path(ext, options, i), knitr:::reduce_plot_opts(options))
    }), use.names = FALSE)
    res <- paste(res, collapse = '')
    ## My hack. Put the color after the end of kframe
    sub("\\end{kframe}",paste0("\\end{kframe}\\color{",options$colorcaption, "}"),res,fixed=TRUE)
})
@
Color of normal font is black.
<<colorcaption='red',fig.show='hide',fig.env='marginfigure',fig.cap="The color of the font of the caption is colorcaption",>>=
1:10
plot(1:10)
10:1
@
Hello
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}

Body:
This should do what you want, provided that the plots produced by your R code chunks are stored in a figure folder:

\documentclass{tufte-book}
\begin{document}
Color of normal font is black.
<<test1, fig.show = 'hide'>>=
plot(1:10)
@

\begin{marginfigure}
\includegraphics[width = \textwidth]{figure/test1-1}
\caption{this is now the correct color}
\end{marginfigure}

\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}

Or you could (re)define fgcolor in your preamble:

\documentclass{tufte-book}
\definecolor{fgcolor}{RGB}{0,0,0}
\begin{document}
Color of normal font is black.
<<fig.env='marginfigure',fig.cap="The color of the font of the caption is fgcolor">>=
plot(1:10)
@
\begin{marginfigure}
    \caption{This color is black.}
\end{marginfigure}
\end{document}


问:
Spring boot @Valid on requestBody in controller method not working
I am trying to validate a simple request body annotated by @Valid annotation in a @RestController annotated by @Validated. Validations are working correctly on primitive variable in request (on age in below example) but not working on pojo request body. @Valid annotation has no effect on request body Person class (i.e. controller accepting blank name and age under 18).

Person class:

```<code>import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank

class Person (

    @NotBlank
    val name : String,

    @Min(18)
    val age : Int
)
</code>```

Controller class:

```<code>import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.validation.Valid

@RestController
@Validated
class HomeController {

    @GetMapping("/{age}")
    fun verifyAge(@PathVariable("age") @Min(18) age:Int): String {
        return "Eligible age."
    }

    @PostMapping
    fun personValidation(@Valid @RequestBody person : Person) : String {
        return "No validation error"
    }
}
</code>```

@NotBlank, @Min and @Valid annotations came from below dependency:

```<code>    implementation("org.springframework.boot:spring-boot-starter-validation:2.3.0.RELEASE")
</code>```

How to make @Valid working on Person request body in a @Validated controller?

答:
Don't mark Person as a Spring @Component.

Correct way to achieve field validation is to add @field to your properties.
Example code:

```<code>class SomeRequest(
    @field:NotBlank val name: String
)
</code>```

This happens because Spring Boot needs this annotations to be applied on fields. Kotlin by default applied them to constructor parameter. See Annotation use-site targets on Kotlin documentation.

Body:
I am trying to validate a simple request body annotated by @Valid annotation in a @RestController annotated by @Validated. Validations are working correctly on primitive variable in request (on age in below example) but not working on pojo request body. @Valid annotation has no effect on request body Person class (i.e. controller accepting blank name and age under 18).

Person class:

import javax.validation.constraints.Min
import javax.validation.constraints.NotBlank

class Person (

    @NotBlank
    val name : String,

    @Min(18)
    val age : Int
)

Controller class:

import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.validation.Valid

@RestController
@Validated
class HomeController {

    @GetMapping("/{age}")
    fun verifyAge(@PathVariable("age") @Min(18) age:Int): String {
        return "Eligible age."
    }

    @PostMapping
    fun personValidation(@Valid @RequestBody person : Person) : String {
        return "No validation error"
    }
}

@NotBlank, @Min and @Valid annotations came from below dependency:

    implementation("org.springframework.boot:spring-boot-starter-validation:2.3.0.RELEASE")

How to make @Valid working on Person request body in a @Validated controller?

Body:
Don't mark Person as a Spring @Component.

Correct way to achieve field validation is to add @field to your properties.
Example code:

class SomeRequest(
    @field:NotBlank val name: String
)

This happens because Spring Boot needs this annotations to be applied on fields. Kotlin by default applied them to constructor parameter. See Annotation use-site targets on Kotlin documentation.


问:
Error occuredjava.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
I trying make connection between Mysql  and my java program

My system configuration is:

Windows :10

64 bit

java version: 1.8

jar file: mysql-connector-java-8.0.19

My source code:
DatabaseConnectivity.java

```<code>package test;
import java.sql.*;
public class DatabaseConnectivity
{
    Connection conn;
    Connection getConnection(String database,String userName,String password)
    {

        try{
        String url;
        url="jdbc:mysql://localhost:8080/"+database;
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection  conn=DriverManager.getConnection(url,userName,password);
        System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println("Error occured"+e);
        }
        return conn;
    }
    public DatabaseConnectivity()
    {

    }

}
</code>```

Test.java

```<code>package test;
import java.sql.*;
import test.*;
class Test
{
    public static void main(String args[])
    {
        try
        {
            DatabaseConnectivity db=new DatabaseConnectivity();
            Connection conn=db.getConnection("records","root","dics");
            System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println(" Error occured"+e);
        }
    }//End of main method
}//End of class Test
</code>```

I have set my classpath as

```<code>>set classpath
classpath="E:\softwares\java\jar files\mysql-connector-java-8.0.19.jar;";
</code>```

I tried to run my code

```<code>javac DatabaseConnectivity.java
javac -classpath e:\user\java\jdbc\ Test.java
java -classpath e:\user\java\jdbc\ test.Test
</code>```

It throws error

```<code>Error occuredjava.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Connected to database successfully
</code>```

答:
There were few problems.

The problem was when I set classpath by environment variables. And pass -classpath variable it overrides the default classpath environment variable.

So add jar file path to classpath option passed with java.exe

Class.forName() is not used anymore in mysql(mysql-connector-java-8.0.19). I
don't know why?

Source code:

E:\user\java\jdbc\test\DatabaseConnectivity.java

```<code>package test;
import java.sql.*;
public class DatabaseConnectivity
{
    Connection conn;
    Connection getConnection(String database,String userName,String password)
    {

        try{
        String url;
        url="jdbc:mysql://localhost:3306/"+database;
        //Class.forName("com.mysql.jdbc.Driver");
        //Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection(url,userName,password);
        System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println("In Class DatabaseConnectivity Error occured"+e);
        }
        return conn;
    }
    public DatabaseConnectivity()
    {

    }
    public static void main(String args[])
    {

    }

}
</code>```

E:\user\java\jdbc\test\Test.java

```<code>package test;
import java.sql.*;
import test.*;
class Test
{
    public static void main(String args[])
    {
        try
        {
            DatabaseConnectivity db=new DatabaseConnectivity();
            Connection conn=db.getConnection("test","root","dics");
            Statement st = conn.createStatement();
            String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";
            st.executeUpdate(table);
            System.out.println("Table creation process successfully!");

        }
        catch(Exception e)
        {
            System.out.println(" class Test Error occured"+e);
        }
    }//End of main method
}//End of class Test
</code>```

Third problem, I was using mysql 8+ and my jar file version was 5+. Your mysql version and jar file version should be same. Now, It is 8 as you can see in the classpath.

Check the port number of mysql

Login to mysql -u root -p

mysql>show variables where variable_name="port";

It was 3306. As you can see in my question I was usnig default port number which is 8080. I must have changed it while mysql installation because some other application was already running on 8080(probably tomcat or wamp server).

To execute

```<code>E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; DatabaseConnectivity.java

E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; Test.java

E:\user\java\jdbc\test>java -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; test.Test
</code>```

Connected to database successfully
Table creation process successfully!

Body:
I trying make connection between Mysql  and my java program

My system configuration is:

Windows :10

64 bit

java version: 1.8

jar file: mysql-connector-java-8.0.19

My source code:
DatabaseConnectivity.java

package test;
import java.sql.*;
public class DatabaseConnectivity
{
    Connection conn;
    Connection getConnection(String database,String userName,String password)
    {

        try{
        String url;
        url="jdbc:mysql://localhost:8080/"+database;
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection  conn=DriverManager.getConnection(url,userName,password);
        System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println("Error occured"+e);
        }
        return conn;
    }
    public DatabaseConnectivity()
    {

    }

}

Test.java

package test;
import java.sql.*;
import test.*;
class Test
{
    public static void main(String args[])
    {
        try
        {
            DatabaseConnectivity db=new DatabaseConnectivity();
            Connection conn=db.getConnection("records","root","dics");
            System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println(" Error occured"+e);
        }
    }//End of main method
}//End of class Test

I have set my classpath as

>set classpath
classpath="E:\softwares\java\jar files\mysql-connector-java-8.0.19.jar;";

I tried to run my code

javac DatabaseConnectivity.java
javac -classpath e:\user\java\jdbc\ Test.java
java -classpath e:\user\java\jdbc\ test.Test

It throws error

Error occuredjava.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Connected to database successfully

Body:
There were few problems.

The problem was when I set classpath by environment variables. And pass -classpath variable it overrides the default classpath environment variable.

So add jar file path to classpath option passed with java.exe

Class.forName() is not used anymore in mysql(mysql-connector-java-8.0.19). I
don't know why?

Source code:

E:\user\java\jdbc\test\DatabaseConnectivity.java

package test;
import java.sql.*;
public class DatabaseConnectivity
{
    Connection conn;
    Connection getConnection(String database,String userName,String password)
    {

        try{
        String url;
        url="jdbc:mysql://localhost:3306/"+database;
        //Class.forName("com.mysql.jdbc.Driver");
        //Class.forName("com.mysql.cj.jdbc.Driver");
            conn=DriverManager.getConnection(url,userName,password);
        System.out.println("Connected to database successfully");
        }
        catch(Exception e)
        {
            System.out.println("In Class DatabaseConnectivity Error occured"+e);
        }
        return conn;
    }
    public DatabaseConnectivity()
    {

    }
    public static void main(String args[])
    {

    }

}

E:\user\java\jdbc\test\Test.java

package test;
import java.sql.*;
import test.*;
class Test
{
    public static void main(String args[])
    {
        try
        {
            DatabaseConnectivity db=new DatabaseConnectivity();
            Connection conn=db.getConnection("test","root","dics");
            Statement st = conn.createStatement();
            String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))";
            st.executeUpdate(table);
            System.out.println("Table creation process successfully!");

        }
        catch(Exception e)
        {
            System.out.println(" class Test Error occured"+e);
        }
    }//End of main method
}//End of class Test

Third problem, I was using mysql 8+ and my jar file version was 5+. Your mysql version and jar file version should be same. Now, It is 8 as you can see in the classpath.

Check the port number of mysql

Login to mysql -u root -p

mysql>show variables where variable_name="port";

It was 3306. As you can see in my question I was usnig default port number which is 8080. I must have changed it while mysql installation because some other application was already running on 8080(probably tomcat or wamp server).

To execute

E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; DatabaseConnectivity.java

E:\user\java\jdbc\test>javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; Test.java

E:\user\java\jdbc\test>java -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar";e:\user\java\jdbc\; test.Test

Connected to database successfully
Table creation process successfully!


问:
Get the last entered id from a table in sql
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

```<code>SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id
</code>```

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

答:
Update: to get the full row of max id:

```<code>SELECT *
FROM loan
INNER JOIN
  (SELECT max(id) max_id
   FROM loan
   GROUP BY employee_id) x ON x.max_id = loan.id
group by employee_id;
</code>```

I have to mention that your DB table design without primary key isn't well designed: https://i.stack.imgur.com/DTYO8.png

Body:
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

Body:
Update: to get the full row of max id:

SELECT *
FROM loan
INNER JOIN
  (SELECT max(id) max_id
   FROM loan
   GROUP BY employee_id) x ON x.max_id = loan.id
group by employee_id;

I have to mention that your DB table design without primary key isn't well designed: https://i.stack.imgur.com/DTYO8.png


问:
What is the correct error part of the Result type of a function propagating different error types?
I tried to write a function, that shall propagate different error types. Only for example see the following code:

```<code>use std::fs::File;
use std::io;
use std::io::Read;

fn main() {
    let number = read_number_from_file().unwrap();

    println!("Read number {}!", number);
}

// So what is the correct error part of the Result<i32, ...>?
fn read_number_from_file() -> Result<i32, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    let number = s.parse()?;
    Ok(number)
}
</code>```

Compiling it results in the following error unsurprisingly:

error[E0277]: `?` couldn't convert the error to `std::io::Error`
  --> src\main.rs:16:27
   |
16 |     let number = s.parse()?;
   |                           ^ the trait `std::convert::From<std::num::ParseIntError>` is not implemented for `std::io::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following implementations were found:
             <std::io::Error as std::convert::From<std::ffi::NulError>>
             <std::io::Error as std::convert::From<std::io::ErrorKind>>
             <std::io::Error as std::convert::From<std::io::IntoInnerError<W>>>
   = note: required by `std::convert::From::from`
```

So what is the correct Error type of the Result type? Is there an answer not only for this specific case: I have a function with several calls to other functions returning Result<T, E> which in the error case shall be propagated out of the function to the caller but have different Types E?

答:
You should define your own error type, which includes all possible errors that could happen:

```<code>#[derive(Debug)]
enum Error {
    Io(io::Error),
    ParseInt(num::ParseIntError)
}

impl From<io::Error> for Error {
    fn from(other: io::Error) -> Error {
        Error::Io(other)
    }
}

impl From<num::ParseIntError> for Error {
    fn from(other: num::ParseIntError) -> Error {
        Error::ParseInt(other)
    }
}
</code>```

The From conversions allow the ? operator to work as expected.

You can save a lot of typing by using one of the several crates that will generate the boilerplate for you. Some popular ones are thiserror and snafu.

I prefer thiserror because it only adds the implementations that you would otherwise write yourself and, if you are writing a library, it is transparent to your library's users. snafu is arguably more powerful - it generates a lot more code, but is opinionated in what it generates, so you will need to get used to its paradigm in order to take full advantage of it, and the snafu concepts will become part of your library's API.

Using thiserror, the code above is reduced to:

```<code>use thiserror::Error;

#[derive(Debug, Error)]
enum Error {
    #[error("IO Error: {0})]
    Io(#[from] io::Error),
    #[error("ParseInt Error: {0})]
    ParseInt(#[from] num::ParseIntError)
}
</code>```

Note that this is also generating Display implementations, which I didn't include above.

Body:
I tried to write a function, that shall propagate different error types. Only for example see the following code:

use std::fs::File;
use std::io;
use std::io::Read;

fn main() {
    let number = read_number_from_file().unwrap();

    println!("Read number {}!", number);
}

// So what is the correct error part of the Result<i32, ...>?
fn read_number_from_file() -> Result<i32, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    let number = s.parse()?;
    Ok(number)
}

Compiling it results in the following error unsurprisingly:

error[E0277]: `?` couldn't convert the error to `std::io::Error`
  --> src\main.rs:16:27
   |
16 |     let number = s.parse()?;
   |                           ^ the trait `std::convert::From<std::num::ParseIntError>` is not implemented for `std::io::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following implementations were found:
             <std::io::Error as std::convert::From<std::ffi::NulError>>
             <std::io::Error as std::convert::From<std::io::ErrorKind>>
             <std::io::Error as std::convert::From<std::io::IntoInnerError<W>>>
   = note: required by `std::convert::From::from`

So what is the correct Error type of the Result type? Is there an answer not only for this specific case: I have a function with several calls to other functions returning Result<T, E> which in the error case shall be propagated out of the function to the caller but have different Types E?

Body:
You should define your own error type, which includes all possible errors that could happen:

#[derive(Debug)]
enum Error {
    Io(io::Error),
    ParseInt(num::ParseIntError)
}

impl From<io::Error> for Error {
    fn from(other: io::Error) -> Error {
        Error::Io(other)
    }
}

impl From<num::ParseIntError> for Error {
    fn from(other: num::ParseIntError) -> Error {
        Error::ParseInt(other)
    }
}

The From conversions allow the ? operator to work as expected.

You can save a lot of typing by using one of the several crates that will generate the boilerplate for you. Some popular ones are thiserror and snafu.

I prefer thiserror because it only adds the implementations that you would otherwise write yourself and, if you are writing a library, it is transparent to your library's users. snafu is arguably more powerful - it generates a lot more code, but is opinionated in what it generates, so you will need to get used to its paradigm in order to take full advantage of it, and the snafu concepts will become part of your library's API.

Using thiserror, the code above is reduced to:

use thiserror::Error;

#[derive(Debug, Error)]
enum Error {
    #[error("IO Error: {0})]
    Io(#[from] io::Error),
    #[error("ParseInt Error: {0})]
    ParseInt(#[from] num::ParseIntError)
}

Note that this is also generating Display implementations, which I didn't include above.


问:
Refreshing table structures, views, functions and sps from one instance to another instance
I have one PROD server database and STG server database.
I need to refresh the STG server database table structures (No Data), Views, Functions and SPs from the PROD server database.

What is the approach and how can we automate this?

答: You can script it, but your life will be simpler if you just use a good comparison tool. Red-Gate's SQL Compare is excellent and easy to automate. I suggest you check it out.</p>


问:
How to use NSJSONSerialization
I have a JSON string (from PHP's json_encode() that looks like this:

```<code>[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
</code>```

I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys "id" => "1" and "name" => "Aaa".

I do not understand how the NSJSONSerialization stores the data though. Here is my code so far:

```<code>NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
    JSONObjectWithData: data
    options: NSJSONReadingMutableContainers
    error: &e];
</code>```

This is just something I saw as an example on another website. I have been trying to get a read on the JSON object by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS.

How do I use NSJSONSerialization to parse the JSON above, and turn it into the data structure I mentioned?

答:
bad example, should be something like this

```<code>{"id":1, "name":"something as name"}
</code>```

number and string are mixed.

ContentLicense: CC BY-SA 3.0

Title: How to use NSJSONSerialization

Body:
I have a JSON string (from PHP's json_encode() that looks like this:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys "id" => "1" and "name" => "Aaa".

I do not understand how the NSJSONSerialization stores the data though. Here is my code so far:

NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
    JSONObjectWithData: data
    options: NSJSONReadingMutableContainers
    error: &e];

This is just something I saw as an example on another website. I have been trying to get a read on the JSON object by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS.

How do I use NSJSONSerialization to parse the JSON above, and turn it into the data structure I mentioned?

Body:
bad example, should be something like this

{"id":1, "name":"something as name"}

number and string are mixed.


问:
Is it possible to have an effect of flowing flame around a div border
I just happen to recall a graphic effect which I saw many years ago in a Windows Mobile Phone.

It is a list of items, when you select one of them, there will be a flame flowing around the selected item.

I have done a quick research about animation effects in css3 and found some properties which might be useful e.g. keyframes, transition, animation-* etc.

But I still have no idea how to use them together to present that effect.
It will be very cool, if someone could help me out and show me the effect in jsfiddle.

Thank you in advance.

答:
You can use border-image property to scale and clip the images to be your borders and animate them accordingly.
Here's a sample:

body{
  margin:0;
  padding:0;
}
div{
  width:100vw;
  height:100vh;
  display:flex;
  justify-content:center;
  margin:0;
  padding:0;
  align-items:center;
}
p{
  width:50%;
  animation:animate 8s linear forwards;
  padding:10px;

}

@keyframes animate{
  0%{
    border-style: solid;
border-width: 0px 0px 0px;
border-image: url(https://image.shutterstock.com/image-vector/cartoon-fire-flame-frame-borders-260nw-1362735449.jpg) 73 157 73 151 repeat stretch;
  }
  100%{
    border-style: solid;
border-width: 29px 0px 29px 0px;
border-image: url(https://image.shutterstock.com/image-vector/cartoon-fire-flame-frame-borders-260nw-1362735449.jpg) 73 157 73 151 repeat stretch;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis maxime suscipit dolorum porro eius dignissimos commodi quibusdam expedita rerum alias asperiores iste nisi animi modi eligendi quam quia, voluptas earum!</p>
</div>
</body></code>```

Body:
You can use border-image property to scale and clip the images to be your borders and animate them accordingly.
Here's a sample:

body{
  margin:0;
  padding:0;
}
div{
  width:100vw;
  height:100vh;
  display:flex;
  justify-content:center;
  margin:0;
  padding:0;
  align-items:center;
}
p{
  width:50%;
  animation:animate 8s linear forwards;
  padding:10px;

}

@keyframes animate{
  0%{
    border-style: solid;
border-width: 0px 0px 0px;
border-image: url(https://image.shutterstock.com/image-vector/cartoon-fire-flame-frame-borders-260nw-1362735449.jpg) 73 157 73 151 repeat stretch;
  }
  100%{
    border-style: solid;
border-width: 29px 0px 29px 0px;
border-image: url(https://image.shutterstock.com/image-vector/cartoon-fire-flame-frame-borders-260nw-1362735449.jpg) 73 157 73 151 repeat stretch;
  }
}

<body>
<div>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis maxime suscipit dolorum porro eius dignissimos commodi quibusdam expedita rerum alias asperiores iste nisi animi modi eligendi quam quia, voluptas earum!</p>
</div>
</body>


问:
Django inlinemodeladmin extra option not working
I'm in the process of adding a user profile inline to the edit user page on django admin. So far the only problem is no matter what value I put in the "extra" option, the page always displays fields for 1 extra user profile record.
I don't actually want to display any extra records, but I can't get the extra one to go away. Hopefully someone can help, it has me stumped.

Here is the code:

```<code>#admin.py
class UserProfileInline(admin.StackedInline):
    model = auth_user_profiles
    extra = 0
    raw_id_fields = ('organisation_id','advertiser_id','division_id','rtp_id','person_id','hp_organisation_id')
    exclude = ('specialist_id',)

class UserAdmin(admin.ModelAdmin):
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined')
    list_filter = ('is_staff', 'is_superuser', 'is_active')
    search_fields = ('username','email','first_name','last_name')
    inlines = (UserProfileInline,)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)
</code>```

This is the relevant spot in the django docs: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#inlinemodeladmin-options

Thanks!

答:
Ok, I've figured it out now. Bit of a silly mistake really.

I upgraded my django version a while ago, but I forgot to update the django admin media files.

When I checked my apache log, I found a few js erorrs relating to inlines.js and a couple of other files.

Updating my admin js files with the ones from the django 1.3 package solved the problem.

Body:
I'm in the process of adding a user profile inline to the edit user page on django admin. So far the only problem is no matter what value I put in the "extra" option, the page always displays fields for 1 extra user profile record.
I don't actually want to display any extra records, but I can't get the extra one to go away. Hopefully someone can help, it has me stumped.

Here is the code:

#admin.py
class UserProfileInline(admin.StackedInline):
    model = auth_user_profiles
    extra = 0
    raw_id_fields = ('organisation_id','advertiser_id','division_id','rtp_id','person_id','hp_organisation_id')
    exclude = ('specialist_id',)

class UserAdmin(admin.ModelAdmin):
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined')
    list_filter = ('is_staff', 'is_superuser', 'is_active')
    search_fields = ('username','email','first_name','last_name')
    inlines = (UserProfileInline,)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

This is the relevant spot in the django docs: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#inlinemodeladmin-options

Thanks!


问:
MaterialDatePicker calendar numbers are not aligned on the center
Description: Numbers are not aligned on the center

Expected behavior: Numbers should be aligned on the center

Source code:
NOTE: The same behavior occured even before adding any style

```<code><style name="OeamtcThemeOverlay_MaterialCalendar"
    parent="@style/Theme.MaterialComponents.Light.Dialog">
    <item name="android:colorAccent">@color/oeamtc_accent</item>
    <item name="headerLayout">@style/Oeamtc_MaterialCalendar_Header</item>
    <item name="android:colorButtonNormal">@color/oeamtc_accent</item>
    <item name="android:button">@color/oeamtc_accent</item>
    <item name="buttonBarPositiveButtonStyle">@style/ThemeMaterialCalendarButton</item>
    <item name="buttonBarNegativeButtonStyle">@style/ThemeMaterialCalendarButton</item>
    <item name="materialCalendarStyle">@style/Oeamtc_MaterialCalendar</item>
    <item name="materialButtonStyle">@style/ThemeMaterialButton</item>
</style>

<style name="Oeamtc_MaterialCalendar"
    parent="@style/Widget.MaterialComponents.MaterialCalendar">
    <item name="rangeFillColor">@color/oeamtc_accent_transparent_50</item>
    <item name="dayStyle">@style/Oeamtc_CalendarDay</item>
    <item name="dayTodayStyle">@style/Oeamtc_CalendarToday</item>
    <item name="daySelectedStyle">@style/Oeamtc_CalendarSelected</item>
</style>

<style name="ThemeMaterialCalendarButton" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/oeamtc_accent</item>
</style>

<style name="ThemeMaterialButton" parent="Widget.MaterialComponents.Button">
    <item name="android:textColor">@color/white</item>
    <item name="android:backgroundTint">@color/oeamtc_accent</item>
</style>

<style name="Oeamtc_CalendarDay" parent="Test.Widget.MaterialComponents.MaterialCalendar.Day">
    <item name="itemTextColor">@color/black</item>
    <item name="itemFillColor">@color/transparent</item>
    <item name="itemStrokeColor">@color/white</item>
    <item name="itemStrokeWidth">0dp</item>
    <item name="android:gravity">center</item>
    <item name="itemShapeAppearance">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
    <item name="itemShapeAppearanceOverlay">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
</style>

<style name="Oeamtc_CalendarSelected" parent="">
    <item name="itemFillColor">@color/oeamtc_accent</item>
    <item name="itemTextColor">@color/white</item>
    <item name="itemStrokeColor">@color/oeamtc_accent</item>
    <item name="itemStrokeWidth">0dp</item>
    <item name="itemShapeAppearance">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
    <item name="itemShapeAppearanceOverlay">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
</style>

<style name="Oeamtc_CalendarToday" parent="">
    <item name="itemTextColor">@color/black</item>
    <item name="itemStrokeColor">@color/oeamtc_accent</item>
    <item name="itemFillColor">@color/white</item>
    <item name="itemStrokeWidth">3dp</item>
    <item name="itemShapeAppearance">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
    <item name="itemShapeAppearanceOverlay">@style/Test.ShapeAppearanceOverlay.MaterialComponents.MaterialCalendar.Day</item>
</style>`
</code>```

Android API version: 29

Material Library version: 1.1.0

Device: Oneplus 6t and all nexus emulators

答: I found the reason this happened. Apparently the main theme of the app has to inherit Material theme. </p>

Body:
Description: Numbers are not aligned on the center

Expected behavior: Numbers should be aligned on the center

Source code:
NOTE: The same behavior occured even before adding any style

`

Android API version: 29

Material Library version: 1.1.0

Device: Oneplus 6t and all nexus emulators


问:
Error in SQL syntax when running SQL in Java but not in HeidiSQL
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

```<code>Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);
</code>```

I can't figure out why.

答:
I would recommend using the insert ... ok duplicate key syntax here rather than a code block. This is more efficient, and implements the lockout a single statement, which should avoid the problem you meet when running the query from your php code.

```<code>insert into billboards(Name, XML, CreatorName)
values(?, ?, ?)
on duplicate key update set XML = values(XML)
</code>```

For this to work, you need a unique (or primary key) constraint on column Name.

Also, consider using a parameterized  query rather than concatenating variables in your query stringW Escaping is inefficient and does not really make your code safer.

Body:
I'm trying to run an insert or update on a table - the string generated from below works fine when copy pasted into HeidiSQL but throws SQLSyntaxErrorExceptions when run from Java:

Statement statement = con.createStatement();
String escapedXML = EscapeString(billboard.getXml());
String sql = String.format(
    "DELIMITER $ \r\nBEGIN NOT ATOMIC\r\n" +
    "IF EXISTS(SELECT * FROM billboards where Name='%s') THEN UPDATE billboards SET XML='%s' where Name='%s';\r\n" +
    "ELSE insert into billboards(Name, XML, CreatorName) values('%s', '%s', '%s');\r\n" +
    "END IF;\r\n" +
    "END $\r\n" +
    "DELIMITER ;", billboard.getName(), escapedXML, billboard.getName(), billboard.getName(), escapedXML, billboard.getCreatorName());
// Insert or update billboard
statement.execute(sql);

I can't figure out why.

Body:
I would recommend using the insert ... ok duplicate key syntax here rather than a code block. This is more efficient, and implements the lockout a single statement, which should avoid the problem you meet when running the query from your php code.

insert into billboards(Name, XML, CreatorName)
values(?, ?, ?)
on duplicate key update set XML = values(XML)

For this to work, you need a unique (or primary key) constraint on column Name.

Also, consider using a parameterized  query rather than concatenating variables in your query stringW Escaping is inefficient and does not really make your code safer.


问:
Sum all the digits of a number Javascript
I am newbie.

I want to make small app which will calculate the sum of all the digits of a number.

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .

Please help me

答:
The sum of digits can be calculated using that function (based on other answers):

```<code>function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}
</code>```

If you really need to sum the digits recursively there is recursive version of the function:

```<code>function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}
</code>```

The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.

Body:
The sum of digits can be calculated using that function (based on other answers):

function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}

If you really need to sum the digits recursively there is recursive version of the function:

function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}

The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.


问:
Delete items that are empty or null - JS - MYSQL - PHP
I have a big list of products, and then i display that on another page, but i need display just the items that had some value, if in DB the item is null, or 0, i need delete it from the list.

The code for the list ais as follow:

```<code>
<html lang="pt-br">

<head>

 <meta charset="utf-8">

    <style>

    * {

    box-sizing: content-box;

    }

    li {

    display: block; }

    body {

    margin: 0;
    padding: 0;
    background: lightgray;

    }

.header h1 {

    color: black;
    background-color: #87c587;
    font-weight: italic;
    text-align: center;
    /*border: 1px solid white;*/
    /*border-bottom: none;
    border-radius: 10px 10px 0px 0px;*/
    padding: 20px;
    font-size: 22px;
}
#nome1 {
    position: relative;
    text-align: center;
    font-weight: bold;
    font-size: 16px;
}

</style>
</head>

<body>

<div class="header">

    <h1>lista de <span id="nome1"></span></h1>

</div>

<ul id="populate"></ul>

<li>Açúcar: <span id="acucar"></span></li>

    <li>Aveia: <span id="aveia"></span></li>

    <li>Catchup: <span id="catchup"></div></li>

    <li>Caldo de Carne: <div id="caldodecarne"></div>

    <li>Caldo de galinha: <span id="caldodegalinha"><span></li>

    <li>Caldo de legumes: <span id="caldodelegumes"><span></li>

    <li>Extrato de tomate: <span id="extratodetomate"></span></li>

    <li>Gelatina em pó: <span id="gelatina"></span></li>

    <li>Iogurte de frutas: <span id="iogurtedefrutas"></span></li>

    <li>Leite de coco: <span id="leitedecoco"></span></li>

    <li>Macarrão instantâneo: <span id="miojo"></span></li>

    <li>Massa de lasanha: <span id="massadelasanha"></span></li>

    <li>Óleo: <span id="Oleo"></span></li>

    <li>Sal: <span id="Sal"></span></li>

    <li>Suco de frutas: <span id="sucodefrutas"></span></li>

    <li>Adoçante: <span id="Adocante"></span></li>

    <li>Azeite: <span id="Azeite"></span></li>

    <li>Bebida láctea: <span id="gelatina"></span></li>

    <li>Cereal: <span id="Cereal"></span></li>

    <li>Creme de leite: <span id="CremeDeLeite"></span></li>

    <li>Fermento biológico: <span id="Fermento"></span></li>

    <li>Geleia: <span id="geleia"></span></li>

<input style="text-align:center;" id="nome" name="nome" type="text">

    <input type="submit" id="lstButton" name="lstButton" value="Confirmar nome">

</ul>

</code>```

the script for check the tag name and then exclude ```display: none;" is as follow, but not working.</p>

```
document.getElementById("lstButton").onclick = delNoSelectedProducts;

function delNoSelectedProducts()

 {

var produtos = document.getElementsByTagName("LI").value;

if(produtos == '' || produtos == null)

{

produtos.style.display = "none";

}

}
</script>
```

<p>and my Ajax/jQuery is very basic...:</p>

```    $(document).ready(function()

    {
    var url = "lista.php";

    $('#lstButton').on('click',function(e)

    {

        var nome = $.trim($("#nome").val());
        e.preventDefault();

        $.ajax(

        {

            type: "POST",
            action: $(this),
            crossDomain: true,
            cache: false,
            url: url,
            dataType: 'json',
            data: {nome:nome},

            success:function(data)

            {
                if(data.status == "success")

                {
                    //$('#populate').html(result); // doesn't work.

                    $('#acucar').html(data.result.acucar);
                    $('#aveia').text(data.result.aveia);
                    $("#caldodecarne").text(data.result.caldodecarne);
                    $("#caldodegalinha").text(data.result.caldodegalinha);
                    $("#caldodelegumes").text(data.result.caldodelegumes);
                    $("#catchup").text(data.result.catchup);
                    $("#extratodetomate").text(data.result.extratodetomate);
                    $("#gelatina").text(data.result.gelatina);
                    $("#iogurtedefrutas").text(data.result.iogurtedefrutas);
                    $("#leitedecoco").text(data.result.leitedecoco);
                    $("#leite").text(data.result.leite)
                    $("#miojo").text(data.result.miojo);
                    $("#massadelasanha").text(data.result.massadelasanha);
                    $("#oleo").text(data.result.Oleo);
                    $('#Suco').text(data.result.Sal);
                    $('#Adocante').text(data.result.adocante);
                    $('#Azeite').text(data.result.Azeite);
                    $('#Cereal').text(data.result.Cereal);
                    $('#CremeDeLeite').text(data.result.cremedeleite);

                    //$('.user-info').slideDown();

                }
                    else

                {
                    //$('.user-info').slideUp();
                    $('#status").text("error");
                }
            }
        });
    });
});
```

in the server is all ok, but i don't get it how to populate all list with one unique id, then i'm doing in that way...

I'll apreciate any help in advance!

答:
A variable can't be both '' and null, which is what you're checking for. Us the OR operator instead of &&:</p>

```<code>if(produtos == '' || produtos == null)
</code>```

Body:
I have a big list of products, and then i display that on another page, but i need display just the items that had some value, if in DB the item is null, or 0, i need delete it from the list.

The code for the list ais as follow:

 <meta charset="utf-8">

lista de

Açúcar:

Aveia:

Catchup:

Caldo de Carne:

Caldo de galinha:

Caldo de legumes:

Extrato de tomate:

Gelatina em pó:

Iogurte de frutas:

Leite de coco:

Macarrão instantâneo:

Massa de lasanha:

Óleo:

Sal:

Suco de frutas:

Adoçante:

Azeite:

Bebida láctea:

Cereal:

Creme de leite:

Fermento biológico:

Geleia:

<input style="text-align:center;" id="nome" name="nome" type="text">

    <input type="submit" id="lstButton" name="lstButton" value="Confirmar nome">

the script for check the tag name and then exclude ```display: none;" is as follow, but not working.

document.getElementById("lstButton").onclick = delNoSelectedProducts;

function delNoSelectedProducts()

 {

var produtos = document.getElementsByTagName("LI").value;

if(produtos == '' || produtos == null)

{

produtos.style.display = "none";

}

}
</script>

and my Ajax/jQuery is very basic...:

    $(document).ready(function()

    {
    var url = "lista.php";

    $('#lstButton').on('click',function(e)

    {

        var nome = $.trim($("#nome").val());
        e.preventDefault();

        $.ajax(

        {

            type: "POST",
            action: $(this),
            crossDomain: true,
            cache: false,
            url: url,
            dataType: 'json',
            data: {nome:nome},

            success:function(data)

            {
                if(data.status == "success")

                {
                    //$('#populate').html(result); // doesn't work.

                    $('#acucar').html(data.result.acucar);
                    $('#aveia').text(data.result.aveia);
                    $("#caldodecarne").text(data.result.caldodecarne);
                    $("#caldodegalinha").text(data.result.caldodegalinha);
                    $("#caldodelegumes").text(data.result.caldodelegumes);
                    $("#catchup").text(data.result.catchup);
                    $("#extratodetomate").text(data.result.extratodetomate);
                    $("#gelatina").text(data.result.gelatina);
                    $("#iogurtedefrutas").text(data.result.iogurtedefrutas);
                    $("#leitedecoco").text(data.result.leitedecoco);
                    $("#leite").text(data.result.leite)
                    $("#miojo").text(data.result.miojo);
                    $("#massadelasanha").text(data.result.massadelasanha);
                    $("#oleo").text(data.result.Oleo);
                    $('#Suco').text(data.result.Sal);
                    $('#Adocante').text(data.result.adocante);
                    $('#Azeite').text(data.result.Azeite);
                    $('#Cereal').text(data.result.Cereal);
                    $('#CremeDeLeite').text(data.result.cremedeleite);

                    //$('.user-info').slideDown();

                }
                    else

                {
                    //$('.user-info').slideUp();
                    $('#status").text("error");
                }
            }
        });
    });
});

in the server is all ok, but i don't get it how to populate all list with one unique id, then i'm doing in that way...

I'll apreciate any help in advance!

Body:
A variable can't be both '' and null, which is what you're checking for. Us the OR operator instead of &&:

if(produtos == '' || produtos == null)


问:
Primefaces 8.0 Datatable with Dynamic Model and Columns
I have a primefaces dataTable that displays data from several database tables.  A selection list allows the user to select the specific database table to display.  It works as expected except when the dataTable filtering capability is used.  For example, when a user selects 'DEPT' from the selection list, the dataTable is rendered with data from the DEPT table.  The user can select other tables normally.  However, if the user selects another table called 'EMP' after filtering, the dataTable fails to render with the following exception:

```<code>javax.el.PropertyNotFoundException: The class 'example.dto.Dept' does not have the property 'firstName'.
at javax.el.BeanELResolver.getBeanProperty(BeanELResolver.java:576)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:291)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:156)
</code>```

Here's the .xhtml file:

```<code><h:form prependId="false">

    <p:outputLabel for="selTbl" value="Select a table:" />
    <p:autoComplete id="selTbl" value="#{mainBean.selectedTable}"
        completeMethod="#{mainBean.filterAuditTables}" cache="true" dropdown="true" effect="fade"
        minQueryLength="3" forceSelection="true" size="35" style="margin-left: 10px;">
        <p:ajax event="itemSelect" listener="#{mainBean.onTableSelect}" process="@this" update="@form" />
    </p:autoComplete>

    <p:dataTable id="audTblData" value="#{mainBean.data}" var="row"
        filteredValue="#{mainBean.filteredData}" resizableColumns="true" resizeMode="expand"
        sortMode="multiple">

        <f:facet name="header">
            <h:outputText value="#{mainBean.selectedTable}" />
        </f:facet>

        <p:columns value="#{mainBean.tableColumns}" var="col" sortBy="#{row[col.property]}"
            filterBy="#{row[col.property]}" filterMatchMode="contains">
            <f:facet name="header">
                <h:outputText value="#{col.header}" />
            </f:facet>
            <h:outputText value="#{row[col.property]}" />
        </p:columns>

    </p:dataTable>

</h:form>
</code>```

MainBean.java:

```<code>@Named
@ViewScoped
public class MainBean implements Serializable {

    private static final long serialVersionUID = 1L;

    // these are used for the audited table selection list
    private List<String> auditedTables;
    private String selectedTable;

    // these are used in the table that displays the audit data
    private List<ColumnModel> tableColumns;
    private List<Auditable> data;
    private List<Auditable> filteredData;

    @Inject
    private AudviewService audviewService;

    @PostConstruct
    public void init() {
        auditedTables = audviewService.getAuditedTables();
    }

    public List<String> filterAuditTables(String query) {
        return auditedTables
                .stream()
                .filter(t -> t.contains(query.toUpperCase()))
                .collect(Collectors.toList());
    }

    public void onTableSelect(SelectEvent<String> event) {
        retrieveTableData();
    }

    public void retrieveTableData() {

        List<String> columns = audviewService.listTableColumns(selectedTable);

        // initialize columns for <p:dataTable>
        tableColumns = new ArrayList<ColumnModel>();
        for (String col : columns) {
            tableColumns.add(new ColumnModel(col, AudviewUtil.columnToProperty(col)));
        }

        // retrieve data for the selected table
        data = audviewService.getTableData(selectedTable);
    }

    /* getters and setters */
}
</code>```

Note that Auditable is an interface implemented by Dept.java and Emp.java.

答:
As you noticed, the problem is switching from a filtered or sorted datatable to another, if the filtered or sorted column is a field that isn't in the new selected class. An easy solution would be moving all the needed fields into the superclass Auditable.

Another approach is separating datatable resetting&updating in two steps, here a possible solution (I replace, for testing purpose, your service with static code, so there could be some errors adapting my solution to your code):

xhtml

```<code><h:form id="formTbl" prependId="false">

    <p:outputLabel for="selTbl" value="Select a table:" />
    <p:autoComplete id="selTbl" value="#{mainBean.selectedTable}"
        completeMethod="#{mainBean.filterAuditTables}" cache="true"
        dropdown="true" effect="fade" minQueryLength="3"
        forceSelection="true" size="35" style="margin-left: 10px;">
        <p:ajax event="itemSelect" listener="#{mainBean.onTableSelect}"
            process="@this" onstart="PF('vtWidget').clearFilters()" />
    </p:autoComplete>
    <p:remoteCommand name="btn" process="@this" update="audTblData" />

    <p:dataTable id="audTblData" value="#{mainBean.data}" var="row"
        filteredValue="#{mainBean.filteredData}" resizableColumns="true"
        resizeMode="expand" sortMode="multiple" widgetVar="vtWidget">

        <f:facet name="header">
            <h:outputText value="#{mainBean.selectedTable}" />
        </f:facet>

        <p:columns value="#{mainBean.tableColumns}" var="col"
            sortBy="#{row[col.property]}" filterBy="#{row[col.property]}"
            filterMatchMode="contains">
            <f:facet name="header">
                <h:outputText value="#{col.header}" />
            </f:facet>
            <h:outputText value="#{row[col.property]}" />
        </p:columns>

    </p:dataTable>

</h:form>
</code>```

java

```<code>public void retrieveTableData() {

    List<String> columns = listTableColumns(selectedTable);

    // initialize columns for <p:dataTable>
    tableColumns = new ArrayList<ColumnModel>();
    for (String col : columns) {
        tableColumns.add(new ColumnModel(col + " header", col));
    }

    // retrieve data for the selected table
    data = getData(selectedTable);
    DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("formTbl:audTblData");
    if (dataTable != null) {
        dataTable.reset();
    }
    PrimeFaces.current().executeScript("btn()");
}
</code>```

Pay attention, if you need also to manage pagination.

Body:
I have a primefaces dataTable that displays data from several database tables.  A selection list allows the user to select the specific database table to display.  It works as expected except when the dataTable filtering capability is used.  For example, when a user selects 'DEPT' from the selection list, the dataTable is rendered with data from the DEPT table.  The user can select other tables normally.  However, if the user selects another table called 'EMP' after filtering, the dataTable fails to render with the following exception:

javax.el.PropertyNotFoundException: The class 'example.dto.Dept' does not have the property 'firstName'.
at javax.el.BeanELResolver.getBeanProperty(BeanELResolver.java:576)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:291)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:156)

Here's the .xhtml file:

<h:form prependId="false">

        <f:facet name="header">
            <h:outputText value="#{mainBean.selectedTable}" />
        </f:facet>

            <f:facet name="header">
                <h:outputText value="#{col.header}" />
            </f:facet>
            <h:outputText value="#{row[col.property]}" />

</h:form>

MainBean.java:

@Named
@ViewScoped
public class MainBean implements Serializable {

    private static final long serialVersionUID = 1L;

    // these are used for the audited table selection list
    private List<String> auditedTables;
    private String selectedTable;

    // these are used in the table that displays the audit data
    private List<ColumnModel> tableColumns;
    private List<Auditable> data;
    private List<Auditable> filteredData;

    @Inject
    private AudviewService audviewService;

    @PostConstruct
    public void init() {
        auditedTables = audviewService.getAuditedTables();
    }

    public List<String> filterAuditTables(String query) {
        return auditedTables
                .stream()
                .filter(t -> t.contains(query.toUpperCase()))
                .collect(Collectors.toList());
    }

    public void onTableSelect(SelectEvent<String> event) {
        retrieveTableData();
    }

    public void retrieveTableData() {

        List<String> columns = audviewService.listTableColumns(selectedTable);

        // initialize columns for

        tableColumns = new ArrayList<ColumnModel>();
        for (String col : columns) {
            tableColumns.add(new ColumnModel(col, AudviewUtil.columnToProperty(col)));
        }

        // retrieve data for the selected table
        data = audviewService.getTableData(selectedTable);
    }

    /* getters and setters */
}

Note that Auditable is an interface implemented by Dept.java and Emp.java.

Body:
As you noticed, the problem is switching from a filtered or sorted datatable to another, if the filtered or sorted column is a field that isn't in the new selected class. An easy solution would be moving all the needed fields into the superclass Auditable.

Another approach is separating datatable resetting&updating in two steps, here a possible solution (I replace, for testing purpose, your service with static code, so there could be some errors adapting my solution to your code):

xhtml

<h:form id="formTbl" prependId="false">

    <p:outputLabel for="selTbl" value="Select a table:" />
    <p:autoComplete id="selTbl" value="#{mainBean.selectedTable}"
        completeMethod="#{mainBean.filterAuditTables}" cache="true"
        dropdown="true" effect="fade" minQueryLength="3"
        forceSelection="true" size="35" style="margin-left: 10px;">
        <p:ajax event="itemSelect" listener="#{mainBean.onTableSelect}"
            process="@this" onstart="PF('vtWidget').clearFilters()" />
    </p:autoComplete>
    <p:remoteCommand name="btn" process="@this" update="audTblData" />

    <p:dataTable id="audTblData" value="#{mainBean.data}" var="row"
        filteredValue="#{mainBean.filteredData}" resizableColumns="true"
        resizeMode="expand" sortMode="multiple" widgetVar="vtWidget">

        <f:facet name="header">
            <h:outputText value="#{mainBean.selectedTable}" />
        </f:facet>

        <p:columns value="#{mainBean.tableColumns}" var="col"
            sortBy="#{row[col.property]}" filterBy="#{row[col.property]}"
            filterMatchMode="contains">
            <f:facet name="header">
                <h:outputText value="#{col.header}" />
            </f:facet>
            <h:outputText value="#{row[col.property]}" />
        </p:columns>

    </p:dataTable>

</h:form>

java

public void retrieveTableData() {

    List<String> columns = listTableColumns(selectedTable);

    // initialize columns for <p:dataTable>
    tableColumns = new ArrayList<ColumnModel>();
    for (String col : columns) {
        tableColumns.add(new ColumnModel(col + " header", col));
    }

    // retrieve data for the selected table
    data = getData(selectedTable);
    DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("formTbl:audTblData");
    if (dataTable != null) {
        dataTable.reset();
    }
    PrimeFaces.current().executeScript("btn()");
}

Pay attention, if you need also to manage pagination.


问:
How to toggle the display property of two sibling elements on hover of one?
I am trying to toggle the display of two sibling elements when I hover on the first sibling. I want to change the display of the hovered first sibling element from block to none while its immediate or next sibling element's style changes to block from none. I was able to write a css code for that but on hover, the elements constantly flicker and alternate in a never ending loop. Below is my html and css code:

.box {
  display: inline-block;
  width: 300px;
  height: 150px;
  margin: 20px 40px;
  border-radius: 4px;
  cursor: pointer;
}

.box-one {
  background: green;
}

.box-two {
  background: whitesmoke;
  display: none;
}

.box-one:hover {
  display: none;
}

.box-one:hover+.box-two {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box box-one"></div>
<div class="box box-two"></div></code>```

答:
Wrap the two boxes with another div (.container) and toggle them when hovering the container:

.box {
  display: inline-block;
  width: 300px;
  height: 150px;
  margin: 20px 40px;
  border-radius: 4px;
  cursor: pointer;
}

.box-one {
  background: green;
}

.box-two {
  background: whitesmoke;
}

.container {
  width: fit-content;
}

.container:hover>.box-one {
  display: none;
}

.container:not(:hover)>.box-two {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box-one"></div>
  <div class="box box-two"></div>
</div></code>```

Using JS mouseenter and mouseleave events, you can add the event listener with the once: true option only to the current item. As soon as the mouse enter, you show the new item, and only when the user leaves the current item, you add the new mouseenter event listener to the current item, and so on...

const showNext = evt => {
  const current = evt.target
  const next = current.nextElementSibling

  if(!next || !next.classList.contains('box')) return

  current.classList.remove('show')

  next.classList.add('show')

  next.addEventListener('mouseleave', () => {
    next.addEventListener('mouseenter', showNext, { once: true })
  }, { once: true })
}

document.querySelector('.box')
  .addEventListener('mouseenter', showNext, { once: true })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  display: none;
  width: 300px;
  height: 150px;
  margin: 20px 40px;
  border-radius: 4px;
  cursor: pointer;
}

.show {
  display: inline-block;
}

.box-one {
  background: green;
}

.box-two {
  background: whitesmoke;
}

.box-three {
  background: red;
}

.box-four {
  background: blue;
}

.container {
  width: fit-content;
}</code>```

```

Body:
Wrap the two boxes with another div (.container) and toggle them when hovering the container:

.box {
  display: inline-block;
  width: 300px;
  height: 150px;
  margin: 20px 40px;
  border-radius: 4px;
  cursor: pointer;
}

.box-one {
  background: green;
}

.box-two {
  background: whitesmoke;
}

.container {
  width: fit-content;
}

.container:hover>.box-one {
  display: none;
}

.container:not(:hover)>.box-two {
  display: none;
}

<div class="container">
  <div class="box box-one"></div>
  <div class="box box-two"></div>
</div>

Using JS mouseenter and mouseleave events, you can add the event listener with the once: true option only to the current item. As soon as the mouse enter, you show the new item, and only when the user leaves the current item, you add the new mouseenter event listener to the current item, and so on...

const showNext = evt => {
  const current = evt.target
  const next = current.nextElementSibling

  if(!next || !next.classList.contains('box')) return

  current.classList.remove('show')

  next.classList.add('show')

  next.addEventListener('mouseleave', () => {
    next.addEventListener('mouseenter', showNext, { once: true })
  }, { once: true })
}

document.querySelector('.box')
  .addEventListener('mouseenter', showNext, { once: true })

.box {
  display: none;
  width: 300px;
  height: 150px;
  margin: 20px 40px;
  border-radius: 4px;
  cursor: pointer;
}

.show {
  display: inline-block;
}

.box-one {
  background: green;
}

.box-two {
  background: whitesmoke;
}

.box-three {
  background: red;
}

.box-four {
  background: blue;
}

.container {
  width: fit-content;
}

<div class="box box-one show"></div>
<div class="box box-two"></div>
<div class="box box-three"></div>
<div class="box box-four"></div>


问:
Remove character from behind using `Backspace` fireEvent
I try to remove a character from behind using the Backspace event but it didn't work as expected.

It won't let me delete the character from behind using the `Backspace.

```<code>input.focus()
const options = {
    key: 'Backspace',
    keyCode: 8,
    which: 8,
}
fireEvent.keyDown(input, options)
fireEvent.keyUp(input, options)
</code>```

Reproduction: https://codesandbox.io/s/testing-library-delete-1-character-i4y3d?file=/src/input.test.js:507-753

答:
I'm able to solve this issue by adding this function.

```<code>function backspace(element) {
  let actuallyTyped = element.value;

  const backspaceKey = {
    key: 'Backspace',
    code: 8,
    inputType: 'deleteContentBackward',
  };

  const sharedEventConfig = {
    key: backspaceKey.key,
    charCode: backspaceKey.code,
    keyCode: backspaceKey.code,
    which: backspaceKey.code,
    modifier: backspaceKey.modifier,
  };
  const downEvent = fireEvent.keyDown(element, sharedEventConfig);

  if (downEvent) {
    actuallyTyped = actuallyTyped.slice(0, -1);

    fireEvent.input(element, {
      target: { value: actuallyTyped },
      inputType: backspaceKey.inputType,
      bubbles: true,
      cancelable: true,
    });
  }

  fireEvent.keyUp(element, sharedEventConfig);
}
</code>```

And then calling it in my test task.

```<code>  // delete up 5 times
  let count = 5;
  do {
    backspace(input);
  } while (count--);
</code>```

Body:
I try to remove a character from behind using the Backspace event but it didn't work as expected.

It won't let me delete the character from behind using the `Backspace.

input.focus()
const options = {
    key: 'Backspace',
    keyCode: 8,
    which: 8,
}
fireEvent.keyDown(input, options)
fireEvent.keyUp(input, options)

Reproduction: https://codesandbox.io/s/testing-library-delete-1-character-i4y3d?file=/src/input.test.js:507-753

Body:
I'm able to solve this issue by adding this function.

function backspace(element) {
  let actuallyTyped = element.value;

  const backspaceKey = {
    key: 'Backspace',
    code: 8,
    inputType: 'deleteContentBackward',
  };

  const sharedEventConfig = {
    key: backspaceKey.key,
    charCode: backspaceKey.code,
    keyCode: backspaceKey.code,
    which: backspaceKey.code,
    modifier: backspaceKey.modifier,
  };
  const downEvent = fireEvent.keyDown(element, sharedEventConfig);

  if (downEvent) {
    actuallyTyped = actuallyTyped.slice(0, -1);

    fireEvent.input(element, {
      target: { value: actuallyTyped },
      inputType: backspaceKey.inputType,
      bubbles: true,
      cancelable: true,
    });
  }

  fireEvent.keyUp(element, sharedEventConfig);
}

And then calling it in my test task.

  // delete up 5 times
  let count = 5;
  do {
    backspace(input);
  } while (count--);


问:
Tidymodels Recipe Package Use step_normalize On List Of Variables
I want to normalize only an arbitrary selection of variables using step_normalize from the recipe package (tidymodels). Unfortunately I can't find a selection function that seems to work within the step_normalize which selects a list of variables:

```<code>library(tidymodels)
iris %>%
  recipe(Species ~ .) %>%
  step_normalize(vars_select(Sepal.Length, Petal.Length)) %>%
  prep()
</code>```

I get this error message:

```<code>Error: Not all functions are allowed in step function selectors (e.g. `vars_select`). See ?selections.
</code>```

答:
step_normalize does not support this select helper function, this works:

```<code>iris %>%
  recipe(Species ~ .) %>%
  step_normalize(Sepal.Length, Petal.Length) %>%
  prep()
</code>```

See ?selections for supported selector functions.

Body:
I want to normalize only an arbitrary selection of variables using step_normalize from the recipe package (tidymodels). Unfortunately I can't find a selection function that seems to work within the step_normalize which selects a list of variables:

library(tidymodels)
iris %>%
  recipe(Species ~ .) %>%
  step_normalize(vars_select(Sepal.Length, Petal.Length)) %>%
  prep()

I get this error message:

Error: Not all functions are allowed in step function selectors (e.g. `vars_select`). See ?selections.

Body:
step_normalize does not support this select helper function, this works:

iris %>%
  recipe(Species ~ .) %>%
  step_normalize(Sepal.Length, Petal.Length) %>%
  prep()

See ?selections for supported selector functions.


问:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist while creating new actor
Have below two entities with manytomany mapping and I want to save Actor with roles into DB for existing roles.

```<code>@Entity
@Data
@Table(name = "actor")
@NoArgsConstructor
public class Actor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long actorId;
    @Column(unique = true)
    @NotNull
    private String username;
    @NotNull
    private String password;
    @Column(unique = true)
    @NotNull
    private String email;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "actor_role", joinColumns = @JoinColumn(name = "actorId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
    private Collection<Role> roles;
}
</code>```

```<code>@Entity
@Table(name = "role")
@Data
@NoArgsConstructor
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long roleId;
    @Column(unique = true)
    @NotNull
    private String roleName;

    @LazyCollection(LazyCollectionOption.FALSE)
    @ManyToMany(mappedBy = "roles")
    private Collection<Actor> actors;

    public Role(String roleName) {
        super();
        this.roleName = roleName;
    }

}
</code>```

When I tried creating a new Actor using JPA ActorRepository

```<code>final Actor actor = new Actor();
actor.setUsername(user.getUsername());
actor.setPassword("");
actor.setEmail(user.getUsername());
List<Role> newRoles = new ArrayList<>();
for (GrantedAuthority authority : authentication.getAuthorities()) {
    Role role = roleRepo.findByRoleName(authority.getAuthority());
    newRoles.add(role);
}
actor.setRoles(newRoles);
Actor savedActor = actorRepo.save(actor);
</code>```

I am getting below error

```<code>Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: org.db.model.Role
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
</code>```

Can you please help me with this, I am new to JPA.

Thanks In Advance

答:
You need to keep synchronized both sides of the relation. Currently you are using EAGER for Actor.roles but, when you get the Role using findByRoleName, the provided one does not contain the list of Actors (and you are not updating that one, I mean, Role.actors)

So, basically you have 2 options:

Use EAGER in both sides. It has several performance problems.

Be sure you will get the required entities with queries in both cases (using JOIN FETCH).

On the other hand, it is avisable use Set for such kinds of relations.
The following links will provide you more information:

Link 1

Link 2

Body:
Have below two entities with manytomany mapping and I want to save Actor with roles into DB for existing roles.

@Entity
@Data
@Table(name = "actor")
@NoArgsConstructor
public class Actor {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long actorId;
    @Column(unique = true)
    @NotNull
    private String username;
    @NotNull
    private String password;
    @Column(unique = true)
    @NotNull
    private String email;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "actor_role", joinColumns = @JoinColumn(name = "actorId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
    private Collection<Role> roles;
}

@Entity
@Table(name = "role")
@Data
@NoArgsConstructor
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long roleId;
    @Column(unique = true)
    @NotNull
    private String roleName;

    @LazyCollection(LazyCollectionOption.FALSE)
    @ManyToMany(mappedBy = "roles")
    private Collection<Actor> actors;

    public Role(String roleName) {
        super();
        this.roleName = roleName;
    }

}

When I tried creating a new Actor using JPA ActorRepository

final Actor actor = new Actor();
actor.setUsername(user.getUsername());
actor.setPassword("");
actor.setEmail(user.getUsername());
List<Role> newRoles = new ArrayList<>();
for (GrantedAuthority authority : authentication.getAuthorities()) {
    Role role = roleRepo.findByRoleName(authority.getAuthority());
    newRoles.add(role);
}
actor.setRoles(newRoles);
Actor savedActor = actorRepo.save(actor);

I am getting below error

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: org.db.model.Role
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)

Can you please help me with this, I am new to JPA.

Thanks In Advance


问:
How to move Navbar Elements to the center?
I want to move 'Try again' between 'New Colors' and 'Easy' to the center. I already tried using flex and other things but I can't figure it out. I want to make it responsive as well.

          NEW COLORS (current)

          class="nav-link" href="#"
            >Try Again (current)

          class="nav-link" href="#"
            >EASY (current)

          class="nav-link" href="#">HARD

```

答:
Add in d-flex and justify-content-between class in id="navbarSupportedContent"
. Then remove ml-auto class in the last navbar-nav
. Then, the nav item will be align left, center and right.

```<code><div class="collapse navbar-collapse d-flex justify-content-between" id="navbarSupportedContent">
     ...
<ul class="navbar-nav pr-md-5 mr-md-5"> <!-- Remove ml-auto -->
</code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

          NEW COLORS (current)

          Try Again (current)

          EASY (current)

          HARD

```

Body:
I want to move 'Try again' between 'New Colors' and 'Easy' to the center. I already tried using flex and other things but I can't figure it out. I want to make it responsive as well.

          NEW COLORS (current)

          Try Again (current)

          EASY (current)

          HARD

Body:
Add in d-flex and justify-content-between class in id="navbarSupportedContent" <div>. Then remove ml-auto class in the last navbar-nav <ul>. Then, the nav item will be align left, center and right.

<div class="collapse navbar-collapse d-flex justify-content-between" id="navbarSupportedContent">
     ...
<ul class="navbar-nav pr-md-5 mr-md-5"> <!-- Remove ml-auto -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<nav class="navbar navbar-expand navbar-light">
  <div class='container'>
    <!-- Add in d-flex and justify-content-between -->
    <div class="collapse navbar-collapse d-flex justify-content-between" id="navbarSupportedContent">
      <ul class="navbar-nav ml-md-5 pl-md-5">
        <li class="nav-item">
          <a class="nav-link" href="#">NEW COLORS <span class="sr-only">(current)</span></a>
        </li>
      </ul>
      <ul class="navbar-nav"> <!-- Remove d-flex -->
        <li class="nav-item">
          <a class="nav-link" href="#">Try Again <span class="sr-only">(current)</span></a>
        </li>
      </ul>
      <ul class="navbar-nav pr-md-5 mr-md-5"> <!-- Remove ml-auto -->
        <li class="nav-item">
          <a class="nav-link" href="#">EASY <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">HARD</a>
        </li>
      </ul>
    </div>
</nav>
</div>


问:
Dividing one smaller number with the bigger one doesn't work without special decleration c#
This:

float a = 2 / 4;
return a;

Will output as 0, while this:

float a = 2;
float b = 4;
float c = a / b;
return c;

Will give a correct output 0.5.

Why am I getting this result?

答:
Because 2 and 4 are the type of integer.</p>

```<code>Type type1 = 2.GetType();
Type type2 = 4.GetType();
</code>```

Body:
Because 2 and 4 are the type of integer.

Type type1 = 2.GetType();
Type type2 = 4.GetType();


问:
Azure SQL Database Partitioning
I currently have an Azure SQL Database (Standard 100 DTUs S3) and I'm wanting to create partitions on a large table splitting a datetime2 value into YYYYMM. Each table has at least the following columns:

Guid (uniqueidentifier type)

MsgTimestamp (datetime2 type) << partition using this.

I've been looking on Azure documentation and SO but can't find anything that clearly says how to create a partition on a 'datetime2' in the desired format or even if it's supported on the SQL database type.

Another example if trying the link below, but I do not find the option to create a partition within SQL Studio to create a partition on the Storage menu.

https://www.sqlshack.com/database-table-partitioning-sql-server/

In addition, would these tables have to be created daily as the clock goes past 12am or is this done automatically?

UPDATE

I suspect I may have to manually create the partitions using the first link below and then at the beginning of each month, use the second link to create the next months partition table in advance.

https://learn.microsoft.com/en-us/sql/t-sql/statements/create-partition-function-transact-sql?view=sql-server-ver15

https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-partition-function-transact-sql?view=sql-server-ver15

Context

I currently connect into a real-time feed that feeds upto 600 rows a minute and have a backlog of around 370 million for 3 years worth of data.

答:
Correct.

You can create partitions based upon datetime2 columns. Generally, you'd just do that on the start of month date, and you'd use a RANGE RIGHT (so that the start of the month is included in the partition).

And yes, at the end of every month, the normal action is to:

Split the partition function to add a new partition option.

Switch out the oldest monthly partition into a separate table for archiving purposes (presuming you want to have a rolling period of months)

And another yes, we all wish the product had options to do this for you automatically.

I was one of the tech reviewers on the following whitepaper by Ron Talmage, back in 2008 and 99% of the advice in it is still current:
https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008/dd578580(v=sql.100)

Title: Azure SQL Database Partitioning


问:
what is wrong with this code.. regarding strncat
sorry i modified the code now:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    int i=0;
    char** f=NULL;
    char* ff=NULL;

    ff="abcd";

    f=( char**)malloc ((i + 1) * sizeof (char *)+5);
    f[0]=ff;
 // strcpy(f[0],ff); (this again giving same error)
    strncat(f[0],"efg",3);
    printf("f : %s",f[0]);
}
</code>```

I am getting some unhandled exception, Access violation writing error. Can anyone explain me the error I did here.
NOTE : sorry i modified the code now:

Thanks for the answers

答:
```<code>char *ff;
ff = "whatever";
</code>```

ff is assigned a string literal, which cannot be changed. This piece of string is stored in the .rodata area of the executable in linux, and a similar readonly area in other types of executables. So after the assignment of the string literal ff = "whatever"  ff contains an address in memory which is read-only. By doing: char f[0] = ff and then trying to modify the string f[0] which actually points to ff which again points to the base address of the string whatever\0 stored in the memory which is read only, which you try to modify, which the OS stops you from doing.

Either You do :

```<code>  char *ff;
  ff = malloc (sizeof (char) * SIZE_OF_YOUR_CHOICE);
  strcpy (ff, "whatever");
  /* now do what ever modification (within the size limits) */
  free (ff);
</code>```

Or you do :

```<code>char ff[SIZE_OF_YOUR_CHOICE] = "whatever";
/* not do whatever modification (within the size limits) */
</code>```

Body:
sorry i modified the code now:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
    int i=0;
    char** f=NULL;
    char* ff=NULL;

    ff="abcd";

    f=( char**)malloc ((i + 1) * sizeof (char *)+5);
    f[0]=ff;
 // strcpy(f[0],ff); (this again giving same error)
    strncat(f[0],"efg",3);
    printf("f : %s",f[0]);
}

I am getting some unhandled exception, Access violation writing error. Can anyone explain me the error I did here.
NOTE : sorry i modified the code now:

Thanks for the answers

Body:
char *ff;
ff = "whatever";

ff is assigned a string literal, which cannot be changed. This piece of string is stored in the .rodata area of the executable in linux, and a similar readonly area in other types of executables. So after the assignment of the string literal ff = "whatever"  ff contains an address in memory which is read-only. By doing: char f[0] = ff and then trying to modify the string f[0] which actually points to ff which again points to the base address of the string whatever\0 stored in the memory which is read only, which you try to modify, which the OS stops you from doing.

Either You do :

  char *ff;
  ff = malloc (sizeof (char) * SIZE_OF_YOUR_CHOICE);
  strcpy (ff, "whatever");
  /* now do what ever modification (within the size limits) */
  free (ff);

Or you do :

char ff[SIZE_OF_YOUR_CHOICE] = "whatever";
/* not do whatever modification (within the size limits) */


问:
open a shell tab for each service in a docker compose file
I have a client-server (both written in C++) application that I am managing using docker-compose. I'm quite new in docker technology and I'm wondering if docker-compose up can do the following job for me:

run services

open a shell tab for each service in the docker-compose.yml file.

I need a separate shell for each service because everytime that I change the code (in client or server) I would like to stop the program, re-compile it and re-run. At the moment I use a workaround:

run docker-compose up

run docker container ls to find containers id

for each container open a shell tab and run docker exec -it <container-id> /bin/bash

I'm wondering if there is a more elegant solution. I'm using Ubuntu and this is my docker-compose.yml:

```<code>version: '3.1'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        volumes:
            - ./server/src:/home/src
            - ./server/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    client:
        build: ./client
        ports:
            - "2800:2800"
        volumes:
            - ./client/src:/home/src
            - ./client/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    db:
        image: mysql
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: example
</code>```

答:
Here is my example with Nginx

```<code>    version: '3'
    services:
        nginx:
            stdin_open: true
            tty: true
            image: nginx
            ports:
                - "80:80"
</code>```

Get into the container in interactive mode with docker-compose run <SERVICE_NAME> sh. Here is the command for getting into the Nginx container interactive mode

```<code>docker-compose run nginx sh
</code>```

Body:
I have a client-server (both written in C++) application that I am managing using docker-compose. I'm quite new in docker technology and I'm wondering if docker-compose up can do the following job for me:

run services

open a shell tab for each service in the docker-compose.yml file.

I need a separate shell for each service because everytime that I change the code (in client or server) I would like to stop the program, re-compile it and re-run. At the moment I use a workaround:

run docker-compose up

run docker container ls to find containers id

for each container open a shell tab and run docker exec -it <container-id> /bin/bash

I'm wondering if there is a more elegant solution. I'm using Ubuntu and this is my docker-compose.yml:

version: '3.1'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        volumes:
            - ./server/src:/home/src
            - ./server/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    client:
        build: ./client
        ports:
            - "2800:2800"
        volumes:
            - ./client/src:/home/src
            - ./client/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    db:
        image: mysql
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: example

Body:
Here is my example with Nginx

    version: '3'
    services:
        nginx:
            stdin_open: true
            tty: true
            image: nginx
            ports:
                - "80:80"

Get into the container in interactive mode with docker-compose run <SERVICE_NAME> sh. Here is the command for getting into the Nginx container interactive mode

docker-compose run nginx sh