问:
Flutter StreamBuilder with Firestore Pagination
I'm trying to build a basic chat feature where all of a users chat messages are stored as documents in a "chats" collection. I have successfully implemented pagination to ensure I am not overpulling data until the user scrolls.

However, even though I have a StreamBuilder, new chat documents are not appearing automatically like they normally would. Why is the streambuilder not registering and displaying these new messages?

Here is my code:

```<code>class MotivatorChat extends StatefulWidget {
  @override
  _MotivatorChatState createState() => _MotivatorChatState();
}

class _MotivatorChatState extends State<MotivatorChat> {

  Firestore firestore = Firestore.instance;
  List<DocumentSnapshot> chats = [];
  bool isLoading = false;
  bool hasMore = true;
  int documentLimit = 10;
  DocumentSnapshot lastDocument;
  ScrollController _scrollController = ScrollController();

  StreamController<List<DocumentSnapshot>> _controller = StreamController<List<DocumentSnapshot>>();

  Stream<List<DocumentSnapshot>> get _streamController => _controller.stream;

  @override
  void initState() {
    super.initState();
    getChats();
    _scrollController.addListener(() {
      double maxScroll = _scrollController.position.maxScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll - currentScroll <= delta) {
        getChats();
      }

    });
  }

  getChats() async {
    if (!hasMore) {
      print('No More Chats');
      return;
    }
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    QuerySnapshot querySnapshot;
    if (lastDocument == null) {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .limit(documentLimit)
          .getDocuments();
    } else {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .startAfterDocument(lastDocument)
          .limit(documentLimit)
          .getDocuments();
      print(1);
    }
    if (querySnapshot.documents.length < documentLimit) {
      hasMore = false;
    }

    lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];

    chats.addAll(querySnapshot.documents);
    _controller.sink.add(chats);

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination with Firestore'),
      ),
      body: Column(children: [
        Expanded(
          child: StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasData && snapshot.data.length > 0) {
                return ListView.builder(
                  reverse: true,
                  controller: _scrollController,
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Container(
                        height: 20,
                        child: Text(snapshot.data[index].data['text']),
                      ),
                    );
                  },
                );
              } else {
                return Center(
                  child: Text('No Data...'),
                );
              }
            },
          ),
        ),
        isLoading
            ? Container(
          width: MediaQuery
              .of(context)
              .size
              .width,
          padding: EdgeInsets.all(5),
          color: Colors.yellowAccent,
          child: Text(
            'Loading',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        )
            : Container(),

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

Updated StreamBuilder

```<code>StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              if (snapshot.connectionState == ConnectionState.none) {
                return Text("None");
              } else if (snapshot.connectionState == ConnectionState.waiting) {
                return Text("Loading");
              } else if (snapshot.connectionState == ConnectionState.active) {
                if (snapshot.hasData && snapshot.data.length > 0) {
                  return ListView.builder(
                    reverse: true,
                    controller: _scrollController,
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Container(
                          height: 20,
                          child: Text(snapshot.data[index].data['text']),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(
                    child: Text('No Data...'),
                  );
                }
              } else {
                return Text("return list");
              }
            },
          ),
</code>```

答:
If hasMore is false, the stream will not sink new data.

don't check hasMore

```<code>//     if (!hasMore) {
//       print('No More Chats');
//       return;
//     }
</code>```

and check documents

```<code>//     if (querySnapshot.documents.length < documentLimit) {
//       hasMore = false;
//     }

    if (querySnapshot.documents.isEmpty) {
      print('No More Chats');
      setLoading(false);
      return;
    }
</code>```

I test on DartPad, It sends data every 3 seconds.

Body:
I'm trying to build a basic chat feature where all of a users chat messages are stored as documents in a "chats" collection. I have successfully implemented pagination to ensure I am not overpulling data until the user scrolls.

However, even though I have a StreamBuilder, new chat documents are not appearing automatically like they normally would. Why is the streambuilder not registering and displaying these new messages?

Here is my code:

class MotivatorChat extends StatefulWidget {
  @override
  _MotivatorChatState createState() => _MotivatorChatState();
}

class _MotivatorChatState extends State<MotivatorChat> {

  Firestore firestore = Firestore.instance;
  List<DocumentSnapshot> chats = [];
  bool isLoading = false;
  bool hasMore = true;
  int documentLimit = 10;
  DocumentSnapshot lastDocument;
  ScrollController _scrollController = ScrollController();

  StreamController<List<DocumentSnapshot>> _controller = StreamController<List<DocumentSnapshot>>();

  Stream<List<DocumentSnapshot>> get _streamController => _controller.stream;

  @override
  void initState() {
    super.initState();
    getChats();
    _scrollController.addListener(() {
      double maxScroll = _scrollController.position.maxScrollExtent;
      double currentScroll = _scrollController.position.pixels;
      double delta = MediaQuery.of(context).size.height * 0.20;
      if (maxScroll - currentScroll <= delta) {
        getChats();
      }

    });
  }

  getChats() async {
    if (!hasMore) {
      print('No More Chats');
      return;
    }
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    QuerySnapshot querySnapshot;
    if (lastDocument == null) {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .limit(documentLimit)
          .getDocuments();
    } else {
      querySnapshot = await firestore
          .collection('chats')
          .orderBy('timestamp', descending: true)
          .startAfterDocument(lastDocument)
          .limit(documentLimit)
          .getDocuments();
      print(1);
    }
    if (querySnapshot.documents.length < documentLimit) {
      hasMore = false;
    }

    lastDocument = querySnapshot.documents[querySnapshot.documents.length - 1];

    chats.addAll(querySnapshot.documents);
    _controller.sink.add(chats);

    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pagination with Firestore'),
      ),
      body: Column(children: [
        Expanded(
          child: StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasData && snapshot.data.length > 0) {
                return ListView.builder(
                  reverse: true,
                  controller: _scrollController,
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: EdgeInsets.only(top: 20),
                      child: Container(
                        height: 20,
                        child: Text(snapshot.data[index].data['text']),
                      ),
                    );
                  },
                );
              } else {
                return Center(
                  child: Text('No Data...'),
                );
              }
            },
          ),
        ),
        isLoading
            ? Container(
          width: MediaQuery
              .of(context)
              .size
              .width,
          padding: EdgeInsets.all(5),
          color: Colors.yellowAccent,
          child: Text(
            'Loading',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
        )
            : Container(),

      ]),
    );
  }
}

Updated StreamBuilder

StreamBuilder<List<DocumentSnapshot>>(
            stream: _streamController,
            builder: (sContext, snapshot) {
              if (snapshot.connectionState == ConnectionState.none) {
                return Text("None");
              } else if (snapshot.connectionState == ConnectionState.waiting) {
                return Text("Loading");
              } else if (snapshot.connectionState == ConnectionState.active) {
                if (snapshot.hasData && snapshot.data.length > 0) {
                  return ListView.builder(
                    reverse: true,
                    controller: _scrollController,
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Padding(
                        padding: EdgeInsets.only(top: 20),
                        child: Container(
                          height: 20,
                          child: Text(snapshot.data[index].data['text']),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(
                    child: Text('No Data...'),
                  );
                }
              } else {
                return Text("return list");
              }
            },
          ),

Body:
If hasMore is false, the stream will not sink new data.

don't check hasMore

//     if (!hasMore) {
//       print('No More Chats');
//       return;
//     }

and check documents

//     if (querySnapshot.documents.length < documentLimit) {
//       hasMore = false;
//     }

    if (querySnapshot.documents.isEmpty) {
      print('No More Chats');
      setLoading(false);
      return;
    }

I test on DartPad, It sends data every 3 seconds.


来源: stackexchange

问:
How to split a items inside a list, surrounded by brackets, seperated by ,
I have a string of plot ploints such as:

```<code>plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc
</code>```

But I want to split them into respective x and y's:

```<code>x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)
</code>```

I am unsure how to do this.

ContentLicense: CC BY-SA 4.0

Body:
I have a string of plot ploints such as:

plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc

But I want to split them into respective x and y's:

x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)

I am unsure how to do this.

Body:
plots = [(0, 1), (0, 2), (1, 4), (0.4, 0.8)]

x = [plot[0] for plot in plots]
y = [plot[1] for plot in plots]


问:
How to add font-awesome to Angular 2 + CLI project
I'm using Angular 2+ and Angular CLI.

How do I add font-awesome to my project?

答:
For Angular 9 using ng :

```<code>ng add @fortawesome/angular-fontawesome@0.6.x
</code>```

Look Here For More Information

ContentLicense: CC BY-SA 3.0

Body:
For Angular 9 using ng :

ng add @fortawesome/angular-fontawesome@0.6.x

Look Here For More Information


问:
I have imported Maven Project from Github to eclipse, inpom.xml dependencies showing underlined in red
When I run project facing an error, in pom.xml file artifact id showing underlined in red</p>

```<code>java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
</code>```

答:
Your current testng jar is missing org.testng.remote.AbstractRemoteTestNG.addListenermethod. I think your current testng dependency version is lower than 6.5.1 so You have to Update your testng maven dependency to a higher version. You can try with below testng version.

```<code><dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
    <scope>test</scope>
</dependency>
</code>```

Body:
When I run project facing an error, in pom.xml file artifact id showing underlined in red

java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Body:
Your current testng jar is missing org.testng.remote.AbstractRemoteTestNG.addListenermethod. I think your current testng dependency version is lower than 6.5.1 so You have to Update your testng maven dependency to a higher version. You can try with below testng version.

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
    <scope>test</scope>
</dependency>


问:
Why does HeapFree() not working as it should?
I created implementation in MVS without using CRT. I use HeapAlloc() and HeapFree() for allocating memory. My example should work without memory leak.

Here is my code:

```<code>LPCSTR byte2ch(BYTE* data, int size) {
    char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
    LPCSTR temp = (reinterpret_cast<char const*>(data));
    for (int i = 0; i < size; i++) {
        datas[i] = temp[i];
    }
    LPSTR tempo = datas;
    HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
    return tempo;
}

int EntryPoint()
{
    BYTE* buffer = 0;

    HANDLE hFile;
    DWORD dwBytesRead, dwBytesWritten, dwPos;

    if (hFile = CreateFileW(L"MinerFinder.exe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL))
    {
        LARGE_INTEGER size;
        GetFileSizeEx(hFile, &size);

        buffer = (BYTE*)HeapAlloc(GetProcessHeap(), NULL, size.QuadPart);
        ReadFile(hFile, buffer, size.QuadPart, &dwBytesRead, NULL);

        MessageBoxA(NULL, byte2ch(buffer, size.QuadPart), NULL, SW_SHOW);
        HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);
        MessageBoxA(NULL, "", NULL, SW_SHOW); // there I can see, that memory is leaking...
        CloseHandle(hFile);
    }

    ExitProcess(0);
}
</code>```

Where is my mistake?

EDIT 1:

```<code>LPCSTR byte2ch(BYTE* data, int size) {
        char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
        LPCSTR temp = (reinterpret_cast<char const*>(data));
        for (int i = 0; i < size; i++) {
            datas[i] = temp[i];
        }
        LPSTR tempo = datas;
        HeapFree(GetProcessHeap(), NULL, datas);
        return tempo;
    }
</code>```

there when I HeapFree() program suddenly crashes. What?

答:
Looking at HeapFree

BOOL HeapFree(
    HANDLE                 hHeap,
    DWORD                  dwFlags,
    _Frees_ptr_opt_ LPVOID lpMem
  );

lpMem

A pointer to the memory block to be freed. This pointer is returned by the HeapAlloc or HeapReAlloc function. If this pointer is NULL, the behavior is undefined.

In the code

```<code>HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);
</code>```

You don't give an allocated pointer to HeapFree, but a pointer to the address of some unrelated (non-heap) memory.

The proper call would be

```<code>HeapFree(GetProcessHeap(), NULL, datas);
</code>```

or

```<code>HeapFree(GetProcessHeap(), NULL, buffer);
</code>```

Body:
I created implementation in MVS without using CRT. I use HeapAlloc() and HeapFree() for allocating memory. My example should work without memory leak.

Here is my code:

LPCSTR byte2ch(BYTE* data, int size) {
    char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
    LPCSTR temp = (reinterpret_cast<char const*>(data));
    for (int i = 0; i < size; i++) {
        datas[i] = temp[i];
    }
    LPSTR tempo = datas;
    HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
    return tempo;
}

int EntryPoint()
{
    BYTE* buffer = 0;

    HANDLE hFile;
    DWORD dwBytesRead, dwBytesWritten, dwPos;

    if (hFile = CreateFileW(L"MinerFinder.exe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL))
    {
        LARGE_INTEGER size;
        GetFileSizeEx(hFile, &size);

        buffer = (BYTE*)HeapAlloc(GetProcessHeap(), NULL, size.QuadPart);
        ReadFile(hFile, buffer, size.QuadPart, &dwBytesRead, NULL);

        MessageBoxA(NULL, byte2ch(buffer, size.QuadPart), NULL, SW_SHOW);
        HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);
        MessageBoxA(NULL, "", NULL, SW_SHOW); // there I can see, that memory is leaking...
        CloseHandle(hFile);
    }

    ExitProcess(0);
}

Where is my mistake?

EDIT 1:

LPCSTR byte2ch(BYTE* data, int size) {
        char* datas = (char*)HeapAlloc(GetProcessHeap(), NULL, size);
        LPCSTR temp = (reinterpret_cast<char const*>(data));
        for (int i = 0; i < size; i++) {
            datas[i] = temp[i];
        }
        LPSTR tempo = datas;
        HeapFree(GetProcessHeap(), NULL, datas);
        return tempo;
    }

there when I HeapFree() program suddenly crashes. What?

Body:
Looking at HeapFree

BOOL HeapFree(
    HANDLE                 hHeap,
    DWORD                  dwFlags,
    _Frees_ptr_opt_ LPVOID lpMem
  );

lpMem

A pointer to the memory block to be freed. This pointer is returned by the HeapAlloc or HeapReAlloc function. If this pointer is NULL, the behavior is undefined.

In the code

HeapFree(GetProcessHeap(), NULL, (LPVOID)&size);
HeapFree(GetProcessHeap(), NULL, (LPVOID)&size.QuadPart);

You don't give an allocated pointer to HeapFree, but a pointer to the address of some unrelated (non-heap) memory.

The proper call would be

HeapFree(GetProcessHeap(), NULL, datas);

or

HeapFree(GetProcessHeap(), NULL, buffer);


问:
How do I get a CXF client to understand a List?
I'm using Apache CXF for my restful web services. I have a service defined by an interface that returns a list of my bean.

```<code>@Path("/")
@Produces("application/xml")
public interface MyService {

  @GET
  @Path("/test")
  public List<MyBean> getBeans() throws IOException;

}
</code>```

..and the service implementation is as such;

```<code>public class MyServiceImpl implements MyService {
  public List<MyBean> getBeans() {
     ArrayList<MyBean> beans = new ArrayList<MyBean>();
     beans.add(new MyBean("foo", "bar");
     return beans;
  }
}
</code>```

This is deployed on my server and works fine. I can hit the service in my browser and get the result I'd expect. The problem is when I try to get a CXF client to call the service.

In my client app I declare a client with the following spring config;

```<code>  <jaxrs:client id="myClient" inheritHeaders="true"
                 address="myhost/test"
                 serviceClass="com.example.MyService">
     <jaxrs:headers>
       <entry key="Accept" value="application/xml"/>
     </jaxrs:headers>
     <jaxrs:providers>
       <ref bean="myJaxbXmlProvider"/>
       <ref bean="myJsonProvider"/>
     </jaxrs:providers>
   </jaxrs:client>

   <bean id="myJaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
     <property name="jaxbElementClassMap" ref="myElementClassMap"/>
   </bean>
   <bean id="myJsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider">
     <property name="jaxbElementClassMap" ref="myElementClassMap"/>
   </bean>
   <util:map id="myElementClassMap">
     <entry key="com.example.MyBean" value="bean"/>
   </util:map>
</code>```

When the client is invoked I get this stacktrace;

org.apache.cxf.jaxrs.client.ClientWebApplicationException:
  .Problem with reading the response
  message, class : interface
  java.util.List, ContentType :
  application/xml.

  ....

  Caused by:
  javax.ws.rs.WebApplicationException:
  java.lang.ClassCastException:
  com.example.MyBean
  cannot be cast to
  org.apache.cxf.jaxrs.provider.AbstractJAXBProvider$CollectionWrapper

Any ideas?

答: This issue is fixed in CXF, qualify MBean class as a workround</p>

Body:
I'm using Apache CXF for my restful web services. I have a service defined by an interface that returns a list of my bean.

@Path("/")
@Produces("application/xml")
public interface MyService {

  @GET
  @Path("/test")
  public List<MyBean> getBeans() throws IOException;

}

..and the service implementation is as such;

public class MyServiceImpl implements MyService {
  public List<MyBean> getBeans() {
     ArrayList<MyBean> beans = new ArrayList<MyBean>();
     beans.add(new MyBean("foo", "bar");
     return beans;
  }
}

This is deployed on my server and works fine. I can hit the service in my browser and get the result I'd expect. The problem is when I try to get a CXF client to call the service.

In my client app I declare a client with the following spring config;

  <jaxrs:client id="myClient" inheritHeaders="true"
                 address="myhost/test"
                 serviceClass="com.example.MyService">
     <jaxrs:headers>
       <entry key="Accept" value="application/xml"/>
     </jaxrs:headers>
     <jaxrs:providers>
       <ref bean="myJaxbXmlProvider"/>
       <ref bean="myJsonProvider"/>
     </jaxrs:providers>
   </jaxrs:client>

   <bean id="myJaxbXmlProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
     <property name="jaxbElementClassMap" ref="myElementClassMap"/>
   </bean>
   <bean id="myJsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider">
     <property name="jaxbElementClassMap" ref="myElementClassMap"/>
   </bean>
   <util:map id="myElementClassMap">
     <entry key="com.example.MyBean" value="bean"/>
   </util:map>

When the client is invoked I get this stacktrace;

org.apache.cxf.jaxrs.client.ClientWebApplicationException:
  .Problem with reading the response
  message, class : interface
  java.util.List, ContentType :
  application/xml.

  ....

  Caused by:
  javax.ws.rs.WebApplicationException:
  java.lang.ClassCastException:
  com.example.MyBean
  cannot be cast to
  org.apache.cxf.jaxrs.provider.AbstractJAXBProvider$CollectionWrapper

Any ideas?


问:
How to get output of the nested loop in a data frame using r? And how to put a time loop?
I am new to r and work on boolean modelling - my nested loop gives output of 50 values of rtk in terms of 0 and 1, how to store this output in a dataframe , cbind is not working . Please help.
2. Also I would like to introduce a time loop ie if j = is 5 seconds I want rtk to change accoding to nwki value in i0 for j =1to 3 and for time j = 4,5 seconds i want rtk to change accoding to nwk value in i0

CODE IS AS FOLLOWS

```<code>library (BoolNet)#make sure lib is installed
library(igraph)
setwd("C:/Users/neha gopal/Desktop/IISC-mkj/r for boolean")#"

nwki<- loadNetwork("rtkufi.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
nwk<- loadNetwork("rtkuf.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
inc<-c(1,0,0,0,0,0,0,0,0,0)#vector
stF<- stateTransition(network=nwki,state= inc,type = "asynchronous")
stF
#loops working
rtk_values <-rep(0,50)# empty vector for total no of rtk  output values
rtk_values
ts<- 10
for (i in 1:ts)# trajectories i=10
{
  i0 <- inc
  rtk_values <-rep(0,50)
  rtk <- i0[2]

tr<-5 #time j=5

for (j in 1:tr)
{

  i0 <- stateTransition(network=nwki,state= i0,type = "asynchronous")
  rtk <- i0[2]
  print (paste0( ",Im in J and my j is ", j, " and my i is", i,"rtk is" , rtk ))

}

}

#table  NOT working

rtk_values[j]= rtk
rtk_table <- cbind.data.frame( rtk_values, rtk)
</code>```

答:
The best way to ask a question is to provide a reproducible example. If your question is how to store variables from a for loop, this would be a way of doing it:

```<code>result <- list() # initalize an empty list

for (i in 1:10){
  result[[i]] <- i # populate list with every loop
}
</code>```

The same system can be used for nested loops:

```<code>result <- list()
for (i in 1:10){
  result_nested <- list() # initialize an empty list within the loop
  for (nested in 1:5){
    result_nested[[nested]] <- nested # populate the results from the nested loop.
  }
  result[[i]] <- result_nested # populate the result from the nested loop to the parent loop
}
</code>```

Body:
I am new to r and work on boolean modelling - my nested loop gives output of 50 values of rtk in terms of 0 and 1, how to store this output in a dataframe , cbind is not working . Please help.
2. Also I would like to introduce a time loop ie if j = is 5 seconds I want rtk to change accoding to nwki value in i0 for j =1to 3 and for time j = 4,5 seconds i want rtk to change accoding to nwk value in i0

CODE IS AS FOLLOWS

library (BoolNet)#make sure lib is installed
library(igraph)
setwd("C:/Users/neha gopal/Desktop/IISC-mkj/r for boolean")#"

nwki<- loadNetwork("rtkufi.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
nwk<- loadNetwork("rtkuf.txt",bodySeparator =",",lowercaseGenes = FALSE)#"
inc<-c(1,0,0,0,0,0,0,0,0,0)#vector
stF<- stateTransition(network=nwki,state= inc,type = "asynchronous")
stF
#loops working
rtk_values <-rep(0,50)# empty vector for total no of rtk  output values
rtk_values
ts<- 10
for (i in 1:ts)# trajectories i=10
{
  i0 <- inc
  rtk_values <-rep(0,50)
  rtk <- i0[2]

tr<-5 #time j=5

for (j in 1:tr)
{

  i0 <- stateTransition(network=nwki,state= i0,type = "asynchronous")
  rtk <- i0[2]
  print (paste0( ",Im in J and my j is ", j, " and my i is", i,"rtk is" , rtk ))

}

}

#table  NOT working

rtk_values[j]= rtk
rtk_table <- cbind.data.frame( rtk_values, rtk)

Body:
The best way to ask a question is to provide a reproducible example. If your question is how to store variables from a for loop, this would be a way of doing it:

result <- list() # initalize an empty list

for (i in 1:10){
  result[[i]] <- i # populate list with every loop
}

The same system can be used for nested loops:

result <- list()
for (i in 1:10){
  result_nested <- list() # initialize an empty list within the loop
  for (nested in 1:5){
    result_nested[[nested]] <- nested # populate the results from the nested loop.
  }
  result[[i]] <- result_nested # populate the result from the nested loop to the parent loop
}


问:
Ktor application not running on my computer
I am trying to learn to use ktor and I'm trying to display the text "Hello Ktor" at the root path but all I keep getting is this site can't be reached.
This is my code:

```<code>import io.ktor.application.*
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

private val userData = "{\"users\": [\"Timi\", \"Tomi\", \"Temi\"]}"

@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {

    routing {
        get("/") {
            call.respondText("Hello Ktor", ContentType.Text.Plain)
        }

    }
}

</code>```

What am I doing wrong?

答:
Are you trying to run without a main?

Did you follow this guide? https://ktor.io/quickstart/quickstart/gradle.html#intellij-extract-out-configuration-data

If you want to start from main, use embeddedServer. Otherwise you have to set the mainClassName.

Body:
I am trying to learn to use ktor and I'm trying to display the text "Hello Ktor" at the root path but all I keep getting is this site can't be reached.
This is my code:

import io.ktor.application.*
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.get
import io.ktor.routing.routing

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

private val userData = "{\"users\": [\"Timi\", \"Tomi\", \"Temi\"]}"

@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {

    routing {
        get("/") {
            call.respondText("Hello Ktor", ContentType.Text.Plain)
        }

    }
}

What am I doing wrong?


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答:
looping over it with a while loop and counting the ';' is probably going to be the fastest, and the most readable.

Consider Konrad's suggestions, that too will loop through the string and check every char and see if it is a simicolon, and then in modifies the string (may or may not be mutable, I don't know with excel), and then it counts the length between it and the original string.

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: Malfist


问:
CakePHP Updating status Twitter and Facebook
I was wondering how I can make a full Twitter and Facebook status updater in CakePHP.

Does anyone ideas to make this or examples.

I read the API reference but I can't find where I should start.

I hope you will have an example.

Many Thanks!

答:
For Twitter see:

See: http://hiteshanjara.com/cakephp/update-twitter-status-in-cakephp/

and: http://www.web7.co/update-twitter-status-remotely-cakephp-component/

And here's a link for Facebook:

http://www.webtechnick.com/blogs/view/229/CakePHP_Facebook_Plugin_Auth_Facebook_and_more


问:
Is midipolyaftertouch broken in csound?
I'm not having much luck with the midipolyaftertouch opcode. Basically

```<code>kPea init 0.1
midipolyaftertouch kPea, 1, 0.1, 0.9
printk2 kPea
</code>```

does not actually respond to polyphonic aftertouch messages. On the other hand, a manually coded rough equivalent

```<code>kPea init 0.1
kstatus,kchan,kdata1,kdata2 midiin
if (kstatus==160 && kchan==1) then
    kPea = kdata2 * 0.007
    printk2 kPea
endif
</code>```

works fine. So is this a known bug in midipolyaftertouch ? I can't find any usage examples for midipolyaftertouch, besides those from the manual, so I'm guess hardly anyone used it... By the way aftouch gets the channel not the per-note after-touch (pressure), i.e. aftouch queries kstatus == 208 (and actually does work, but of course it's not per note). For the difference see this.

I'm using Csound version 6.13 beta from inside Cabbage 2.3.0 on Windows (because that's what ships with that version of Cabbage).

答:
There's another opcode namely polyaft that actually works, following the documentation

```<code>kPea init 0.1
inote   notnum          ; note number
kPea    polyaft inote, 0.1, 0.9
printk2 kPea
</code>```

Looking at the C source for midipolyaftertouch it is actually indexed exactly the same way as for polyaft. So based on that I tried:

```<code>kPea init 0.1
inote   notnum          ; note number
midipolyaftertouch kPea, inote, 0.1, 0.9
printk2 kPea
</code>```

and this actually works too.

In the MIDI API jargon, "MIDI controller [number]" (usually) means key/note [number]... unlike in world of DAWs where one uses e.g. "multiple MIDI controllers" to mean several keyboards, not several keys of the same keyboard... Also, Csound has a notion of multiple controllers in the latter/DAW sense, selected by the -M startup switch, although it calls them "MIDI devices".

The code example for midipolyaftertouch from the documentation can't possibly work unless you just try it with D0 as the key/note; insert joke about the broken clock here. Interestingly the documentation was written by the source code author for that opcode, so it wasn't a case of someone else misunderstanding the code...

Title: Is midipolyaftertouch broken in csound?

Body:
I'm not having much luck with the midipolyaftertouch opcode. Basically

kPea init 0.1
midipolyaftertouch kPea, 1, 0.1, 0.9
printk2 kPea

does not actually respond to polyphonic aftertouch messages. On the other hand, a manually coded rough equivalent

kPea init 0.1
kstatus,kchan,kdata1,kdata2 midiin
if (kstatus==160 && kchan==1) then
    kPea = kdata2 * 0.007
    printk2 kPea
endif

works fine. So is this a known bug in midipolyaftertouch ? I can't find any usage examples for midipolyaftertouch, besides those from the manual, so I'm guess hardly anyone used it... By the way aftouch gets the channel not the per-note after-touch (pressure), i.e. aftouch queries kstatus == 208 (and actually does work, but of course it's not per note). For the difference see this.

I'm using Csound version 6.13 beta from inside Cabbage 2.3.0 on Windows (because that's what ships with that version of Cabbage).

Body:
There's another opcode namely polyaft that actually works, following the documentation

kPea init 0.1
inote   notnum          ; note number
kPea    polyaft inote, 0.1, 0.9
printk2 kPea

Looking at the C source for midipolyaftertouch it is actually indexed exactly the same way as for polyaft. So based on that I tried:

kPea init 0.1
inote   notnum          ; note number
midipolyaftertouch kPea, inote, 0.1, 0.9
printk2 kPea

and this actually works too.

In the MIDI API jargon, "MIDI controller [number]" (usually) means key/note [number]... unlike in world of DAWs where one uses e.g. "multiple MIDI controllers" to mean several keyboards, not several keys of the same keyboard... Also, Csound has a notion of multiple controllers in the latter/DAW sense, selected by the -M startup switch, although it calls them "MIDI devices".

The code example for midipolyaftertouch from the documentation can't possibly work unless you just try it with D0 as the key/note; insert joke about the broken clock here. Interestingly the documentation was written by the source code author for that opcode, so it wasn't a case of someone else misunderstanding the code...


问:
How to have colors based PolyLine on folium
I try to have the path of a race with different colors according to the speed (as do applications like Strava) using folium.

I saw that you could change the colors of the markers according to the data but I can't transpose it with PolyLines.

Here is the code of my visualization :

points = []
for track in gpx.tracks:
    for segment in track.segments:
        for point in segment.points:
            points.append(tuple([point.latitude, point.longitude]))

ave_lat = sum(p[0] for p in points)/len(points)
ave_lon = sum(p[1] for p in points)/len(points)

my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=13)
folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(my_map)
```

I also have a dataframe with longitude, latitude and speed and I would like the line to change color according to the speed.

答:
The PolyLine function does not have a built in method that does this for you. The color argument needs a string value: "red" or "#FF0000". Therefore the easiest way I know is to create a dictionary with rounded speed as key and desired color hex code as value:

Given a dataframe containing coordinates:

```<code>>>> coordinates = {'lat':[52.354, 52.081, 52.384], 'lng':[4.903, 5.099, 4.643]}
>>> df = pd.DataFrame(data=coordinates, index=['Amsterdam', 'Utrecht', 'Haarlem'])
>>> df
              lat    lng
Amsterdam  52.354  4.903
Utrecht    52.081  5.099
Haarlem    52.384  4.643
</code>```

And a dictionary containing the speeds between these:

```<code>>>> dict_speed = {}
>>> cities_all = df.index.to_list()
>>>
>>> for origin in df.index:
...     dict_speed[origin] = {
...         desti: np.random.uniform(3, 30) for desti in cities_all if origin != desti
...     }
...     cities_all.remove(origin)
...
>>> dict_speed
{'Amsterdam': {'Utrecht': 11.17300608896625, 'Haarlem': 28.078139459927645},
 'Utrecht': {'Haarlem': 17.07939077211872},
 'Haarlem': {}}
</code>```

Final ingredient: the mapping dictionary that gives us a desired color for the given speed, using this link (http://blogs.perl.org/users/ovid/2010/12/perl101-red-to-green-gradient.html)
:

```<code>list_colors = [
    "#00FF00",
    "#12FF00",
    "#24FF00",
    "#35FF00",
    "#47FF00",
    "#58FF00",
    "#6AFF00",
    "#7CFF00",
    "#8DFF00",
    "#9FFF00",
    "#B0FF00",
    "#C2FF00",
    "#D4FF00",
    "#E5FF00",
    "#F7FF00",
    "#FFF600",
    "#FFE400",
    "#FFD300",
    "#FFC100",
    "#FFAF00",
    "#FF9E00",
    "#FF8C00",
    "#FF7B00",
    "#FF6900",
    "#FF5700",
    "#FF4600",
    "#FF3400",
    "#FF2300",
    "#FF1100",
    "#FF0000",
]
color_dict = {i: list_colors[i] for i in range(len(list_colors))}
</code>```

And the plotting code:

```<code>my_map = folium.Map(
    location=[np.mean(df["lat"].values), np.mean(df["lng"].values)],
    zoom_start=7,
    tiles="Stamen Terrain",
)

for city, row in df.iterrows():
    folium.Marker([row["lat"], row["lng"]], tooltip=city).add_to(my_map)

for origin, _ in dict_speed.items():
    for desti, speed in _.items():
        folium.PolyLine(
            (df.loc[origin].values, df.loc[desti].values),
            color=color_dict[round(speed)],
        ).add_to(my_map)

my_map
</code>```

You get a folium map with color indicating the speed!

'

<iframe src="data:text/html;charset=utf-8;base64,[encoded data, 7928 characters]" style="position:absolute;width:100%;height:100%;left:0;top:0;border:none !important;" allowfullscreen webkitallowfullscreen mozallowfullscreen>

'```

Body:
I try to have the path of a race with different colors according to the speed (as do applications like Strava) using folium.

I saw that you could change the colors of the markers according to the data but I can't transpose it with PolyLines.

Here is the code of my visualization :

points = []
for track in gpx.tracks:
    for segment in track.segments:
        for point in segment.points:
            points.append(tuple([point.latitude, point.longitude]))

ave_lat = sum(p[0] for p in points)/len(points)
ave_lon = sum(p[1] for p in points)/len(points)

my_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=13)
folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(my_map)

I also have a dataframe with longitude, latitude and speed and I would like the line to change color according to the speed.

Body:
The PolyLine function does not have a built in method that does this for you. The color argument needs a string value: "red" or "#FF0000". Therefore the easiest way I know is to create a dictionary with rounded speed as key and desired color hex code as value:

Given a dataframe containing coordinates:

>>> coordinates = {'lat':[52.354, 52.081, 52.384], 'lng':[4.903, 5.099, 4.643]}
>>> df = pd.DataFrame(data=coordinates, index=['Amsterdam', 'Utrecht', 'Haarlem'])
>>> df
              lat    lng
Amsterdam  52.354  4.903
Utrecht    52.081  5.099
Haarlem    52.384  4.643

And a dictionary containing the speeds between these:

>>> dict_speed = {}
>>> cities_all = df.index.to_list()
>>>
>>> for origin in df.index:
...     dict_speed[origin] = {
...         desti: np.random.uniform(3, 30) for desti in cities_all if origin != desti
...     }
...     cities_all.remove(origin)
...
>>> dict_speed
{'Amsterdam': {'Utrecht': 11.17300608896625, 'Haarlem': 28.078139459927645},
 'Utrecht': {'Haarlem': 17.07939077211872},
 'Haarlem': {}}

Final ingredient: the mapping dictionary that gives us a desired color for the given speed, using this link (http://blogs.perl.org/users/ovid/2010/12/perl101-red-to-green-gradient.html)
:

list_colors = [
    "#00FF00",
    "#12FF00",
    "#24FF00",
    "#35FF00",
    "#47FF00",
    "#58FF00",
    "#6AFF00",
    "#7CFF00",
    "#8DFF00",
    "#9FFF00",
    "#B0FF00",
    "#C2FF00",
    "#D4FF00",
    "#E5FF00",
    "#F7FF00",
    "#FFF600",
    "#FFE400",
    "#FFD300",
    "#FFC100",
    "#FFAF00",
    "#FF9E00",
    "#FF8C00",
    "#FF7B00",
    "#FF6900",
    "#FF5700",
    "#FF4600",
    "#FF3400",
    "#FF2300",
    "#FF1100",
    "#FF0000",
]
color_dict = {i: list_colors[i] for i in range(len(list_colors))}

And the plotting code:

my_map = folium.Map(
    location=[np.mean(df["lat"].values), np.mean(df["lng"].values)],
    zoom_start=7,
    tiles="Stamen Terrain",
)

for city, row in df.iterrows():
    folium.Marker([row["lat"], row["lng"]], tooltip=city).add_to(my_map)

for origin, _ in dict_speed.items():
    for desti, speed in _.items():
        folium.PolyLine(
            (df.loc[origin].values, df.loc[desti].values),
            color=color_dict[round(speed)],
        ).add_to(my_map)

my_map

You get a folium map with color indicating the speed!

'<div style="width:100%;"><div style="position:relative;width:100%;height:0;padding-bottom:60%;"><iframe src="data:text/html;charset=utf-8;base64,[encoded data, 7928 characters]" style="position:absolute;width:100%;height:100%;left:0;top:0;border:none !important;" allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe></div></div>'


问:
error in compilation process when run spring boot project
during the debugging and compiling , there is not error but when I build project is says this error.

```<code>org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
        at uz.esm.esmserver.EsmApplication.main(EsmApplication.java:15)
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:202)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152)
        ... 8 common frames omitted
</code>```

my main class

```<code>

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import uz.esm.esmserver.config.InitConfig;

@SpringBootApplication
@EnableScheduling
public class EsmApplication {
        public static void main(String[] args) {
            if (InitConfig.isStart()){
                SpringApplication.run(EsmApplication.class, args);
            }else {
                System.err.println("Enter info before starting");
            }
        }
    }
</code>```

initConfig class (it is just for simple configuration. we can remove it also but it didint solve problem

```<code>
    public static boolean isStart(){
        Properties props = new Properties();
        try {
            props.load(new ClassPathResource("/application.properties").getInputStream());
            if (props.getProperty("spring.jpa.hibernate.ddl-auto").equals("update")){
                return true;
            }else{
                String confirm = JOptionPane.showInputDialog("Ma'lumotlarni o'chirib yuborma! Keyin bilmay qoldim dema! Agar rostdan ham o'chirmoqchi bo'lsang. O'chirish kodi (DROP_PDP_DATABASE) :");
                if (confirm!=null && confirm.equals("DROP_PDP_DATABASE")){
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
</code>```

pom.xls file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>esm-server</groupId>
    <artifactId>uz.esm.esmserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>uz.esm.esmserver</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->

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

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>6.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>15.0</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

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

</project>
</code>```

it is working when I compile the code but when I create artifact and make jar file and run it by cmd it gives error

答:
In Application properties add</p>

```<code>spring.main.web-application-type=none
</code>```

Body:
during the debugging and compiling , there is not error but when I build project is says this error.

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
        at uz.esm.esmserver.EsmApplication.main(EsmApplication.java:15)
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:202)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178)
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152)
        ... 8 common frames omitted

my main class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import uz.esm.esmserver.config.InitConfig;

@SpringBootApplication
@EnableScheduling
public class EsmApplication {
        public static void main(String[] args) {
            if (InitConfig.isStart()){
                SpringApplication.run(EsmApplication.class, args);
            }else {
                System.err.println("Enter info before starting");
            }
        }
    }

initConfig class (it is just for simple configuration. we can remove it also but it didint solve problem

    public static boolean isStart(){
        Properties props = new Properties();
        try {
            props.load(new ClassPathResource("/application.properties").getInputStream());
            if (props.getProperty("spring.jpa.hibernate.ddl-auto").equals("update")){
                return true;
            }else{
                String confirm = JOptionPane.showInputDialog("Ma'lumotlarni o'chirib yuborma! Keyin bilmay qoldim dema! Agar rostdan ham o'chirmoqchi bo'lsang. O'chirish kodi (DROP_PDP_DATABASE) :");
                if (confirm!=null && confirm.equals("DROP_PDP_DATABASE")){
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

pom.xls file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>esm-server</groupId>
    <artifactId>uz.esm.esmserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>uz.esm.esmserver</name>
    <description>Demo project for Spring Boot</description>

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

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

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

            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-browser</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>6.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>15.0</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

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

</project>

it is working when I compile the code but when I create artifact and make jar file and run it by cmd it gives error

Body:
In Application properties add

spring.main.web-application-type=none


问:
ASP .NET Core Web Server console output not visible in VS for .NET Core 2.2
I created a .NET Core 2.2 web application project in VS 2017 and the ASP.NET Core Web Server option from the console output is not visible when the application runs with IIS Express.

By .NET Core 2.1 web application projects this option is there and it is showing the output without any problems.

答:
I think you have to right-click on Project->Properties.
Then on the right side menu to select "Debug".
In Web Server Settings find "Hosting Model" and select "Out of process"


问:
How to: Stop ListView from rebuilding video_player widget?
I have managed to get a video to play on flutter-web, however, when I scroll the video in the ListView will rebuild/reload.

How can I stop the video_player (in the ListView) from being rebuilt when I scroll?

Sorry for the lengthy code sample.. I'm not sure how to condense it further

Any help would be great! Thanks

```<code>import 'package:flutter/material.dart';
import '../../widgets/video/chewie_video.dart';
import 'package:video_player/video_player.dart';

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: <Widget>[
          Container(height: 1000),
          Center(
            child: ChewieVideo(
              videoPlayerController:
                  VideoPlayerController.asset('assets/video.mp4'),
            ),
          ),
          Container(height: 1000),
        ],
      ),
    );
  }
}
</code>```

```<code>import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class ChewieVideo extends StatefulWidget {
  final VideoPlayerController videoPlayerController;
  final bool looping;

  ChewieVideo({
    @required this.videoPlayerController,
    this.looping,
    Key key,
  }) : super(key: key);

  @override
  _ChewieVideoState createState() => _ChewieVideoState();
}

class _ChewieVideoState extends State<ChewieVideo> {
  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    _chewieController = ChewieController(
      videoPlayerController: widget.videoPlayerController,
      autoInitialize: true,
      aspectRatio: 16 / 9,
      looping: widget.looping,
      errorBuilder: (context, errorMessage) {
        return Center(
          child: Text(
            errorMessage,
            style: TextStyle(color: Colors.white),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    widget.videoPlayerController.dispose();
    _chewieController.dispose();
  }
}
</code>```

答:
I'm not sure if this is a good or just temporary fix but this is how I have managed to get it to work...

If you are using inside of a ListView/CustomScrollView, then you need to adjust the cacheExtent for either of these widgets... I have set mine to 1000.

I'm not quite sure what's happening but it works...

```<code>class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: primaryBlack,
      drawer: NavDrawer(),
      body: Scrollbar(
        child: CustomScrollView(
          cacheExtent: 1000,
          slivers: <Widget>[

...
</code>```

after doing that chewie and video_player plugins shouldn't rebuild/refresh inside of a ListView

Body:
I have managed to get a video to play on flutter-web, however, when I scroll the video in the ListView will rebuild/reload.

How can I stop the video_player (in the ListView) from being rebuilt when I scroll?

Sorry for the lengthy code sample.. I'm not sure how to condense it further

Any help would be great! Thanks

import 'package:flutter/material.dart';
import '../../widgets/video/chewie_video.dart';
import 'package:video_player/video_player.dart';

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: <Widget>[
          Container(height: 1000),
          Center(
            child: ChewieVideo(
              videoPlayerController:
                  VideoPlayerController.asset('assets/video.mp4'),
            ),
          ),
          Container(height: 1000),
        ],
      ),
    );
  }
}

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class ChewieVideo extends StatefulWidget {
  final VideoPlayerController videoPlayerController;
  final bool looping;

  ChewieVideo({
    @required this.videoPlayerController,
    this.looping,
    Key key,
  }) : super(key: key);

  @override
  _ChewieVideoState createState() => _ChewieVideoState();
}

class _ChewieVideoState extends State<ChewieVideo> {
  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    _chewieController = ChewieController(
      videoPlayerController: widget.videoPlayerController,
      autoInitialize: true,
      aspectRatio: 16 / 9,
      looping: widget.looping,
      errorBuilder: (context, errorMessage) {
        return Center(
          child: Text(
            errorMessage,
            style: TextStyle(color: Colors.white),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    widget.videoPlayerController.dispose();
    _chewieController.dispose();
  }
}

Body:
I'm not sure if this is a good or just temporary fix but this is how I have managed to get it to work...

If you are using inside of a ListView/CustomScrollView, then you need to adjust the cacheExtent for either of these widgets... I have set mine to 1000.

I'm not quite sure what's happening but it works...

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: primaryBlack,
      drawer: NavDrawer(),
      body: Scrollbar(
        child: CustomScrollView(
          cacheExtent: 1000,
          slivers: <Widget>[

...

after doing that chewie and video_player plugins shouldn't rebuild/refresh inside of a ListView


问:
Can't set background color in tkinter
```<code>from tkinter import *

root = Tk()

def myClick():
    myLabel = Label(root, text='Button clicked. ')
    myLabel.pack()

myButton = Button(root, text="Click me!", command=myClick, fg='blue', background="red", activeforeground='green', activebackground='black')

myButton.pack()
root.mainloop()
</code>```

The code runs fine except the background color. Could someone help? Many thanks
BTW, I'm using Python 3.7.4 and macOS Catalina 10.15.2

答: On python 3.8 and windows 7 at least is work fine. Style can work to, but with what u set is text color blue and background red, when the button is pressed the text will become green and the background black.</p>

Title: Can't set background color in tkinter

Body:
from tkinter import *

root = Tk()

def myClick():
    myLabel = Label(root, text='Button clicked. ')
    myLabel.pack()

myButton = Button(root, text="Click me!", command=myClick, fg='blue', background="red", activeforeground='green', activebackground='black')

myButton.pack()
root.mainloop()

The code runs fine except the background color. Could someone help? Many thanks
BTW, I'm using Python 3.7.4 and macOS Catalina 10.15.2


问:
Finding the criterion of the Features in Binary Classification
I have done a binary classification using DRF in h2o. I have got the feature importance, then I have asked to find the criterion of each feature.

E.g: I have to classify the user which to accept and which to reject and the features are age, salary, work_experience, live city (already decoded of course). So, my boss wanted to know which range of ages is the tendency of users got rejected or accepted, which range of salaries, which cities that have tendency got rejected or accepted.

I can't be wrong but the output I want may look like:

```<code>Tendency salary for accepted user = 10k - 50k
Tendency salary for accepted user = 5k - 30k

Tendency age for accepted user = 18 - 55
Tendency age for rejected user = 31 - 35

Tendency cities for accepted user = 1, 5, 10, 23
Tendency cities for rejected user = 3, 4, 12, 36

so on..
</code>```

How to achieve it?

p.s: I have a list of accepted users.

答:
I think you need something like Partial Dependency Plots.
Here is an example in H2O: https://rdrr.io/cran/h2o/man/h2o.partialPlot.html

PDP will show how the probability of target depends on the value of a certain variable.

Body:
I have done a binary classification using DRF in h2o. I have got the feature importance, then I have asked to find the criterion of each feature.

E.g: I have to classify the user which to accept and which to reject and the features are age, salary, work_experience, live city (already decoded of course). So, my boss wanted to know which range of ages is the tendency of users got rejected or accepted, which range of salaries, which cities that have tendency got rejected or accepted.

I can't be wrong but the output I want may look like:

Tendency salary for accepted user = 10k - 50k
Tendency salary for accepted user = 5k - 30k

Tendency age for accepted user = 18 - 55
Tendency age for rejected user = 31 - 35

Tendency cities for accepted user = 1, 5, 10, 23
Tendency cities for rejected user = 3, 4, 12, 36

so on..

How to achieve it?

p.s: I have a list of accepted users.


问:
Spring boot RabbitMQ give exception Error creating bean with name 'connectionFactory' defined in class path resource
I'm using Jhipster to consume message from RabbitMQ, When I run the code locally using the IDE it works without issue however when build the project using (mvn clean install) command, I'm getting many exception.

Hint 1:
I'm retrieving the configuration parameters from .yaml file, however when write parameters  in side the code the project works and build without issues.

Hint 2:
when remove RabbitListener calls the project build without issues.

exception like below:

```<code>Error creating bean with name 'connectionFactory' defined in class path resource [com/config/RabbitConfig.java] Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException

org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'; nested exception is org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:185)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:893)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassTestDescriptor.java:349)
    at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:215)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassTestDescriptor.java:349)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:313)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:647)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:348)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:270)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$0(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:69)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Caused by: org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.waitForConsumersToStart(SimpleMessageListenerContainer.java:558)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doStart(SimpleMessageListenerContainer.java:516)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:1296)
    at org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry.startIfNecessary(RabbitListenerEndpointRegistry.java:299)
    at org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry.start(RabbitListenerEndpointRegistry.java:249)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182)
    ... 67 common frames omitted
Caused by: org.springframework.amqp.rabbit.listener.exception.FatalListenerStartupException: Authentication failure
    at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:564)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.initialize(SimpleMessageListenerContainer.java:1201)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1046)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:65)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:530)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:702)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:215)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils$RabbitResourceFactory.createConnection(ConnectionFactoryUtils.java:294)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.doGetTransactionalResourceHolder(ConnectionFactoryUtils.java:131)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:93)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:76)
    at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:558)
    ... 3 common frames omitted
Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:362)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1104)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1218)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:492)
    ... 10 common frames omitted
</code>```

My code as below

```<code>@Configuration
@ConfigurationProperties("rabbitmq")
public class RabbitConfig {
    private String environment;
    private String host;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }

    @Bean
    ConnectionFactory connectionFactory() throws java.io.IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(getHost());
        connectionFactory.setUsername(getUsername());
        connectionFactory.setPassword(getPassword());
        return connectionFactory;
    }

}

@Service
public class RabbitListener{

    private final Logger log = LoggerFactory.getLogger(RabbitListener.class);

    @org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "queueName")
    public void receiveMessageFromTopic(Message message){
        String MQMessage =new String(message.getBody());
        log.info("RabbitMQ consuming Messages ....");
        log.debug(MQMessage);
    }

}
</code>```

答:
You're having

```<code>Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
</code>```

which is quite clear message, but check this anyways.

Body:
I'm using Jhipster to consume message from RabbitMQ, When I run the code locally using the IDE it works without issue however when build the project using (mvn clean install) command, I'm getting many exception.

Hint 1:
I'm retrieving the configuration parameters from .yaml file, however when write parameters  in side the code the project works and build without issues.

Hint 2:
when remove RabbitListener calls the project build without issues.

exception like below:

Error creating bean with name 'connectionFactory' defined in class path resource [com/config/RabbitConfig.java] Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException

org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.amqp.rabbit.config.internalRabbitListenerEndpointRegistry'; nested exception is org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:185)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:893)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:552)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassTestDescriptor.java:349)
    at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:215)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassTestDescriptor.java:349)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:313)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
    at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:647)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:348)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:270)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$0(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:83)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:69)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150)
    at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Caused by: org.springframework.amqp.AmqpIllegalStateException: Fatal exception on listener startup
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.waitForConsumersToStart(SimpleMessageListenerContainer.java:558)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doStart(SimpleMessageListenerContainer.java:516)
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.start(AbstractMessageListenerContainer.java:1296)
    at org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry.startIfNecessary(RabbitListenerEndpointRegistry.java:299)
    at org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry.start(RabbitListenerEndpointRegistry.java:249)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182)
    ... 67 common frames omitted
Caused by: org.springframework.amqp.rabbit.listener.exception.FatalListenerStartupException: Authentication failure
    at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:564)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.initialize(SimpleMessageListenerContainer.java:1201)
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1046)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.amqp.AmqpAuthenticationException: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
    at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:65)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:530)
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:702)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:215)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils$RabbitResourceFactory.createConnection(ConnectionFactoryUtils.java:294)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.doGetTransactionalResourceHolder(ConnectionFactoryUtils.java:131)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:93)
    at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.getTransactionalResourceHolder(ConnectionFactoryUtils.java:76)
    at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:558)
    ... 3 common frames omitted
Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:362)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1104)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1054)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1218)
    at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:492)
    ... 10 common frames omitted

My code as below

@Configuration
@ConfigurationProperties("rabbitmq")
public class RabbitConfig {
    private String environment;
    private String host;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }

    @Bean
    ConnectionFactory connectionFactory() throws java.io.IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(getHost());
        connectionFactory.setUsername(getUsername());
        connectionFactory.setPassword(getPassword());
        return connectionFactory;
    }

}

@Service
public class RabbitListener{

    private final Logger log = LoggerFactory.getLogger(RabbitListener.class);

    @org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "queueName")
    public void receiveMessageFromTopic(Message message){
        String MQMessage =new String(message.getBody());
        log.info("RabbitMQ consuming Messages ....");
        log.debug(MQMessage);
    }

}

Body:
You're having

Caused by: com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.

which is quite clear message, but check this anyways.