问:
Getting a 500 Internal Server Error even with fixes as recommended in a couple of similar questions
I'm having same issue as described in these two questions/answers:

Python WSGI + Flask render_template - 500 Internal Server Error?

Getting a 500 Internal Server Error using render_template and Flask

and I've narrowed it to the following:

Here's the file structure:

```<code>../project/
    project.py
    templates/
        about.html
</code>```

I'm still getting this error (shorten):

```<code>
● project.service - Gunicorn instance to serve project
   Loaded: loaded (/etc/systemd/system/project.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2020-02-15 06:28:46 UTC; 3min 28s ago
 Main PID: 3942 (gunicorn)
    Tasks: 4 (limit: 1151)
   CGroup: /system.slice/project.service
           ├─3942 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           ├─3967 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           ├─3968 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           └─3969 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi

Feb 15 06:29:17 project gunicorn[3942]:     return self._load_template(name, self.make_globals(globals))
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/environment.py", line 857, in _load_template
Feb 15 06:29:17 project gunicorn[3942]:     template = self.loader.load(self, name, globals)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/loaders.py", line 117, in load
Feb 15 06:29:17 project gunicorn[3942]:     source, filename, uptodate = self.get_source(environment, name)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 60, in get_source
Feb 15 06:29:17 project gunicorn[3942]:     return self._get_source_fast(environment, template)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 89, in _get_source_fast
Feb 15 06:29:17 project gunicorn[3942]:     raise TemplateNotFound(template)
Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html
</code>```

So the issue as far as I can tell, is that last line

```<code>Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html
</code>```

I don't understand why, even though the files/folders are there. The closest I could find is this comment:

https://stackoverflow.com/a/56589998/12070612

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
```

But if I add the "ENV=..." lines to my project.py file, then Gunicorn complaints and fails to start process.

答:
There are different ways in Flask to render HTML. You could simply generate that HTML directly from the Python code similar to what you have done for the home route or you could use a templating language like Jinja.

What you have written in the about route is the render_template function. The way render_template works is by reading an HTML file with the name you pass as a parameter and renders that template. In you case, you have called the render_template method and asked it to render a template called about.html but since the template does not exist, it fails to load and throws an exception.

Create an about.html file at the same level as your app.py file and type in something in it and try to render. It should work.

To read more on render_template check out the documentation here or read the getting started tutorial for Flask here

Body:
I'm having same issue as described in these two questions/answers:

Python WSGI + Flask render_template - 500 Internal Server Error?

Getting a 500 Internal Server Error using render_template and Flask

and I've narrowed it to the following:

Here's the file structure:

../project/
    project.py
    templates/
        about.html

I'm still getting this error (shorten):

● project.service - Gunicorn instance to serve project
   Loaded: loaded (/etc/systemd/system/project.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2020-02-15 06:28:46 UTC; 3min 28s ago
 Main PID: 3942 (gunicorn)
    Tasks: 4 (limit: 1151)
   CGroup: /system.slice/project.service
           ├─3942 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           ├─3967 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           ├─3968 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi
           └─3969 /home/dev/project/project_env/bin/python3.6 /home/dev/project/project_env/bin/gunicorn --workers 3 --bind unix:project.sock -m 007 wsgi

Feb 15 06:29:17 project gunicorn[3942]:     return self._load_template(name, self.make_globals(globals))
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/environment.py", line 857, in _load_template
Feb 15 06:29:17 project gunicorn[3942]:     template = self.loader.load(self, name, globals)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/jinja2/loaders.py", line 117, in load
Feb 15 06:29:17 project gunicorn[3942]:     source, filename, uptodate = self.get_source(environment, name)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 60, in get_source
Feb 15 06:29:17 project gunicorn[3942]:     return self._get_source_fast(environment, template)
Feb 15 06:29:17 project gunicorn[3942]:   File "/home/dev/project/project_env/lib/python3.6/site-packages/flask/templating.py", line 89, in _get_source_fast
Feb 15 06:29:17 project gunicorn[3942]:     raise TemplateNotFound(template)
Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html

So the issue as far as I can tell, is that last line

Feb 15 06:29:17 project gunicorn[3942]: jinja2.exceptions.TemplateNotFound: about.html

I don't understand why, even though the files/folders are there. The closest I could find is this comment:

https://stackoverflow.com/a/56589998/12070612

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)

But if I add the "ENV=..." lines to my project.py file, then Gunicorn complaints and fails to start process.


来源: stackexchange

问:
Updating two consecutive textviews using threads
I have been reading up about threads in my java book and I wanted to try making updates with two consecutive threads at the same time.

OF course though threads can't update the UI. I have used handlers a little bit but only by passing messengers from one class to another to capture location from a service to an activity.

But this must be simpler than that.

I assume I should use AsyncTask but i want to count 1-10 in each field and I don't want to keep dipping in and out of the asynctask class.

Any pointers appreciated

Stephen

UPDATE

So I did a little more experimenting. I wrote a handler method to handle any messages sent to it. It checks which field it should be updating and then performs a setText on said field. Here is the code

```<code>Handler myHandler = new Handler(){
 public void handleMessage(Message msg){
 msg = Message.obtain();
 Bundle bundle = msg.getData();

 String fieldName = bundle.getString("fieldName");
 int count = bundle.getInt("count");

 if(fieldName=="text1"){
     text1.setText(count);
 }else{
     text2.setText(count);
 }
}
};
</code>```

I then have some code in the onCreate of my activity which launches two threads and each thread passes a messages with my int count to the handler. It also passes in a TextView name so my handler knows which textview it should be updating. Here is the code...

```<code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 text1 = (TextView)findViewById(R.id.text1);
 text2 = (TextView)findViewById(R.id.text2);

 new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text1");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
      }
    }.start();

new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text2");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
 }
   }.start();

}
</code>```

But I am getting an error on the setText

05-17 17:13:00.013: ERROR/AndroidRuntime(966): android.content.res.Resources$NotFoundException: String resource ID #0x0

Any ideas?

答:
If you really want to run two additional threads, that can be done with handlers. Simply create ONE handler for your activity and switch on what. Then launch two threads and when each thread completes send a message to the handler using the appropriate what value. Then update the appropriate text view in the handler as you are back in the UI thread in the handler:

```<code>private Handler myHandler= new Handler(){
    @Override
    public void  handleMessage(Message msg){
        switch(msg.what){
            case 0:
                this.removeMessages(0);
                Toast.makeText(Main.this,"Message0", Toast.LENGTH_SHORT).show();
            break;
            case 1:
                this.removeMessages(1);
                Toast.makeText(Main.this,"Message1", Toast.LENGTH_SHORT).show();
                break;
            default:
                super.handleMessage(msg);
                break;
        }
    }
};
</code>```

Simply replace the toast with your UI update code. You can launch a thread as in:

```<code>    // DISPLAY ON CLICK HANDLER
    threadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Thread thread= new Thread( new Runnable() {
                public void run() {
                    try {  // DO NOT TOUCH THE UI HERE
                    Thread.sleep(1000); // mimic time consuming task
                    }
                    catch(Exception e){
                    }
                    myHandler.sendEmptyMessage(0);
                }
            });
            thread.setDaemon(true);
            thread.start();
        }
    });
</code>```

If you just want to count from i= 1-10 seconds, you do not even need to use threads, just use postMessageDelayed by looping and calling:

```<code>myHandler.sendEmptyMessageDelayed(0, 1000);  // what 0, 1 second
</code>```

You can pass (preferably immutable) data in the messages as in:

```<code>Message msg= Message.obtainMessage(0);
Bundle b= new Bundle();
b.putString("stringData",outString);
msg.setData(b);
handler.sendMessage(msg);
</code>```

and retrieve it as in:

```<code>Bundle b= msg.getData();
String data="";
if (b != null){
    data= b.getString("stringData");
}
</code>```

If you only need one additional thread, I would use asyncTask.

ContentLicense: CC BY-SA 3.0

Body:
I have been reading up about threads in my java book and I wanted to try making updates with two consecutive threads at the same time.

OF course though threads can't update the UI. I have used handlers a little bit but only by passing messengers from one class to another to capture location from a service to an activity.

But this must be simpler than that.

I assume I should use AsyncTask but i want to count 1-10 in each field and I don't want to keep dipping in and out of the asynctask class.

Any pointers appreciated

Stephen

UPDATE

So I did a little more experimenting. I wrote a handler method to handle any messages sent to it. It checks which field it should be updating and then performs a setText on said field. Here is the code

Handler myHandler = new Handler(){
 public void handleMessage(Message msg){
 msg = Message.obtain();
 Bundle bundle = msg.getData();

 String fieldName = bundle.getString("fieldName");
 int count = bundle.getInt("count");

 if(fieldName=="text1"){
     text1.setText(count);
 }else{
     text2.setText(count);
 }
}
};

I then have some code in the onCreate of my activity which launches two threads and each thread passes a messages with my int count to the handler. It also passes in a TextView name so my handler knows which textview it should be updating. Here is the code...

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 text1 = (TextView)findViewById(R.id.text1);
 text2 = (TextView)findViewById(R.id.text2);

 new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text1");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
      }
    }.start();

new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text2");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
 }
   }.start();

}

But I am getting an error on the setText

05-17 17:13:00.013: ERROR/AndroidRuntime(966): android.content.res.Resources$NotFoundException: String resource ID #0x0

Any ideas?

Body:
If you really want to run two additional threads, that can be done with handlers. Simply create ONE handler for your activity and switch on what. Then launch two threads and when each thread completes send a message to the handler using the appropriate what value. Then update the appropriate text view in the handler as you are back in the UI thread in the handler:

private Handler myHandler= new Handler(){
    @Override
    public void  handleMessage(Message msg){
        switch(msg.what){
            case 0:
                this.removeMessages(0);
                Toast.makeText(Main.this,"Message0", Toast.LENGTH_SHORT).show();
            break;
            case 1:
                this.removeMessages(1);
                Toast.makeText(Main.this,"Message1", Toast.LENGTH_SHORT).show();
                break;
            default:
                super.handleMessage(msg);
                break;
        }
    }
};

Simply replace the toast with your UI update code. You can launch a thread as in:

    // DISPLAY ON CLICK HANDLER
    threadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Thread thread= new Thread( new Runnable() {
                public void run() {
                    try {  // DO NOT TOUCH THE UI HERE
                    Thread.sleep(1000); // mimic time consuming task
                    }
                    catch(Exception e){
                    }
                    myHandler.sendEmptyMessage(0);
                }
            });
            thread.setDaemon(true);
            thread.start();
        }
    });

If you just want to count from i= 1-10 seconds, you do not even need to use threads, just use postMessageDelayed by looping and calling:

myHandler.sendEmptyMessageDelayed(0, 1000);  // what 0, 1 second

You can pass (preferably immutable) data in the messages as in:

Message msg= Message.obtainMessage(0);
Bundle b= new Bundle();
b.putString("stringData",outString);
msg.setData(b);
handler.sendMessage(msg);

and retrieve it as in:

Bundle b= msg.getData();
String data="";
if (b != null){
    data= b.getString("stringData");
}

If you only need one additional thread, I would use asyncTask.


问:
clang-tidy report error unknown argument when contain other compiler options
I have a project, I built it with intel compiler. I want use the clang-tidy to help detect code problems.

I am using CMake to generate compile_commands.json and I'm getting the follow error when I using clang-tidy:

```<code>$ run-clang-tidy
# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 warning and 1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
warning: unknown warning option '-Wno-maybe-uninitialized'; did you mean '-Wno-uninitialized'? [clang-diagnostic-unknown-warning-option]
</code>```

Actually, there is a very simliar question exist: clang-tidy reporting unknown warnings

However, when I try to using the method refered above, there is no help. The warning can be suppressed but error still exist.

```<code>$ run-clang-tidy -extra-arg=-Wno-unknown-warning-option

# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -extra-arg=-Wno-unknown-warning-option -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
</code>```

How can I deal with the error?

-w2 options is used to control warning in intel compiler.

Although the problem occurs to me because of the intel compiler, but may be other compiler's options can also leads to the problem.

Appendix

The follow code snippets can help reproduce the problem.

```<code>// CMakeLists.txt
SET(CMAKE_CXX_COMPILER "icc")
SET(CMAKE_CXX_COMPILER "icpc")

project(test)

# leads to warning, can be settled by refer link
add_compile_options("-Wno-maybe-uninitialized")

# leads to error, can not be settled by refer link
add_compile_options("-w2")

add_executable(a.out main.cpp)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
</code>```

```<code>// main.cpp
#include <iostream>
int main()
{
    std::cout << "hello!" << std::endl;
    return 0;
}
</code>```

the above code can generate compile_commands.json like follows:

```<code>[
{
  "directory": "/home/xuhui/temp/build",
  "command": "/opt/intel/compilers_and_libraries_2019.0.117/linux/bin/intel64/icpc      -Wno-maybe-uninitialized -w2 -o CMakeFiles/a.out.dir/main.o -c /home/xuhui/temp/main.cpp",
  "file": "/home/xuhui/temp/main.cpp"
}
]
</code>```

Thanks for your time.

答:
@pablo285 already give the perfect answer.
He said that:

have to remove the argument before passing the compile commands to
  clang-tidy

He already provide a link to demonstate how to modify CMakeLists.txt to remove argument.

Also, we can do some modification directly on compile_commands.json to remove argument.

A script to tidy code can be written as follows:

```<code># tidy_code.sh

cd build
cmake ..

# do modification on compile_commands.json to remove argument which clang can not recognized
# replace '-w2' to ' '
sed -i 's/-w2/ /g' compile_commands.json

# using clang tidy
run-clang-tidy -checks='*' -extra-arg=-Wno-unknown-warning-option
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a project, I built it with intel compiler. I want use the clang-tidy to help detect code problems.

I am using CMake to generate compile_commands.json and I'm getting the follow error when I using clang-tidy:

$ run-clang-tidy
# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 warning and 1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
warning: unknown warning option '-Wno-maybe-uninitialized'; did you mean '-Wno-uninitialized'? [clang-diagnostic-unknown-warning-option]

Actually, there is a very simliar question exist: clang-tidy reporting unknown warnings

However, when I try to using the method refered above, there is no help. The warning can be suppressed but error still exist.

$ run-clang-tidy -extra-arg=-Wno-unknown-warning-option

# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -extra-arg=-Wno-unknown-warning-option -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]

How can I deal with the error?

-w2 options is used to control warning in intel compiler.

Although the problem occurs to me because of the intel compiler, but may be other compiler's options can also leads to the problem.

Appendix

The follow code snippets can help reproduce the problem.

// CMakeLists.txt
SET(CMAKE_CXX_COMPILER "icc")
SET(CMAKE_CXX_COMPILER "icpc")

project(test)

# leads to warning, can be settled by refer link
add_compile_options("-Wno-maybe-uninitialized")

# leads to error, can not be settled by refer link
add_compile_options("-w2")

add_executable(a.out main.cpp)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

// main.cpp
#include <iostream>
int main()
{
    std::cout << "hello!" << std::endl;
    return 0;
}

the above code can generate compile_commands.json like follows:

[
{
  "directory": "/home/xuhui/temp/build",
  "command": "/opt/intel/compilers_and_libraries_2019.0.117/linux/bin/intel64/icpc      -Wno-maybe-uninitialized -w2 -o CMakeFiles/a.out.dir/main.o -c /home/xuhui/temp/main.cpp",
  "file": "/home/xuhui/temp/main.cpp"
}
]

Thanks for your time.

Body:
@pablo285 already give the perfect answer.
He said that:

have to remove the argument before passing the compile commands to
  clang-tidy

He already provide a link to demonstate how to modify CMakeLists.txt to remove argument.

Also, we can do some modification directly on compile_commands.json to remove argument.

A script to tidy code can be written as follows:

# tidy_code.sh

cd build
cmake ..

# do modification on compile_commands.json to remove argument which clang can not recognized
# replace '-w2' to ' '
sed -i 's/-w2/ /g' compile_commands.json

# using clang tidy
run-clang-tidy -checks='*' -extra-arg=-Wno-unknown-warning-option


问:
Can anyone help me this? HTTPS in Alibaba Cloud WA
I have been told to notice this rule as follow:

"Before using the HTTPS protection feature in Alibaba Cloud WAF, you
must upload the server certificate and private key beforehand."

Does anyone know where I can find this? At Alibaba website or someplace?

答:
Check out the "Procedure" on the following link, it describes how to authenticate and configure HTTPS certificates:

https://www.alibabacloud.com/help/doc-detail/27118.htm


问:
JSX array.map undefined boolean data
i tried to display & map my objects in a table row, but my boolean datas will return as undefined and i can't even convert them into strings, whats the solution?

Look at user.isenable and user.isonline in mapping ...

this is what i tried ...

```<code>import { component, Fragment } from 'react'

class Users extends Component {
  constructor(props) {
    super(props);

    this.state = {
      users: []
    };
  }
  componentDidMount() {
    const url = "http://localhost:4000/api/user";
    // AXIOS REQUEST
    axios.get(url).then(res => {
      this.setState({ users: res.data });
      console.log(this.state.users);
    });
  }

  render() {
    const users = this.state;
    console.log(this.state.users.isenbale);
    return (
      <table id="users">
        <tr>
          <th>is Enable</th>
          <th>is Online</th>
        </tr>

        {this.state.users.map(user => {
          return (
            <tr key={user.nationalcode}>
              <td>{user.isEnable.toString()}</td>
              <td>{user.isOnline.toString()}</td>
            </tr>
          );
        })}
      </table>
    );
  }
}
</code>```

console logs of res.data & this.state.users are the same.

(5) [{…}, {…}, {…}, {…}, {…}]
0: {nationalcode: 134556778, stockcode: "md3456", firstname: "ali", lastname: "khodabakhashi", isenable: true, …}
1: {nationalcode: 1334853905, stockcode: "md4f5789", firstname: "saeed", lastname: "mohammad", isenable: true, …}
2: {nationalcode: 11313, stockcode: "31313", firstname: "1313", lastname: "1313", isenable: null, …}
3: {nationalcode: 4151515, stockcode: "151", firstname: "5131", lastname: "3114", isenable: null, …}
4: {nationalcode: 123456789, stockcode: "3131", firstname: "31", lastname: "3131", isenable: null, …}
length: 5
__proto__: Array(0)
```

答:
There is two issues.

In the example users object you provided it is isenable with lowercase. However, you are trying to reference isEnable

Some of your isenable fields are null. This does not have a toString method

As null is falsy, you can short circuit it.

Here is an example

Title: JSX array.map undefined boolean data

Body:
i tried to display & map my objects in a table row, but my boolean datas will return as undefined and i can't even convert them into strings, whats the solution?

Look at user.isenable and user.isonline in mapping ...

this is what i tried ...

import { component, Fragment } from 'react'

class Users extends Component {
  constructor(props) {
    super(props);

    this.state = {
      users: []
    };
  }
  componentDidMount() {
    const url = "http://localhost:4000/api/user";
    // AXIOS REQUEST
    axios.get(url).then(res => {
      this.setState({ users: res.data });
      console.log(this.state.users);
    });
  }

  render() {
    const users = this.state;
    console.log(this.state.users.isenbale);
    return (

          is Enable
          is Online

        {this.state.users.map(user => {
          return (

              {user.isEnable.toString()}
              {user.isOnline.toString()}

          );
        })}

    );
  }
}

console logs of res.data & this.state.users are the same.

(5) [{…}, {…}, {…}, {…}, {…}]
0: {nationalcode: 134556778, stockcode: "md3456", firstname: "ali", lastname: "khodabakhashi", isenable: true, …}
1: {nationalcode: 1334853905, stockcode: "md4f5789", firstname: "saeed", lastname: "mohammad", isenable: true, …}
2: {nationalcode: 11313, stockcode: "31313", firstname: "1313", lastname: "1313", isenable: null, …}
3: {nationalcode: 4151515, stockcode: "151", firstname: "5131", lastname: "3114", isenable: null, …}
4: {nationalcode: 123456789, stockcode: "3131", firstname: "31", lastname: "3131", isenable: null, …}
length: 5
__proto__: Array(0)


问:
How to keep persistent volumes in sync between clusters?
I'm trying to get an installation of Wordpress running in Kubernetes, as well as have an option of running the same configuration locally in minikube. I want to use the standard Docker image of Wordpress: https://hub.docker.com/_/wordpress/.

I'm having trouble with making sure that the plugins and templates are in sync though. The Docker container exposes a Volume at /var/www/html. Wordpress installation, as well as my plugins will live there.

Assuming I do the development on Minikube, along with the installation of plugins etc. How do handle the move between Persistent Volumes between my local cluster and the target cluster? Should I just reinstall Wordpress every time when the Pod is scaled?

答: You can follow Writing Portable Configuration (https://kubernetes.io/docs/concepts/storage/persistent-volumes/#writing-portable-configuration) guide for persistent volume if you are planning to migrate it to different cluster.</p>


问:
How can I automatically reconnect Chrome DevTools after reinstall a cordova app?
I'm developing a hybrid Android app with Cordova and using Chrome DevTools (chrome://inspect/#devices) to inspect and debug.

Every time I run cordova run android --emulator to update the app on emulator, DevTools gets disconnected.

My question is how can I automatically reconnect DevTools after Cordova successfully launch the app?

答:
Based on Paul's answer, I updated his script and modified to my approach if an Android device is connected.

Considering the Android device is connected on local IP 192.168.0.149 on port 5037, entering this script in chrome://inspect/#devices worked like a charm:

const targetNode = document.querySelector('#device\\:192\\.168\\.0\\.149\\:5037 .browsers')

const callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    if (mutation.addedNodes.length) {
      targetNode.querySelector('.action').click();
    }
  }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, {childList: true});
```


问:
Dyanamic mutation dplyr
I want to dynamically subtract values using mutate but not sure how to do it. Below is an exemplar image of what I would like to do:

Staring from the 2nd row of the table, Col C = previous Col C element - current Col B element, i.e. 5- 1 = 4. Similarly 3rd row of Col C = 2nd element of Col C (that we just mutated) -  3rd element of Col B, i.e. 4-2 = 2. Thus, nth element of Col C = (n-1)th of Col C - nth of Col B. I already have values in Col B, but Col C values are being mutated dynamically. So the current mutated value for Col C depends on the previous mutated value. I am using lag command (dplyr) to subtract the values. Can anyone help with this dynamic mutation?

Thanks a lot!

答:
We can subtract the cumulative sum from the second value in ColB onwards with the 1st value in ColB. This can be done in base R

```<code>df$ColC <- with(df, c(ColB[1], ColB[1] - cumsum(ColB[-1])))
df
#  ColB ColC
#1    5    5
#2    1    4
#3    2    2
#4    3   -1
#5    4   -5
</code>```

Or using dplyr

```<code>library(dplyr)
df %>% mutate(ColC = c(first(ColB),first(ColB) - cumsum(ColB[-1])))
</code>```

data

```<code>df <- data.frame(ColB = c(5, 1:4))
</code>```

Title: Dyanamic mutation dplyr

Body:
We can subtract the cumulative sum from the second value in ColB onwards with the 1st value in ColB. This can be done in base R

df$ColC <- with(df, c(ColB[1], ColB[1] - cumsum(ColB[-1])))
df
#  ColB ColC
#1    5    5
#2    1    4
#3    2    2
#4    3   -1
#5    4   -5

Or using dplyr

library(dplyr)
df %>% mutate(ColC = c(first(ColB),first(ColB) - cumsum(ColB[-1])))

data

df <- data.frame(ColB = c(5, 1:4))


问:
How to find the path of a running process using the process id? (windows)
I have a little script that scans the opened windows, when it founds a word doc opened it has to get the path to the file. But how ? I searched a lot but nothing seems to work. I would appreciate any help. Thanks in advance.</p>

```<code>from ctypes import *
import sys
from win32gui import GetWindowText, GetForegroundWindow
import win32gui
import win32clipboard
import os
import shutil
import time

user32   = windll.user32
kernel32 = windll.kernel32
psapi    = windll.psapi
current_window = None

def get_current_process():
    global current_window
    global process_id
    # get a handle to the foreground window
    hwnd = user32.GetForegroundWindow()

    # find the process ID
    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    # store the current process ID
    process_id = "%d" % pid.value

    # grab the executable
    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)

    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    # now read it's title
    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    # print out the header if we're in the right process

    print("\n")
    print("[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value))
    print("\n")

while True:
    get_current_process()
    time.sleep(10)
</code>```

答:
use CreateToolhelp32Snapshot, the MODULEENTRY32 struct contains szModule which is module name and szExePath is the full path

CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot
def GetModulePath(PID,ModuleName):
    hModuleSnap = CreateToolhelp32Snapshot( 0x00000008, PID );
    me32 = MODULEENTRY32()
    me32.dwSize = sizeof(MODULEENTRY32)
    Module32First( hModuleSnap, byref(me32))
    path = None
    while True:
        if (me32.szModule.lower()==ModuleName.lower()):
            path=me32.szExePath
            break
        if not Module32Next(hModuleSnap, byref(me32)):
            break
    CloseHandle(hModuleSnap)
    return path
```

Body:
I have a little script that scans the opened windows, when it founds a word doc opened it has to get the path to the file. But how ? I searched a lot but nothing seems to work. I would appreciate any help. Thanks in advance.

from ctypes import *
import sys
from win32gui import GetWindowText, GetForegroundWindow
import win32gui
import win32clipboard
import os
import shutil
import time

user32   = windll.user32
kernel32 = windll.kernel32
psapi    = windll.psapi
current_window = None

def get_current_process():
    global current_window
    global process_id
    # get a handle to the foreground window
    hwnd = user32.GetForegroundWindow()

    # find the process ID
    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    # store the current process ID
    process_id = "%d" % pid.value

    # grab the executable
    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)

    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    # now read it's title
    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    # print out the header if we're in the right process

    print("\n")
    print("[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value))
    print("\n")

while True:
    get_current_process()
    time.sleep(10)


问:
How do i reinterpter_cast vector to int?
I've got a vector of four bytes:
std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa };, which in hexadecimal is. (0x0000000a)

How do i type-pun it into an int32_t so that i get 10 using reinterpret_cast?

This can be done easily using bitshifts like this:

(int32_t)((src[offset] << 24) | (src[offset+ 1] << 16) | (src[offset+ 2] << 8) | (src[offset+ 3]));

but as far as i'm aware of how reinterpret_cast work, it can be used here at its best, but i can't firgure out how exactly do that in code itself.

```<code>reinterpret_cast<int32_t*>(&0x0000000a);
</code>```

ps: This is not just for int32_t or so, this can be reinterpreted to anything i would wish. That's the point.

答:
```<code>#include <iostream>
#include <numeric>
#include <vector>

int main() {
  std::vector<int8_t> src = { 0x0, 0x0, 0x27, 0x10 };
  std::cout <<
    std::accumulate(src.begin(), src.end(),  // or src.begin() + sizeof(int32_t)
       0, [](const uint32_t &a, const uint8_t &b){ return a * 256 + b; });
  std::cout << std::endl;
  return 0;
}
</code>```

Body:
I've got a vector of four bytes:
std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa };, which in hexadecimal is. (0x0000000a)

How do i type-pun it into an int32_t so that i get 10 using reinterpret_cast?

This can be done easily using bitshifts like this:

(int32_t)((src[offset] << 24) | (src[offset+ 1] << 16) | (src[offset+ 2] << 8) | (src[offset+ 3]));

but as far as i'm aware of how reinterpret_cast work, it can be used here at its best, but i can't firgure out how exactly do that in code itself.

reinterpret_cast<int32_t*>(&0x0000000a);

ps: This is not just for int32_t or so, this can be reinterpreted to anything i would wish. That's the point.


问:
How do you keep variables in Visual Studio C sharp
I am creating a web game using Visual Studio and asp.net.

Now, I want to navigate from form 1 to form 2. However, I dont know how to store the login name and password so that I can update records later from form 2.

This is my code in form 1 where i get the username of the person playing.

```<code> SqlCommand cmd = new SqlCommand
     ("select UserName from UserData where UserName = @name", conn);
            cmd.Parameters.Add(new SqlParameter("@name", TextBox2.Text.ToString()));
            // 2. Call Execute reader to get query results
            SqlDataReader rdr = cmd.ExecuteReader();

            //Label1.Text = "Welcome";
            while (rdr.Read())
            {
                Label1.Text = "Welcome " + rdr["UserName"].ToString() +
                                  ". Press the Play Button to Play";
                Button3.Enabled = true;
            }

            if (rdr.HasRows == false)
            {
              //  Button3.Enabled = false;
                Label1.Text = "Sorry You arent in our system.
                                 Please Register Yourself Before Starting";
            }

        }
        catch (Exception ex)
        {
           // Label1.Text = "Error: " + ex.Message + "<br/>";
        }
</code>```

Now, I want to go to form two and update his results. How can I do that.

Thank you.

答:
If I understand your question correctly, you need to store the value in session state so that you can retrieve in subsequence page request.</p>

```<code>// Form 1
while (rdr.Read())
{
   Page.Session["UserName"] = rdr["UserName"].ToString();
   Label1.Text = "Welcome " + rdr["UserName"].ToString() + ". Press the Play Button to Play";
   Button3.Enabled = true;
}

// Form 2
string username = Page.Session["UserName"].ToString(); // Retrieve in form 2
</code>```

Body:
I am creating a web game using Visual Studio and asp.net.

Now, I want to navigate from form 1 to form 2. However, I dont know how to store the login name and password so that I can update records later from form 2.

This is my code in form 1 where i get the username of the person playing.

 SqlCommand cmd = new SqlCommand
     ("select UserName from UserData where UserName = @name", conn);
            cmd.Parameters.Add(new SqlParameter("@name", TextBox2.Text.ToString()));
            // 2. Call Execute reader to get query results
            SqlDataReader rdr = cmd.ExecuteReader();

            //Label1.Text = "Welcome";
            while (rdr.Read())
            {
                Label1.Text = "Welcome " + rdr["UserName"].ToString() +
                                  ". Press the Play Button to Play";
                Button3.Enabled = true;
            }

            if (rdr.HasRows == false)
            {
              //  Button3.Enabled = false;
                Label1.Text = "Sorry You arent in our system.
                                 Please Register Yourself Before Starting";
            }

        }
        catch (Exception ex)
        {
           // Label1.Text = "Error: " + ex.Message + "
";
        }

Now, I want to go to form two and update his results. How can I do that.

Thank you.

Body:
If I understand your question correctly, you need to store the value in session state so that you can retrieve in subsequence page request.

// Form 1
while (rdr.Read())
{
   Page.Session["UserName"] = rdr["UserName"].ToString();
   Label1.Text = "Welcome " + rdr["UserName"].ToString() + ". Press the Play Button to Play";
   Button3.Enabled = true;
}

// Form 2
string username = Page.Session["UserName"].ToString(); // Retrieve in form 2


问:
padding leading zeros (0 characters) in some string
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

```<code>char str[11] = "12345";
</code>```

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

```<code>sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters
</code>```

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);
</code>```

2nd Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);
</code>```

If I try using sprintf with string as argument I get leading blanks:

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);
</code>```

OUTPUT:

```<code>     12345   //leading spaces
</code>```

Is there any simple method to accomplish this?

答:
Given that you want the padded string in the original array, you can use memmove to shift the number to the end of the array, and then use memset to fill with zeros.

```<code>char str[11] = "12345";
size_t text_size = strlen(str) + 1;
memmove(str + sizeof(str) - text_size, str, text_size);
memset(str, '0', sizeof(str) - text_size);
</code>```

Body:
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

char str[11] = "12345";

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);

2nd Method

char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);

If I try using sprintf with string as argument I get leading blanks:

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);

OUTPUT:

     12345   //leading spaces

Is there any simple method to accomplish this?

Body:
Given that you want the padded string in the original array, you can use memmove to shift the number to the end of the array, and then use memset to fill with zeros.

char str[11] = "12345";
size_t text_size = strlen(str) + 1;
memmove(str + sizeof(str) - text_size, str, text_size);
memset(str, '0', sizeof(str) - text_size);


问:
Spring boot + ActiveMQ + stomp broker relay failed to connect
I am following the this guide http://spring.io/guides/gs/messaging-stomp-websocket/ and but instead of using the simple message broker, I am trying to use the stomp broker relay

```<code>@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableStompBrokerRelay("/topic").setRelayHost("stomp://localhost").setRelayPort(61612);
    registry.setApplicationDestinationPrefixes("/app");
}
</code>```

and I am trying but my console keeps showing failed to connect

2016-02-26 01:38:05.786  INFO 3584 --- [           main] o.s.m.s.s.StompBrokerRelayMessageHandler : Connecting "system" session to stomp://localhost:61612

2016-02-26 01:38:05.942  INFO 3584 --- [eactor-tcp-io-1] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

2016-02-26 01:38:05.957  INFO 3584 --- [           main] o.s.m.s.s.StompBrokerRelayMessageHandler : Started.

2016-02-26 01:38:06.025  INFO 3584 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8052 (http)

2016-02-26 01:38:06.025  INFO 3584 --- [           main] main.java.test.TestApplication             : Started TestApplication in 9.419 seconds (JVM running for 15.121)

2016-02-26 01:38:11.022  INFO 3584 --- [eactor-tcp-io-2] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

2016-02-26 01:38:16.008  INFO 3584 --- [eactor-tcp-io-3] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

My activemq.xml is the default except for this:

```<code><transportConnectors>
        <transportConnector name="stomp" uri="stomp://localhost:61612"/>
 </transportConnectors>
</code>```

ActiveMQ starts up with no problems as I am able to connect to the admin page at http://localhost:8161/admin.

Here is my maven pom.xml in case someone spots out that I might be using the wrong dependencies

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><groupId>com.test.program</groupId>
<artifactId>testapp</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.2.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-messaging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-core</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>2.0.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-net</artifactId>
        <version>2.0.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport</artifactId>
        <version>4.0.34.Final</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport-native-epoll</artifactId>
        <version>4.0.34.Final</version>
    </dependency>

</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestone</id>
        <url>https://repo.spring.io/libs-release</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>

</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-milestone</id>
        <url>https://repo.spring.io/libs-release</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>
</code>```

答:
change the configureMessageBroker as shown below</p>

```<code> @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app");
    registry.enableStompBrokerRelay("/topic").setRelayHost("localhost").setRelayPort(15672).setClientLogin("guest")
            .setClientPasscode("guest");
}
</code>```

Body:
I am following the this guide http://spring.io/guides/gs/messaging-stomp-websocket/ and but instead of using the simple message broker, I am trying to use the stomp broker relay

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableStompBrokerRelay("/topic").setRelayHost("stomp://localhost").setRelayPort(61612);
    registry.setApplicationDestinationPrefixes("/app");
}

and I am trying but my console keeps showing failed to connect

2016-02-26 01:38:05.786  INFO 3584 --- [           main] o.s.m.s.s.StompBrokerRelayMessageHandler : Connecting "system" session to stomp://localhost:61612

2016-02-26 01:38:05.942  INFO 3584 --- [eactor-tcp-io-1] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

2016-02-26 01:38:05.957  INFO 3584 --- [           main] o.s.m.s.s.StompBrokerRelayMessageHandler : Started.

2016-02-26 01:38:06.025  INFO 3584 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8052 (http)

2016-02-26 01:38:06.025  INFO 3584 --- [           main] main.java.test.TestApplication             : Started TestApplication in 9.419 seconds (JVM running for 15.121)

2016-02-26 01:38:11.022  INFO 3584 --- [eactor-tcp-io-2] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

2016-02-26 01:38:16.008  INFO 3584 --- [eactor-tcp-io-3] r.io.net.impl.netty.tcp.NettyTcpClient   : Failed to connect to stomp://localhost:61612. Attempting reconnect in 5000ms.

My activemq.xml is the default except for this:

<transportConnectors>
        <transportConnector name="stomp" uri="stomp://localhost:61612"/>
 </transportConnectors>

ActiveMQ starts up with no problems as I am able to connect to the admin page at http://localhost:8161/admin.

Here is my maven pom.xml in case someone spots out that I might be using the wrong dependencies

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<groupId>com.test.program</groupId>
<artifactId>testapp</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.2.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-messaging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-core</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>3.1.5</version>
    </dependency>

    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-core</artifactId>
        <version>2.0.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-net</artifactId>
        <version>2.0.7.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport</artifactId>
        <version>4.0.34.Final</version>
    </dependency>

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-transport-native-epoll</artifactId>
        <version>4.0.34.Final</version>
    </dependency>

</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestone</id>
        <url>https://repo.spring.io/libs-release</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>

</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-milestone</id>
        <url>https://repo.spring.io/libs-release</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

Body:
change the configureMessageBroker as shown below

 @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app");
    registry.enableStompBrokerRelay("/topic").setRelayHost("localhost").setRelayPort(15672).setClientLogin("guest")
            .setClientPasscode("guest");
}


问:
Not able to reach an internal endpoint when using tcp-services
I have an issue on which am blocked since few days . Tried lot of things but none worked .

I have a k8s cluster in which I have a pod running corda (https://docs.corda.net/docker-image.html) . This pod expose a RPC endpoint (10201), endpoint that I want to be able to reach from outside the cluster (my laptop) using the corda-shell tool .

So I created an ingress (using ingress-nginx) and added a config-map that looks like that :

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-tcp-services
  namespace: {{ .Release.Namespace }}
data:
  10201: {{ .Release.Namespace }}/{{ .Release.Name }}-corda-node:10201
</code>```

The service.yaml for the corda pod looks like this :

```<code>apiVersion: v1
kind: Service
metadata:
  name: {{ include "corda-node.fullname" . }}
  labels:
{{ include "corda-node.labels" . | indent 4 }}
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      protocol: TCP
      name: http
    - port: 10200
      targetPort: p2p
      protocol: TCP
      name: p2p
    - port: 10201
      targetPort: rpc
      protocol: TCP
      name: rpc
    - port: 10202
      targetPort: rpcadmin
      protocol: TCP
      name: rpcadmin
  selector:
    app.kubernetes.io/name: {{ include "corda-node.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
</code>```

But so far, no matter what I tried I was not able to connect to it from the outside .
From another pod / container in the cluster it is working fine, same as when I'm port-forwarding to my local .

Note : I can connect to other services in my cluster from the outside . In fact this corda pod has a sidecar which expose an API on 8080 and I can access it .

I can see the port '10201' being exposed by the ingress, so I guess it took my tcp-services into account, but does not seem to be able to forward the request to the corda pod .

If I try to do telnet public-ip-of-the-cluter 10201 , I just have a timeout .
Same when running the corda-shell tool ...

I see no relevant logs in the ingress-controller pod as far as I can tell .

I created a small github repo with various 'kubectl describe xxx' commands in order to give you an overview of what I did .

If you need more info just ask me . Am really struggling with that, most likely I'm doing something stupid somewhere ...

Thanks !

EDIT :

I put the logs of the ingress on - --v=3 , I can see this when it starts :

I0215 09:30:32.081819       6 controller.go:333] Searching Endpoints
  with TCP port number 10201 for Service
  "salmon-locust/salmon-locust-corda-node-corda-node"

  │ │ I0215 09:30:32.081836       6 endpoints.go:74] Getting Endpoints
  for Service "salmon-locust/salmon-locust-corda-node-corda-node" and
  port &ServicePort{Name:rpc,Protocol:TCP,Port:10201,TargetPort:{1 0
  rpc},NodePort:0,}                  │ │ I0215 09:30:32.081849       6
  endpoints.go:117] Endpoints found for Service
  "salmon-locust/salmon-locust-corda-node-corda-node": [{10.96.1.13
  10201
  &ObjectReference{Kind:Pod,Namespace:salmon-locust,Name:salmon-locust-corda-node-corda-
  │

But no activity when I’m trying to connect to it via the corda-tools-shell.

EDIT 2 :

We found what was the issue, the ingress -> dns resolved to the cloudflare proxy, which was not handling the 1xxxx port ...

答: Is any incoming request in ingress logs ? Ingress might be looking http header which may not work right Corda RPC </p>

Body:
I have an issue on which am blocked since few days . Tried lot of things but none worked .

I have a k8s cluster in which I have a pod running corda (https://docs.corda.net/docker-image.html) . This pod expose a RPC endpoint (10201), endpoint that I want to be able to reach from outside the cluster (my laptop) using the corda-shell tool .

So I created an ingress (using ingress-nginx) and added a config-map that looks like that :

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-tcp-services
  namespace: {{ .Release.Namespace }}
data:
  10201: {{ .Release.Namespace }}/{{ .Release.Name }}-corda-node:10201

The service.yaml for the corda pod looks like this :

apiVersion: v1
kind: Service
metadata:
  name: {{ include "corda-node.fullname" . }}
  labels:
{{ include "corda-node.labels" . | indent 4 }}
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      protocol: TCP
      name: http
    - port: 10200
      targetPort: p2p
      protocol: TCP
      name: p2p
    - port: 10201
      targetPort: rpc
      protocol: TCP
      name: rpc
    - port: 10202
      targetPort: rpcadmin
      protocol: TCP
      name: rpcadmin
  selector:
    app.kubernetes.io/name: {{ include "corda-node.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}

But so far, no matter what I tried I was not able to connect to it from the outside .
From another pod / container in the cluster it is working fine, same as when I'm port-forwarding to my local .

Note : I can connect to other services in my cluster from the outside . In fact this corda pod has a sidecar which expose an API on 8080 and I can access it .

I can see the port '10201' being exposed by the ingress, so I guess it took my tcp-services into account, but does not seem to be able to forward the request to the corda pod .

If I try to do telnet public-ip-of-the-cluter 10201 , I just have a timeout .
Same when running the corda-shell tool ...

I see no relevant logs in the ingress-controller pod as far as I can tell .

I created a small github repo with various 'kubectl describe xxx' commands in order to give you an overview of what I did .

If you need more info just ask me . Am really struggling with that, most likely I'm doing something stupid somewhere ...

Thanks !

EDIT :

I put the logs of the ingress on - --v=3 , I can see this when it starts :

I0215 09:30:32.081819       6 controller.go:333] Searching Endpoints
  with TCP port number 10201 for Service
  "salmon-locust/salmon-locust-corda-node-corda-node"

  │ │ I0215 09:30:32.081836       6 endpoints.go:74] Getting Endpoints
  for Service "salmon-locust/salmon-locust-corda-node-corda-node" and
  port &ServicePort{Name:rpc,Protocol:TCP,Port:10201,TargetPort:{1 0
  rpc},NodePort:0,}                  │ │ I0215 09:30:32.081849       6
  endpoints.go:117] Endpoints found for Service
  "salmon-locust/salmon-locust-corda-node-corda-node": [{10.96.1.13
  10201
  &ObjectReference{Kind:Pod,Namespace:salmon-locust,Name:salmon-locust-corda-node-corda-
  │

But no activity when I’m trying to connect to it via the corda-tools-shell.

EDIT 2 :

We found what was the issue, the ingress -> dns resolved to the cloudflare proxy, which was not handling the 1xxxx port ...


问:
(How) Can I make this Array code look better? (Codingbat - Array-1 sum2)
I'm new to this forum and to programming and I have my first question :)

The objective is to return the sum of the first two integers in the array. My solution is in the picture I've added. Is there a way to solve this with less if cases? (I know I did not have to do the for loop, but I just learned it and wanted to try it out :D)

Thank you for all answers!

https://i.stack.imgur.com/hx06s.png

Edit: Here's my code:

```<code>public int sum2(int[] nums) {

  int sum = 0;

  if(nums.length == 0){
    return sum;
  }

  if(nums.length == 1){
    return nums[0];
  }
  for(int i = 0; i < 2; i++){
    sum += nums[i];
  }
  return sum;
}
</code>```

答:
you can use limit() method in stream</p>

```<code> public long sum2(int[] nums) {
      return Arrays.stream(nums).limit(2).sum();
   }
</code>```

Body:
I'm new to this forum and to programming and I have my first question :)

The objective is to return the sum of the first two integers in the array. My solution is in the picture I've added. Is there a way to solve this with less if cases? (I know I did not have to do the for loop, but I just learned it and wanted to try it out :D)

Thank you for all answers!

https://i.stack.imgur.com/hx06s.png

Edit: Here's my code:

public int sum2(int[] nums) {

  int sum = 0;

  if(nums.length == 0){
    return sum;
  }

  if(nums.length == 1){
    return nums[0];
  }
  for(int i = 0; i < 2; i++){
    sum += nums[i];
  }
  return sum;
}

Body:
you can use limit() method in stream

 public long sum2(int[] nums) {
      return Arrays.stream(nums).limit(2).sum();
   }


问:
RecyclerView item's properites automatically changing while using DataBinding
I'm trying to build a simple task using DataBinding (in Java) without any design pattern.
The scenario is that there is a RecyclerView in which items/ products are binding from a HardCoded List. Whenever a user clicks on any item, it should show that specific item on the Left (blank) side, with default values (properties). Now when the user clicks on that left-side item its properties (quantity, price, etc.) should be changed (only within that left-side box). Now everything is going fine. The problem is that after changing the left-side item's properties, whenever the user again clicks on the same item (that he clicked earlier) it is showing the item with changed values on the left side. But I want that on clicking again it should show the item with default values. I've attached all the classes and screenshots. Kindly identify me If I'm doing anything wrong.

Product.java

```<code>public class Product {
private String title;
private String price;
private String image;
private String quantity;
private String discount;

public Product(String title, String price, String image, String quantity, String discount) {
    this.title = title;
    this.price = price;
    this.image = image;
    this.quantity = quantity;
    this.discount = discount;
}

//Getters and Setters
}
</code>```

MainTestActivity.java

```<code>public class MainTestActivity extends AppCompatActivity implements ProductsListAdapter.ProductItemClickListener{

ActivityMainTestingBinding binding;
private Product myCurrentProduct;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main_testing);

    getItems();
}

private void getItems(){

    List<Product> products = new ArrayList<>();

    products.add(new Product("Black Grapes", "480", "", "1", "0"));
    products.add(new Product("Oranges", "198", "", "1", "0"));
    products.add(new Product("Pears", "170", "", "1", "0"));
    products.add(new Product("Apple", "169", "", "1", "0"));
    products.add(new Product("Jonagold", "110", "", "1", "0"));
    products.add(new Product("Lemon", "198", "", "1", "0"));

    binding.rvProductList.setLayoutManager(new GridLayoutManager(this, 5));
    binding.rvProductList.setAdapter(new ProductsListAdapter(products, this));
}

@Override
public void onProductItemClicked(Product product) {

    myCurrentProduct = product;

    binding.setPopUpProduct(myCurrentProduct);
    binding.cvCurrentProduct.setVisibility(View.VISIBLE);

    binding.cvCurrentProduct.setOnClickListener(v -> {
        myCurrentProduct.setDiscount("100");
        myCurrentProduct.setPrice("50000");
        myCurrentProduct.setQuantity("5");
        myCurrentProduct.setTitle("Null");
        binding.setPopUpProduct(myCurrentProduct);
    });
}
}
</code>```

ProductsListAdapter.java

```<code>public class ProductsListAdapter extends RecyclerView.Adapter<ProductsListAdapter.ViewHolder> {

private ProductItemClickListener mListener;
private List<Product> products;

public ProductsListAdapter(List<Product> products, ProductItemClickListener mListener) {
    this.products = products;
    this.mListener = mListener;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    ItemListProductsBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.item_list_products, viewGroup, false);
    return new ViewHolder(binding);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int i) {

    holder.bind(products.get(i), mListener);

}

@Override
public int getItemCount() {
    return products.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    ItemListProductsBinding binding;

    public ViewHolder(ItemListProductsBinding binding) {
        super(binding.getRoot());
        this.binding = binding;

    }

    void bind(Product currentProduct, ProductItemClickListener clickListener){
        //For each item, corresponding product object is passed to the binding
        binding.setProduct(currentProduct);
        binding.setProductItemClick(clickListener);
        //This is to force bindings to execute right away
        binding.executePendingBindings();
    }
}

public interface ProductItemClickListener {
    void onProductItemClicked(Product product);
}
}
</code>```

activity_main_testing.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="popUpProduct"
        type="tech.oratier.parlour.models.Product" />

</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:orientation="vertical">

        <com.google.android.material.card.MaterialCardView
            android:id="@+id/cvCurrentProduct"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="8dp"
            app:cardCornerRadius="5dp"
            app:cardElevation="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingTop="8dp"
                android:paddingBottom="8dp">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/ic_launcher_round" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/garamond"
                        android:hint="Product Title"
                        android:text="@{popUpProduct.title}"
                        android:textSize="30sp"
                        android:textStyle="bold" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Quantity:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.quantity}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Discount:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.discount}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Price:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.price}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/seperator" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Total"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.price != null ? (popUpProduct.quantity != null ? (popUpProduct.discount != null ? String.valueOf((Double.parseDouble(popUpProduct.price) * Double.parseDouble(popUpProduct.quantity)) - Double.parseDouble(popUpProduct.discount)) : String.valueOf(Double.parseDouble(popUpProduct.price) * Double.parseDouble(popUpProduct.quantity))) : @string/nothing) : @string/nothing}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>
        </com.google.android.material.card.MaterialCardView>
    </LinearLayout>

    <View
        android:layout_width="3dp"
        android:layout_height="match_parent"
        android:background="@color/seperator" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvProductList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />
    </LinearLayout>
</LinearLayout>
</code>```

item_list_products.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="product"
        type="tech.oratier.parlour.models.Product" />

    <variable
        name="productItemClick"
        type="tech.oratier.parlour.adapters.ProductsListAdapter.ProductItemClickListener" />
</data>

<com.google.android.material.card.MaterialCardView
android:layout_marginTop="5dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:onClick="@{()->productItemClick.onProductItemClicked(product)}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:contentPaddingRight="5dp"
android:orientation="vertical">

<LinearLayout
    android:paddingStart="16dp"
    android:paddingRight="16dp"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_marginTop="8dp"
        android:src="@mipmap/ic_launcher_round"
        android:layout_width="100dp"
        android:layout_height="100dp"/>

    <TextView
        android:fontFamily="@font/garabd"
        android:paddingLeft="8dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:paddingRight="8dp"
        android:background="@color/priceBackground"
        android:textColor="@color/defaultTextColor"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="@{product.price}"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

<com.google.android.material.textview.MaterialTextView
    android:singleLine="true"
    android:textSize="20sp"
    android:textColor="@android:color/black"
    android:fontFamily="@font/raleway_regular"
    android:layout_marginTop="8dp"
    android:layout_gravity="center_horizontal"
    android:text="@{product.title}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<com.google.android.material.textview.MaterialTextView
    android:singleLine="true"
    android:textSize="20sp"
    android:textColor="@android:color/black"
    android:fontFamily="@font/raleway_regular"
    android:layout_marginTop="8dp"
    android:layout_gravity="center_horizontal"
    android:text="@{product.quantity}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

答:
The problem is that I'm using

```<code>myCurrentProduct = product;
</code>```

Here it binds myCurrentProduct with product / layout therefore its value automatically updating.
So, to get rid of this I declared another object tempProduct as,

```<code>tempProduct = product;
</code>```

then I get values from tempProduct

```<code>myCurrentProduct = new Product();  //create a default constructor in Product model class
myCurrentProduct.setTitle(tempProduct.getTitle());
myCurrentProduct.setQuantity("5");
myCurrentProduct.setPrice("50000");
myCurrentProduct.setDiscount(tempProduct.getDiscount());
binding.setPopUpProduct(myCurrentProduct);
</code>```

In this way I'm also able to get values from the clicked item, also set my own values.

Body:
I'm trying to build a simple task using DataBinding (in Java) without any design pattern.
The scenario is that there is a RecyclerView in which items/ products are binding from a HardCoded List. Whenever a user clicks on any item, it should show that specific item on the Left (blank) side, with default values (properties). Now when the user clicks on that left-side item its properties (quantity, price, etc.) should be changed (only within that left-side box). Now everything is going fine. The problem is that after changing the left-side item's properties, whenever the user again clicks on the same item (that he clicked earlier) it is showing the item with changed values on the left side. But I want that on clicking again it should show the item with default values. I've attached all the classes and screenshots. Kindly identify me If I'm doing anything wrong.

Product.java

public class Product {
private String title;
private String price;
private String image;
private String quantity;
private String discount;

public Product(String title, String price, String image, String quantity, String discount) {
    this.title = title;
    this.price = price;
    this.image = image;
    this.quantity = quantity;
    this.discount = discount;
}

//Getters and Setters
}

MainTestActivity.java

public class MainTestActivity extends AppCompatActivity implements ProductsListAdapter.ProductItemClickListener{

ActivityMainTestingBinding binding;
private Product myCurrentProduct;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main_testing);

    getItems();
}

private void getItems(){

    List<Product> products = new ArrayList<>();

    products.add(new Product("Black Grapes", "480", "", "1", "0"));
    products.add(new Product("Oranges", "198", "", "1", "0"));
    products.add(new Product("Pears", "170", "", "1", "0"));
    products.add(new Product("Apple", "169", "", "1", "0"));
    products.add(new Product("Jonagold", "110", "", "1", "0"));
    products.add(new Product("Lemon", "198", "", "1", "0"));

    binding.rvProductList.setLayoutManager(new GridLayoutManager(this, 5));
    binding.rvProductList.setAdapter(new ProductsListAdapter(products, this));
}

@Override
public void onProductItemClicked(Product product) {

    myCurrentProduct = product;

    binding.setPopUpProduct(myCurrentProduct);
    binding.cvCurrentProduct.setVisibility(View.VISIBLE);

    binding.cvCurrentProduct.setOnClickListener(v -> {
        myCurrentProduct.setDiscount("100");
        myCurrentProduct.setPrice("50000");
        myCurrentProduct.setQuantity("5");
        myCurrentProduct.setTitle("Null");
        binding.setPopUpProduct(myCurrentProduct);
    });
}
}

ProductsListAdapter.java

public class ProductsListAdapter extends RecyclerView.Adapter<ProductsListAdapter.ViewHolder> {

private ProductItemClickListener mListener;
private List<Product> products;

public ProductsListAdapter(List<Product> products, ProductItemClickListener mListener) {
    this.products = products;
    this.mListener = mListener;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    ItemListProductsBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.item_list_products, viewGroup, false);
    return new ViewHolder(binding);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int i) {

    holder.bind(products.get(i), mListener);

}

@Override
public int getItemCount() {
    return products.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    ItemListProductsBinding binding;

    public ViewHolder(ItemListProductsBinding binding) {
        super(binding.getRoot());
        this.binding = binding;

    }

    void bind(Product currentProduct, ProductItemClickListener clickListener){
        //For each item, corresponding product object is passed to the binding
        binding.setProduct(currentProduct);
        binding.setProductItemClick(clickListener);
        //This is to force bindings to execute right away
        binding.executePendingBindings();
    }
}

public interface ProductItemClickListener {
    void onProductItemClicked(Product product);
}
}

activity_main_testing.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="popUpProduct"
        type="tech.oratier.parlour.models.Product" />

</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:orientation="vertical">

        <com.google.android.material.card.MaterialCardView
            android:id="@+id/cvCurrentProduct"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="8dp"
            app:cardCornerRadius="5dp"
            app:cardElevation="5dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingTop="8dp"
                android:paddingBottom="8dp">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:gravity="center">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/ic_launcher_round" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:fontFamily="@font/garamond"
                        android:hint="Product Title"
                        android:text="@{popUpProduct.title}"
                        android:textSize="30sp"
                        android:textStyle="bold" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Quantity:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.quantity}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Discount:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.discount}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Price:"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.price}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/seperator" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:text="Total"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:fontFamily="@font/garamond"
                            android:gravity="end"
                            android:text="@{popUpProduct.price != null ? (popUpProduct.quantity != null ? (popUpProduct.discount != null ? String.valueOf((Double.parseDouble(popUpProduct.price) * Double.parseDouble(popUpProduct.quantity)) - Double.parseDouble(popUpProduct.discount)) : String.valueOf(Double.parseDouble(popUpProduct.price) * Double.parseDouble(popUpProduct.quantity))) : @string/nothing) : @string/nothing}"
                            android:textSize="20sp"
                            android:textStyle="bold" />

                    </LinearLayout>
                </LinearLayout>

            </LinearLayout>
        </com.google.android.material.card.MaterialCardView>
    </LinearLayout>

    <View
        android:layout_width="3dp"
        android:layout_height="match_parent"
        android:background="@color/seperator" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvProductList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />
    </LinearLayout>
</LinearLayout>

item_list_products.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="product"
        type="tech.oratier.parlour.models.Product" />

    <variable
        name="productItemClick"
        type="tech.oratier.parlour.adapters.ProductsListAdapter.ProductItemClickListener" />
</data>

<com.google.android.material.card.MaterialCardView
android:layout_marginTop="5dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:onClick="@{()->productItemClick.onProductItemClicked(product)}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:contentPaddingRight="5dp"
android:orientation="vertical">

<LinearLayout
    android:paddingStart="16dp"
    android:paddingRight="16dp"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_marginTop="8dp"
        android:src="@mipmap/ic_launcher_round"
        android:layout_width="100dp"
        android:layout_height="100dp"/>

    <TextView
        android:fontFamily="@font/garabd"
        android:paddingLeft="8dp"
        android:paddingStart="8dp"
        android:paddingEnd="8dp"
        android:paddingRight="8dp"
        android:background="@color/priceBackground"
        android:textColor="@color/defaultTextColor"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="@{product.price}"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

<com.google.android.material.textview.MaterialTextView
    android:singleLine="true"
    android:textSize="20sp"
    android:textColor="@android:color/black"
    android:fontFamily="@font/raleway_regular"
    android:layout_marginTop="8dp"
    android:layout_gravity="center_horizontal"
    android:text="@{product.title}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<com.google.android.material.textview.MaterialTextView
    android:singleLine="true"
    android:textSize="20sp"
    android:textColor="@android:color/black"
    android:fontFamily="@font/raleway_regular"
    android:layout_marginTop="8dp"
    android:layout_gravity="center_horizontal"
    android:text="@{product.quantity}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</LinearLayout>

Body:
The problem is that I'm using

myCurrentProduct = product;

Here it binds myCurrentProduct with product / layout therefore its value automatically updating.
So, to get rid of this I declared another object tempProduct as,

tempProduct = product;

then I get values from tempProduct

myCurrentProduct = new Product();  //create a default constructor in Product model class
myCurrentProduct.setTitle(tempProduct.getTitle());
myCurrentProduct.setQuantity("5");
myCurrentProduct.setPrice("50000");
myCurrentProduct.setDiscount(tempProduct.getDiscount());
binding.setPopUpProduct(myCurrentProduct);

In this way I'm also able to get values from the clicked item, also set my own values.


问:
How to change label value based on two dropdown list in jquery
```<code><script>
   $(document).ready(function(){
   $("#method,#paper").on("change", function(){

               var paper= $('option:selected',this).text()
               var method = $('option:selected', this).text()

                   if (method == "1 month") {
                   $('#duration').html("150");
               } else if (method == "3 month" ) {
                   $('#duration').html("450");
               }
                 else if (method == "6 month"  ) {
                   $('#duration').html("900");
               }
                 else if (method == "1 year" ) {
                   $('#duration').html("1800");
               }

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

答:
try to use .text().

Details: https://api.jquery.com/text/

```<code>if (method == "1 month") {
  $('#duration').text("150");
}
</code>```

Body:
try to use .text().

Details: https://api.jquery.com/text/

if (method == "1 month") {
  $('#duration').text("150");
}


问:
How do you create dynamic rowspan tables in vuejs?
How do you render the following data into an html table with rowspans using vueJs?

Array

```<code>[
  {
    "id": 1,
    "name": "Dog",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 2,
    "name": "Cat",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 3,
    "name": "Fish",
    "param_id": null,
    "total": "55.000"
  },
  {
    "id": 4,
    "name": "Bird",
    "param_id": 2,
    "total": "75.000"
  }
]
</code>```

This is an example of the result

答:
First you may use Laravel Collection groupBy method to groups the collection's items by a given key ('total')

Controller code

```<code>//...

$myElequentCollection = Model::where(...)->get();

$grouped = $myElequentCollection->groupBy('total');

$data = $grouped->toArray();

//outpout
/*
    [
        '45.000' => [
            ['id' => '1', 'name' => 'Dog', ...],
            ['id' => '2', 'name' => 'Cat', ...],
        ],
        '55.000' => [
            ['id' => '3', 'name' => 'Fish', ...],
        ],
        '75.000' => [
            ['id' => '4', 'name' => 'Bird', ...],
        ],
    ]
*/

//...

return view('viewName', compact('data'));
</code>```

HTML code example

```<code><table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    @foreach($data as $item)
    @foreach($item as $row)
    <tr>
      <td> {{ $row['id'] }}</td>
      <td> {{ $row['name'] }}</td>
      @if($loop->first )
      <td rowspan="{{ count($item) }}">{{ $row['total'] }}</td>
      @else
      <td>{{ $row['total'] }}</td>
      @endif
    </tr>
    @enforeach
    @endforeach
  </tbody>
</table>
</code>```

Body:
How do you render the following data into an html table with rowspans using vueJs?

Array

[
  {
    "id": 1,
    "name": "Dog",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 2,
    "name": "Cat",
    "param_id": 5,
    "total": "45.000"
  },
  {
    "id": 3,
    "name": "Fish",
    "param_id": null,
    "total": "55.000"
  },
  {
    "id": 4,
    "name": "Bird",
    "param_id": 2,
    "total": "75.000"
  }
]

This is an example of the result

Body:
First you may use Laravel Collection groupBy method to groups the collection's items by a given key ('total')

Controller code

//...

$myElequentCollection = Model::where(...)->get();

$grouped = $myElequentCollection->groupBy('total');

$data = $grouped->toArray();

//outpout
/*
    [
        '45.000' => [
            ['id' => '1', 'name' => 'Dog', ...],
            ['id' => '2', 'name' => 'Cat', ...],
        ],
        '55.000' => [
            ['id' => '3', 'name' => 'Fish', ...],
        ],
        '75.000' => [
            ['id' => '4', 'name' => 'Bird', ...],
        ],
    ]
*/

//...

return view('viewName', compact('data'));

HTML code example

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    @foreach($data as $item)
    @foreach($item as $row)
    <tr>
      <td> {{ $row['id'] }}</td>
      <td> {{ $row['name'] }}</td>
      @if($loop->first )
      <td rowspan="{{ count($item) }}">{{ $row['total'] }}</td>
      @else
      <td>{{ $row['total'] }}</td>
      @endif
    </tr>
    @enforeach
    @endforeach
  </tbody>
</table>


问:
Run cron job once for entire application in Flask
I was looking at using APScheduler BackgroundScheduler to run a job every few seconds.

My question is if I put the Scheduler in my code, run it on the cloud and have thousands of users making requests,will the work of the scheduler be repeated?

To me it seems that for every process that Flask creates there will be a BackgroundScheduler thread running. Which means that on the cloud the work will be repeated.

If this is the case, is there a way to get around the issue without having to run some script in a separate machine. I would prefer to have the job in Flask mainly because of costs and maintainability.

答:
From an architecture perspective, what you want is some operations to be done on a database. Ideally, this should not be a part of your Flask application.

Flask is meant to be a webserver. It should be used just like a webserver. The task that you want to run should be run as a separate script using ApScheduler or anything else that you might need. There needs to be a separation between the two as they are not dependant on each other.

Assume that tomorrow your Flask application crashes, does it mean that your script should not run?

If your requirement would have been something like an endpoint where you get the time and task to schedule and then you need to be processed at that time, having APScheduler and Flask together would've made sense.