问:
How to Access Many to many field in class based views in Django?
I have two models, Author & Book in models.py

```<code>class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

def __str__(self):
    return '%s %s' %(self.first_name, self.last_name)

def __unicode__(self):
    return '%s %s' %(self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100) #name = title
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    author = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

def __str__(self):
    return self.title

def __unicode__(self):
    return self.title
</code>```

Now i'm listing all the books using ListView. And on click of a book i'm getting information the book using following method

```<code>class BookDetailView(generic.DetailView):
    template_name = 'books/book_detail1.html'
    model = Book
    context_object_name = 'book_detail'
</code>```

I'm able to access title, pages, price, rating, publisher & publication_date but not getting all the Authors(Author list). While i'm going to simply print it, it prints None in template. I even try to iterate using For Loop but not done in template

views.py

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<ul>
    <li>Price:{{ book_detail.price }}</li>
    <li>Pub Date:{{ book_detail.publication_date }}</li>
    <li>Title: {{ book_detail.title }}</li>
    <li>Pages: {{ book_detail.pages }}</li>
    <li>Rating: {{ book_detail.rating }}</li>
    <li>Publisher: {{ book_detail.publisher }}</li>
    <li>Author: {{ book_detail.author }}</li>
</ul>

</body>
</html>
</code>```

Can anyone help me to out from this?

答:
Or if you use Function-Based Views, define this view:

```<code>#views.py
def book_detail_view(request, id):
    book = get_object_or_404(Book, id=id)
    authors_of_book = book.questions.all()
    template = 'books/book_detail1.html'
    context = {'authors_of_book': authors_of_book}
    return render(request, template, context)
</code>```

And also in your template:

```<code>#html.py
<ul>
{% for author in authors_of_book %}
    <li>{{ author }}</li>
{% endfor %}
</ul>
</code>```

For more detail read this document.

Body:
I have two models, Author & Book in models.py

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

def __str__(self):
    return '%s %s' %(self.first_name, self.last_name)

def __unicode__(self):
    return '%s %s' %(self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100) #name = title
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    rating = models.FloatField()
    author = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

def __str__(self):
    return self.title

def __unicode__(self):
    return self.title

Now i'm listing all the books using ListView. And on click of a book i'm getting information the book using following method

class BookDetailView(generic.DetailView):
    template_name = 'books/book_detail1.html'
    model = Book
    context_object_name = 'book_detail'

I'm able to access title, pages, price, rating, publisher & publication_date but not getting all the Authors(Author list). While i'm going to simply print it, it prints None in template. I even try to iterate using For Loop but not done in template

views.py

<!DOCTYPE html>

    <title></title>

Price:{{ book_detail.price }}

Pub Date:{{ book_detail.publication_date }}

Title: {{ book_detail.title }}

Pages: {{ book_detail.pages }}

Rating: {{ book_detail.rating }}

Publisher: {{ book_detail.publisher }}

Author: {{ book_detail.author }}

Can anyone help me to out from this?

Body:
Or if you use Function-Based Views, define this view:

#views.py
def book_detail_view(request, id):
    book = get_object_or_404(Book, id=id)
    authors_of_book = book.questions.all()
    template = 'books/book_detail1.html'
    context = {'authors_of_book': authors_of_book}
    return render(request, template, context)

And also in your template:

#html.py
<ul>
{% for author in authors_of_book %}
    <li>{{ author }}</li>
{% endfor %}
</ul>

For more detail read this document.


来源: stackexchange

问:
Multiple entries with same key: android:allowBackup=REPLACE and android1:allowBackup=REPLACE
I'm facing below using while compiling the project

Below are the error logs

```<code>Error:Execution failed for task ':sampleproject:processDebugAndroidTestManifest'.
> java.lang.IllegalArgumentException: Multiple entries with same key: android:allowBackup=REPLACE and android1:allowBackup=REPLACE
</code>```

AndroidManifest.XML

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sample.mini" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <uses-sdk tools:overrideLibrary="com.sample.toolkit.payment"/>

    <application
        android:allowBackup="false"
        android:icon="@mipmap/icn_app"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="false"
        android:theme="@style/MaterialTheme"
        tools:replace="android:label, theme, allowBackup, android:icon,android:supportsRtl">

        <activity
            android:name="com.sample.SwiftActivity"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialTheme" />

        <activity
            android:name="com.activities.TermsAndConditionActivity"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialTheme" />

    </application>

</manifest>
</code>```

答:
Try to add android: to the front of allowBackup in the tools:replace list

```<code>tools:replace="android:label,theme,android:allowBackup,android:icon,android:supportsRtl"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm facing below using while compiling the project

Below are the error logs

Error:Execution failed for task ':sampleproject:processDebugAndroidTestManifest'.
> java.lang.IllegalArgumentException: Multiple entries with same key: android:allowBackup=REPLACE and android1:allowBackup=REPLACE

AndroidManifest.XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.sample.mini" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <uses-sdk tools:overrideLibrary="com.sample.toolkit.payment"/>

    <application
        android:allowBackup="false"
        android:icon="@mipmap/icn_app"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="false"
        android:theme="@style/MaterialTheme"
        tools:replace="android:label, theme, allowBackup, android:icon,android:supportsRtl">

        <activity
            android:name="com.sample.SwiftActivity"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialTheme" />

        <activity
            android:name="com.activities.TermsAndConditionActivity"
            android:screenOrientation="portrait"
            android:theme="@style/MaterialTheme" />

    </application>

</manifest>

Body:
Try to add android: to the front of allowBackup in the tools:replace list

tools:replace="android:label,theme,android:allowBackup,android:icon,android:supportsRtl"

ContentLicense: CC BY-SA 4.0


问:
Serializing null values with jackson
I'm trying to serialize through jackson some fields, which can be null, with a custom serializer. Reading online it seems that jackson should write a "null" string, and if I want a different output I should follow this example from its official github

The problem is that I get a NullPointerException instead of a "null" string.
This occurs both with JsonGenerator.writeNumberField, both with JsonGenerator.writeStringField.

To write an empty string should I manage the exception, or is there something I'm missing?

This is the stacktrace:

```<code>com.fasterxml.jackson.databind.JsonMappingException: [no message for java.lang.NullPointerException]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._wrapAsIOE(DefaultSerializerProvider.java:509) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:482) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3219) ~[jackson-databind-2.9.6.jar:2.9.6]
    at petmenu.restControllers.ProdottoController.thirdStageInput(ProdottoController.java:92) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_202]
Caused by: java.lang.NullPointerException: null
    at petmenu.CustomProdottoSerializer.serialize(CustomProdottoSerializer.java:32) ~[main/:na]
    at petmenu.CustomProdottoSerializer.serialize(CustomProdottoSerializer.java:1) ~[main/:na]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.9.6.jar:2.9.6]
    ... 58 common frames omitted
</code>```

And this is the interesting code

   @Override
    public void serialize(
      Prodotto prod, JsonGenerator jgen, SerializerProvider serializer) throws IOException {
        jgen.writeStartObject();

//      getPeso_netto returns an Integer, that in the example is null
        jgen.writeNumberField("peso_netto", prod.getPeso_netto());
```

答:
i would suggest to simply make a null check, or as you sugested, handle via exception.

@Override
    public void serialize(
      Prodotto prod, JsonGenerator jgen, SerializerProvider serializer) throws IOException {
        jgen.writeStartObject();

//      getPeso_netto returns an Integer, that in the example is null
        if (prod.getPeso_netto() != null)
            jgen.writeNumberField("peso_netto", prod.getPeso_netto());
        else {
            jgen.writeNullField("peso_netto");
        }

```

<h3>EDIT Explanation</h3>

<p>the method JsonGenerator.writeNumberField has following method body:</p>

<pre class="lang-java prettyprint-override"><code>public final void writeNumberField(String fieldName, int value) throws IOException {
    this.writeFieldName(fieldName);
    this.writeNumber(value);
}
</code>```

as you see, the method is expecting an int, not an Integer. The compiler is trying to Autobox the Integer to an int.
This fails with an NPE, because the Integer is a null object. So the NPE is not thrown 'by code of jackson library', but from the JVM at the point trying to pass an autoboxed null value as an int to a jackson method.

You can test this behaviour with following snippet:

Integer x = null;
x = 1 + x; // will throw NPE
```

Title: Serializing null values with jackson

Body:
I'm trying to serialize through jackson some fields, which can be null, with a custom serializer. Reading online it seems that jackson should write a "null" string, and if I want a different output I should follow this example from its official github

The problem is that I get a NullPointerException instead of a "null" string.
This occurs both with JsonGenerator.writeNumberField, both with JsonGenerator.writeStringField.

To write an empty string should I manage the exception, or is there something I'm missing?

This is the stacktrace:

com.fasterxml.jackson.databind.JsonMappingException: [no message for java.lang.NullPointerException]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._wrapAsIOE(DefaultSerializerProvider.java:509) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:482) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905) ~[jackson-databind-2.9.6.jar:2.9.6]
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3219) ~[jackson-databind-2.9.6.jar:2.9.6]
    at petmenu.restControllers.ProdottoController.thirdStageInput(ProdottoController.java:92) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.9.RELEASE.jar:5.0.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_202]
Caused by: java.lang.NullPointerException: null
    at petmenu.CustomProdottoSerializer.serialize(CustomProdottoSerializer.java:32) ~[main/:na]
    at petmenu.CustomProdottoSerializer.serialize(CustomProdottoSerializer.java:1) ~[main/:na]
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.9.6.jar:2.9.6]
    ... 58 common frames omitted

And this is the interesting code

   @Override
    public void serialize(
      Prodotto prod, JsonGenerator jgen, SerializerProvider serializer) throws IOException {
        jgen.writeStartObject();

//      getPeso_netto returns an Integer, that in the example is null
        jgen.writeNumberField("peso_netto", prod.getPeso_netto());

Body:
i would suggest to simply make a null check, or as you sugested, handle via exception.

@Override
    public void serialize(
      Prodotto prod, JsonGenerator jgen, SerializerProvider serializer) throws IOException {
        jgen.writeStartObject();

//      getPeso_netto returns an Integer, that in the example is null
        if (prod.getPeso_netto() != null)
            jgen.writeNumberField("peso_netto", prod.getPeso_netto());
        else {
            jgen.writeNullField("peso_netto");
        }

EDIT Explanation

the method JsonGenerator.writeNumberField has following method body:

public final void writeNumberField(String fieldName, int value) throws IOException {
    this.writeFieldName(fieldName);
    this.writeNumber(value);
}

as you see, the method is expecting an int, not an Integer. The compiler is trying to Autobox the Integer to an int.
This fails with an NPE, because the Integer is a null object. So the NPE is not thrown 'by code of jackson library', but from the JVM at the point trying to pass an autoboxed null value as an int to a jackson method.

You can test this behaviour with following snippet:

Integer x = null;
x = 1 + x; // will throw NPE


问:
how can this SQL be done in LINQ?
i have this simple SQL query...

```<code>-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC
</code>```

Im using entity framwork and want to do the same thing using linq. so far i have...

```<code>                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }
</code>```

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly

答:
Check what queries it performs when you run it with LINQ.

I suspect that you orderby g.Count() descending might be executing a COUNT query for each row and that would take a toll on performance to say the least.

When working with EF, always check what your LINQ statements produce in terms of queries. It is very easy to create queries that result in a n+1 scenario.

Title: how can this SQL be done in LINQ?

Body:
i have this simple SQL query...

-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC

Im using entity framwork and want to do the same thing using linq. so far i have...

                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly


问:
installing gtk+ on mac osx 10.11.4 El-Capitan
I have a macbook pro with osx 10.11.4 El-Capitan. I use zsh, which I wonder could be causing problems? I've been tinkering with python for the last year on a wide variety of small projects with no problems, so my environment is pretty stable. I needed gtk, so...

I started with this

git clone git://git.gnome.org/gtk+

I am following the instructions here to build the gtk+ distribution:

https://wiki.gnome.org/action/show//Projects/GTK+/OSX/Building?action=show&redirect=GTK%2B%2FOSX%2FBuilding

Things seemed to be progressing until I ran this step :

```<code>jhbuild build meta-gtk-osx-bootstrap
</code>```

and get the following error :

checking for python module libxml2... not found
  configure: error: Python module libxml2 is needed to run this package
  * Error during phase configure of itstool: ########## Error running ./configure --prefix /Users/Dad/gtk/inst    * [7/12]

So I tried :

```<code>brew install libxml2
</code>```

gives me :

OS X already provides this software and installing another version in
  parallel can cause all kinds of trouble.

Generally there are no consequences of this for you. If you build your
  own software and it requires this formula, you'll need to add to your
  build variables:

```<code>LDFLAGS:  -L/usr/local/opt/libxml2/lib
CPPFLAGS: -I/usr/local/opt/libxml2/include
</code>```

Any ideas on how to proceed ? The problem seems like libxml2 is installed but can't be found by jhbuild - so I expect this to be a relatively common problem, easy to fix, but I'm stuck? I'm not sure where to set these environment variables. I set them from the command line and reran but same result.

Thanks in advance

答:
I also had this issue and tried ptomato's answer and it didn't work for me. But I found the right .py file:

```<code>find ~ -iname "libxml2.py"
~/gtk/source/libxml2-2.9.8/python/libxml2.py
~/gtk/inst/lib/python3.6/site-packages/libxml2.py
</code>```

And copied it and the libxml2mod library it needs, over to the python2.7 site packages:

```<code>cp ~/gtk/source/libxml2-2.9.8/python/libxml2.py ~/gtk/inst/lib/python2.7/site-packages/
cp ~/.cache/jhbuild/build/libxml2-2.9.8/python/.libs/libxml* ~/gtk/inst/lib/python2.7/site-packages/
</code>```

I don't know (or care) why the libxml2/python makefile can't install it into the right place. However I'm leaving this here so I don't forget and run into the same problem next time.

Body:
I have a macbook pro with osx 10.11.4 El-Capitan. I use zsh, which I wonder could be causing problems? I've been tinkering with python for the last year on a wide variety of small projects with no problems, so my environment is pretty stable. I needed gtk, so...

I started with this

git clone git://git.gnome.org/gtk+

I am following the instructions here to build the gtk+ distribution:

https://wiki.gnome.org/action/show//Projects/GTK+/OSX/Building?action=show&redirect=GTK%2B%2FOSX%2FBuilding

Things seemed to be progressing until I ran this step :

jhbuild build meta-gtk-osx-bootstrap

and get the following error :

checking for python module libxml2... not found
  configure: error: Python module libxml2 is needed to run this package
  * Error during phase configure of itstool: ########## Error running ./configure --prefix /Users/Dad/gtk/inst    * [7/12]

So I tried :

brew install libxml2

gives me :

OS X already provides this software and installing another version in
  parallel can cause all kinds of trouble.

Generally there are no consequences of this for you. If you build your
  own software and it requires this formula, you'll need to add to your
  build variables:

LDFLAGS:  -L/usr/local/opt/libxml2/lib
CPPFLAGS: -I/usr/local/opt/libxml2/include

Any ideas on how to proceed ? The problem seems like libxml2 is installed but can't be found by jhbuild - so I expect this to be a relatively common problem, easy to fix, but I'm stuck? I'm not sure where to set these environment variables. I set them from the command line and reran but same result.

Thanks in advance

Body:
I also had this issue and tried ptomato's answer and it didn't work for me. But I found the right .py file:

find ~ -iname "libxml2.py"
~/gtk/source/libxml2-2.9.8/python/libxml2.py
~/gtk/inst/lib/python3.6/site-packages/libxml2.py

And copied it and the libxml2mod library it needs, over to the python2.7 site packages:

cp ~/gtk/source/libxml2-2.9.8/python/libxml2.py ~/gtk/inst/lib/python2.7/site-packages/
cp ~/.cache/jhbuild/build/libxml2-2.9.8/python/.libs/libxml* ~/gtk/inst/lib/python2.7/site-packages/

I don't know (or care) why the libxml2/python makefile can't install it into the right place. However I'm leaving this here so I don't forget and run into the same problem next time.


问:
Copying a column in excel and doubling every entry/cell. How to?
Let's say we have a row of elements, 1 per cell: 1,2,3,4.
I want to copy this row(or column) and double every entry: 1,1,2,2,3,3,4,4.

Is there any formula, function, etc that does this? Thanks a lot.

I have about 20k entries so doing it manually is not an option.

答:
Formula:

Result:

Hold and drag along the rows


问:
How to hide a border?
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

```<code>.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}
</code>```

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

```<code>.text-center a {border: none !important; box-shadow : none;}
</code>```

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

```<code>    <div class="event_registration registration">

    <input type="button" class="registration_button button" value="Register for event" />

    <div class="registration_details">
        <p>To register for this event please visit the following URL: <a href="https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779" target="_blank" rel="nofollow">https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →</a></p>     </div>
        </div>
                 <!-- For more details information start -->
                          <div class="text-center">
                <a class="link-button" data-toggle="modal" href="https://www.theunderworldcamden.co.uk/event/camden-rocks-festival-2019/"  target="_blank" >View More Details</a>
              </div>

         <!-- For more details infomation end-->
         <!-- Video popup box section start -->
                     <!-- Video popup box section end -->

 <!-- Event Location and Time start-->

    <h3 class="section-title">When & Where</h3>
      <ul class="when-where">
        <li class="event-start-date">
         From:2019-06-01   12:00 PM            </li>
        <li class="event-end-date">
         To:2019-06-02 12:00 AM            </li>
        <li class="event-location">
         Location:
                       <span class="venue-name">
            The Underworld
</code>```

https://adsler.co.uk/event/camden-rocks-festival/

答: Try, in .link-button class, to remove border and box-shadow attributes

Title: How to hide a border?

Body:
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

.text-center a {border: none !important; box-shadow : none;}

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

    <input type="button" class="registration_button button" value="Register for event" />

To register for this event please visit the following URL: https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →

                View More Details

When & Where

         From:2019-06-01   12:00 PM

         To:2019-06-02 12:00 AM

         Location:

            The Underworld

https://adsler.co.uk/event/camden-rocks-festival/


问:
Why is my paragraph exceeding the hr line which is below the paragraph on resizing?
The problem is that I have an image on the left side of my screen and I have a paragraph on the right side of my screen and I have an hr line below the paragraph and the image. So whenever I resize the browser window, the paragraph just goes below the hr line because it gets compressed(squashed) on resizing. I don't want the paragraph to go below the hr line even if I resize the browser window. I want the paragraph to go below the image but not exceeding the hr line. If you want to see what is the problem please check out my website and resize the browser window to see the problem.

Link to website: http://www.greenfield-school.com/AboutUs.html

Thanks

This is the HTML:

```<code><h3><b>About Us</b></h3>
    <hr style="border: 2px solid green; width: 88%">
    <div class="row2">
  <div class="column2" style="background-color:;">
    <img class="pic img-responsive" src="Icon.jpeg" style="height: 200px; height: 230px">
  </div>
  <div class="column" style="background-color:;">
    <h5 class="welcome"><b>Mission</b></h5>
     <p class="paragraph" style="font-family: book antiqua"><li class="vision1">To care for, respect and encourage all children equally, regardless of gender or ability.</li>
     <li class="vision1">To encourage our pupils to develop a sense of self worth, self discipline, personal responsibility and consideration for others.</li>
     <li class="vision1">To provide an enjoyable, challenging and purposeful atmosphere for our pupils.</li>
     <li class="vision1">To value and encourage the special talents and strengths of pupils.</li></p>

  </div>
</div>
</code>```

And this is the CSS:

```<code>.vision1 {

    list-style-type: square;
    font-family: book-antiqua;
}

.row2{
  display: flex;
  padding: 2rem 6rem;
}

.column {
  flex: 60%;
  height: 200px; /* Should be removed. Only for demonstration */
}

.column2{
  flex: 0%;
  height: 0px; /* Should be removed. Only for demonstration */
}

h3{
    padding: 5rem 5rem 0rem;
    color: green;
}
</code>```

答:
Let me offer you an alternative - I can't seem to trigger that auto-adjust on the container height. But this works seamlessly:

This is your HTML:

```<code><div class="container">
  <div class="column one"> Column 1 - this is where your picture is</div>
  <div class="column two"> Column 2 - this is where your paragraph is</div>
</div>
<hr />
</code>```

This is CSS:

```<code>.container{
  width: 100%;
  overflow: auto;
  height: auto;
  clear: both;
  display: block;
}
.column{
  float: left;
}

.column.one{
    //style for column one here
}
.column.two{
    //style for column two here
}

hr{
  clear: both;
}
</code>```

This will adjust the height of the container based on on the biggest height of either column one or column two

I have checked this code here CodePen

Body:
The problem is that I have an image on the left side of my screen and I have a paragraph on the right side of my screen and I have an hr line below the paragraph and the image. So whenever I resize the browser window, the paragraph just goes below the hr line because it gets compressed(squashed) on resizing. I don't want the paragraph to go below the hr line even if I resize the browser window. I want the paragraph to go below the image but not exceeding the hr line. If you want to see what is the problem please check out my website and resize the browser window to see the problem.

Link to website: http://www.greenfield-school.com/AboutUs.html

Thanks

This is the HTML:

About Us

Mission

To care for, respect and encourage all children equally, regardless of gender or ability.

To encourage our pupils to develop a sense of self worth, self discipline, personal responsibility and consideration for others.

To provide an enjoyable, challenging and purposeful atmosphere for our pupils.

To value and encourage the special talents and strengths of pupils.

And this is the CSS:

.vision1 {

    list-style-type: square;
    font-family: book-antiqua;
}

.row2{
  display: flex;
  padding: 2rem 6rem;
}

.column {
  flex: 60%;
  height: 200px; /* Should be removed. Only for demonstration */
}

.column2{
  flex: 0%;
  height: 0px; /* Should be removed. Only for demonstration */
}

h3{
    padding: 5rem 5rem 0rem;
    color: green;
}

Body:
Let me offer you an alternative - I can't seem to trigger that auto-adjust on the container height. But this works seamlessly:

This is your HTML:

<div class="container">
  <div class="column one"> Column 1 - this is where your picture is</div>
  <div class="column two"> Column 2 - this is where your paragraph is</div>
</div>
<hr />

This is CSS:

.container{
  width: 100%;
  overflow: auto;
  height: auto;
  clear: both;
  display: block;
}
.column{
  float: left;
}

.column.one{
    //style for column one here
}
.column.two{
    //style for column two here
}

hr{
  clear: both;
}

This will adjust the height of the container based on on the biggest height of either column one or column two

I have checked this code here CodePen


问:
How can I read an audio file using streams?
I am currently looking for away to stream audio-files. I'd like to read x amounts of seconds from a given .wav file, do my analysis task and repeat.....

Here is some code to get the idea of what i want:

```<code>`read_x_seconds = 30
 file_length_in_min = 15
 for x in range(file_length_in_min * (60 / read_x_seconds)):
    y, fs = librosa.core.load(FILENAME, offset=x * read_x_seconds,
    duration=read_x_seconds)
    do_analysis(y, fs)`
</code>```

答:
```<code>with open(stream_file, 'rb') as audio_file:
    content = audio_file.read(BYTES_PER_SECOND)
</code>```

Body:
I am currently looking for away to stream audio-files. I'd like to read x amounts of seconds from a given .wav file, do my analysis task and repeat.....

Here is some code to get the idea of what i want:

`read_x_seconds = 30
 file_length_in_min = 15
 for x in range(file_length_in_min * (60 / read_x_seconds)):
    y, fs = librosa.core.load(FILENAME, offset=x * read_x_seconds,
    duration=read_x_seconds)
    do_analysis(y, fs)`


问:
Query array using whereHas
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

```<code>  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);
</code>```

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

答:
I'm improving other persons answer. Below is the filtered code here

```<code>$builder = new Product;

if($request->filled('keywords')) {  // if keywords key has any value then query will execute.

    $builder = $builder->whereHas('categories', function($q) use ($request){
                        $q->whereIn('title', array_values($request->keywords));
                    });
}

$items = $builder->get();
dd($items);
</code>```

You can try this.

Title: Query array using whereHas

Body:
I want to filter products by category (manyToMany relationship). Basically the user select which categories to show. The categories I want to filter are in $request->keywords. This is what I tried:

  $products = Product::all();
  foreach($request->keywords as $keyword) {
    $products = Product::whereHas('categories', function($q) use ($keyword){
      $q->where('title', '=', $keyword);
    })->get();
  }

  return response()->json($products);

The problem is that this does not get all the categories, only the products with the last category in the array. I guess at this point: $q->where('title', '=', $keyword);, $q does not keep the results of the last loop iteration but always deletes the last loop results.
I also tried the same thing with $q->orWhere('title', '=', $keyword);, but that actually doesn't give me any results.

Thanks for your help!

Body:
I'm improving other persons answer. Below is the filtered code here

$builder = new Product;

if($request->filled('keywords')) {  // if keywords key has any value then query will execute.

    $builder = $builder->whereHas('categories', function($q) use ($request){
                        $q->whereIn('title', array_values($request->keywords));
                    });
}

$items = $builder->get();
dd($items);

You can try this.


问:
Data Binding set a static String as input
I'm using data binding in my application and and my call back interface for onclick

```<code>public interface HomeCallBack {
void onProvinceClick(String provinceName);
}
</code>```

and inside of XML I need to set static string as province name
is that possible ?

```<code> <ImageView
            android:onClick="@{(v)->callBack.onProvinceClick(static string)}"
            android:layout_width="@dimen/dp_10"
            android:layout_height="@dimen/dp_10"
            android:layout_marginLeft="@dimen/dp_10"
            android:layout_marginTop="@dimen/dp_40"
            android:src="@drawable/broken_heart" />
</code>```

答:
You should pass like this</p>

```<code><ImageView
        android:onClick='@{(v)->callBack.onProvinceClick("Your text")}'
        android:layout_width="@dimen/dp_10"
        android:layout_height="@dimen/dp_10"
        android:layout_marginLeft="@dimen/dp_10"
        android:layout_marginTop="@dimen/dp_40"
        android:src="@drawable/broken_heart" />
</code>```

Body:
I'm using data binding in my application and and my call back interface for onclick

public interface HomeCallBack {
void onProvinceClick(String provinceName);
}

and inside of XML I need to set static string as province name
is that possible ?

 <ImageView
            android:onClick="@{(v)->callBack.onProvinceClick(static string)}"
            android:layout_width="@dimen/dp_10"
            android:layout_height="@dimen/dp_10"
            android:layout_marginLeft="@dimen/dp_10"
            android:layout_marginTop="@dimen/dp_40"
            android:src="@drawable/broken_heart" />

Body:
You should pass like this

<ImageView
        android:onClick='@{(v)->callBack.onProvinceClick("Your text")}'
        android:layout_width="@dimen/dp_10"
        android:layout_height="@dimen/dp_10"
        android:layout_marginLeft="@dimen/dp_10"
        android:layout_marginTop="@dimen/dp_40"
        android:src="@drawable/broken_heart" />


问:
readiness probe fails with connection refused
I am trying to setup K8S to work with two Windows Nodes (2019). Everything seems to be working well and the containers are working and accessible using k8s service. But, once I introduce configuration for readiness (or liveness) probes - all fails.  The exact error is:

Readiness probe failed: Get http://10.244.1.28:80/test.txt: dial tcp 10.244.1.28:80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

When I try the url from k8s master, it works well and I get 200. However I read that the kubelet is the one executing the probe and indeed when trying from the Windows Node - it cannot be reached (which seems weird because the container is running on that same node). Therefore I assume that the problem is related to some network configuration.

I have a HyperV with External network Virtual Switch configured. K8S is configured to use flannel overlay (vxlan) as instructed here: https://learn.microsoft.com/en-us/virtualization/windowscontainers/kubernetes/network-topologies.

Any idea how to troubleshoot and fix this?

UPDATE: providing the yaml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: dummywebapplication
  labels:
    app: dummywebapplication
spec:
  ports:
    # the port that this service should serve on
  - port: 80
    targetPort: 80
  selector:
    app: dummywebapplication
  type: NodePort
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: dummywebapplication
  name: dummywebapplication
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: dummywebapplication
      name: dummywebapplication
    spec:
      containers:
      - name: dummywebapplication
        image: <my image>
        readinessProbe:
          httpGet:
            path: /test.txt
            port: 80
          initialDelaySeconds: 15
          periodSeconds: 30
          timeoutSeconds: 60
      nodeSelector:
        beta.kubernetes.io/os: windows
</code>```

And one more update. In this doc (https://kubernetes.io/docs/setup/windows/intro-windows-in-kubernetes/) it is written:

My Windows node cannot access NodePort service

Local NodePort access from the node itself fails. This is a known
limitation. NodePort access works from other nodes or external
clients.

I don't know if this is related or not as I could not connect to the container from a different node as stated above. I also tried a service of LoadBalancer type but it didn't provide a different result.

答:
The network configuration assumption was correct. It seems that for 'overlay', by default, the kubelet on the node cannot reach the IP of the container. So it keeps returning timeouts and connection refused messages.

Possible workarounds:

Insert an 'exception' into the ExceptionList 'OutBoundNAT' of C:\k\cni\config on the nodes. This is somewhat tricky if you start the node with start.ps1 because it overwrites this file everytime. I had to tweak 'Update-CNIConfig' function in c:\k\helper.psm1 to re-insert the exception similar to the 'l2bridge' in that file.

Use 'l2bridge' configuration. Seems like 'overlay' is running in a more secured isolation, but l2bridge is not.

Body:
I am trying to setup K8S to work with two Windows Nodes (2019). Everything seems to be working well and the containers are working and accessible using k8s service. But, once I introduce configuration for readiness (or liveness) probes - all fails.  The exact error is:

Readiness probe failed: Get http://10.244.1.28:80/test.txt: dial tcp 10.244.1.28:80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

When I try the url from k8s master, it works well and I get 200. However I read that the kubelet is the one executing the probe and indeed when trying from the Windows Node - it cannot be reached (which seems weird because the container is running on that same node). Therefore I assume that the problem is related to some network configuration.

I have a HyperV with External network Virtual Switch configured. K8S is configured to use flannel overlay (vxlan) as instructed here: https://learn.microsoft.com/en-us/virtualization/windowscontainers/kubernetes/network-topologies.

Any idea how to troubleshoot and fix this?

UPDATE: providing the yaml:

apiVersion: v1
kind: Service
metadata:
  name: dummywebapplication
  labels:
    app: dummywebapplication
spec:
  ports:
    # the port that this service should serve on
  - port: 80
    targetPort: 80
  selector:
    app: dummywebapplication
  type: NodePort
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  labels:
    app: dummywebapplication
  name: dummywebapplication
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: dummywebapplication
      name: dummywebapplication
    spec:
      containers:
      - name: dummywebapplication
        image: <my image>
        readinessProbe:
          httpGet:
            path: /test.txt
            port: 80
          initialDelaySeconds: 15
          periodSeconds: 30
          timeoutSeconds: 60
      nodeSelector:
        beta.kubernetes.io/os: windows

And one more update. In this doc (https://kubernetes.io/docs/setup/windows/intro-windows-in-kubernetes/) it is written:

My Windows node cannot access NodePort service

Local NodePort access from the node itself fails. This is a known
limitation. NodePort access works from other nodes or external
clients.

I don't know if this is related or not as I could not connect to the container from a different node as stated above. I also tried a service of LoadBalancer type but it didn't provide a different result.


问:
Whats the equivalent of ST_DWithin (PostGIS - PostgreSQL) for MySQL?
I am trying to find an efficient way to do proximity queries, ie to return POINTs which are within a radius from a central POINT.

I understand that PostGIS's ST_DWithin method is a good way to do this in PostgreSQL and that it uses the INDEX.

I am currently using ST_Distance_Sphere(g1, g2 [, radius]) which returns the minimum spherical distance between Point on a sphere, in meters.

```<code>SELECT placeNames FROM myPlaces
WHERE ST_Distance_Sphere(placeLocation, POINT(28.861105, 77.337)) < 10000
</code>```

I'm using the WHERE clause to filter the rows. Is the query using the index? If no, is there a better approach to implement the same.

I'm using MySQL 5.7.26 and 8.0.16, both running the default InnoDB database engine.

答:
Firtly SRID set this query 4326 use it;
sample

SELECT ST_SetSRID(ST_MakePoint(-71.1043443253471, 42.3150676015829),4326);

Body:
I am trying to find an efficient way to do proximity queries, ie to return POINTs which are within a radius from a central POINT.

I understand that PostGIS's ST_DWithin method is a good way to do this in PostgreSQL and that it uses the INDEX.

I am currently using ST_Distance_Sphere(g1, g2 [, radius]) which returns the minimum spherical distance between Point on a sphere, in meters.

SELECT placeNames FROM myPlaces
WHERE ST_Distance_Sphere(placeLocation, POINT(28.861105, 77.337)) < 10000

I'm using the WHERE clause to filter the rows. Is the query using the index? If no, is there a better approach to implement the same.

I'm using MySQL 5.7.26 and 8.0.16, both running the default InnoDB database engine.


问:
Java equivalent of signal&slot from QT
I'm writing a JavaFX application and I have problem with updating progress bar in main form, when some task executing. So, now, I passed reference to MainWindow, but I think, that is not the best solution. </p>

<p>In QT framework, there is a signal&slot system - so, in JavaFX there is similar system? For example, after load file, my utils class should emit signal to update connected progress bar. </p>

答:
Signal/slots is just a wrapper for events that happend asynch, assuming you have an object of ProgressBar then you just need to do</p>

```<code>ProgressBar myPB = new ProgressBar();
myPB.setProgress(someNumber);
</code>```

Title: Java equivalent of signal&slot from QT

Body:
I'm writing a JavaFX application and I have problem with updating progress bar in main form, when some task executing. So, now, I passed reference to MainWindow, but I think, that is not the best solution.

In QT framework, there is a signal&slot system - so, in JavaFX there is similar system? For example, after load file, my utils class should emit signal to update connected progress bar.

Body:
Signal/slots is just a wrapper for events that happend asynch, assuming you have an object of ProgressBar then you just need to do

ProgressBar myPB = new ProgressBar();
myPB.setProgress(someNumber);


问:
Why to put a property variable in the constructor
From other languages I am used to code a class property and afterwards I can access this without having it in the constructor like

```<code>Class MyClass:
    def __init__(self):
        self._value = 0
    @property
    my_property(self):
        print('I got the value:' & self._value)
</code>```

In almost every example I worked through the property variable was in the constructor self._value like this

```<code>Class MyClass:
    def __init__(self, value = 0):
        self._value = value
</code>```

To me this makes no sence since you want to set it in the property. Could anyone explain to me what is the use of placing the value variable in the constructor?

答:
Python objects are not struct-based (like C++ or Java), they are dict-based (like Javascript). This means that the instances attributes are dynamic (you can add new attributes or delete existing ones at runtime), and are not defined at the class level but at the instance level, and they are defined quite simply by assigning to them. While they can technically be defined anywhere in the code (even outside the class), the convention (and good practice) is to define them (eventually to default values) in the initializer (the __init__ method - the real constructor is named __new__ but there are very few reasons to override it) to make clear which attributes an instance of a given class is supposed to have.

Note the use of the term "attribute" here - in python, we don't talk about "member variables" or "member functions" but about "attributes" and "methods". Actually, since Python classes are objects too (instance of the type class or a subclass of), they have attributes too, so we have instance attributes (which are per-instance) and class attributes (which belong to the class object itself, and are shared amongst instances). A class attribute can be looked up on an instance, as long as it's not shadowed by an instance attribute of the same name.

Also, since Python functions are objects too (hint: in Python, everything - everything you can put on the RHS of an assignment that is - is an object), there are no distinct namespaces for "data" attributes and "function" attributes, and Python's "methods" are actually functions defined on the class itself - IOW they are class attributes that happen to be instances of the function type. Since methods need to access the instance to be able to work on it, there's a special mechanism that allow to "customize" attribute access so a given object - if it implements the proper interface - can return something else than itself when it's looked up on an instance but resolved on the class. This mechanism is used by functions so they turn themselves into methods (callable objects that wraps the function and instance together so you don't have to pass the instance to the function), but also more generally as the support for computed attributes.

The property class is a generic implementation of computed attributes that wraps a getter function (and eventually a setter and a deleter) - so in Python "property" has a very specific meaning (the property class itself or an instance of it). Also, the @decorator syntax is nothing magical (and isn't specific to properties), it's just syntactic sugar so given a "decorator" function:

```<code> def decorator(func):
     return something
</code>```

this:

```<code> @decorator
 def foo():
     # code here
</code>```

is just a shortcut for:

```<code> def foo():
     # code here

 foo = decorator(foo)
</code>```

Here I defined decorator as a function, but just any callable object (a "callable" object is an instance of a class that defines the __call__ magic method) can be used instead - and Python classes are callables (that's even actually by calling a class that you instanciate it).

So back to your code:

```<code># in py2, you want to inherit from `object` for
# descriptors and other fancy things to work.
# this is useless in py3 but doesn't break anything either...

class MyClass(object):

    # the  `__init__` function will become an attribute
    # of the `MyClass` class object

    def __init__(self, value=0):
        # defines the instance attribute named `_value`
        # the leading underscore denotes an "implementation attribute"
        # - something that is not part of the class public interface
        # and should not be accessed externally (IOW a protected attribute)
        self._value = value

    # this first defines the `my_property` function, then
    # pass it to `property()`, and rebinds the `my_property` name
    # to the newly created `property` instance. The `my_property` function
    # will then become the property's getter (it's `fget` instance attribute)
    # and will be called when the `my_property` name is resolved on a `MyClass` instance

    @property
    my_property(self):
        print('I got the value: {}'.format(self._value))
        # let's at least return something
        return self._value
</code>```

You may then want to inspect both the class and an instance of it:

```<code>>>> print(MyClass.__dict__)
{'__module__': 'oop', '__init__': <function MyClass.__init__ at 0x7f477fc4a158>, 'my_property': <property object at 0x7f477fc639a8>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
>>> print(MyClass.my_property)
<property object at 0x7f477fc639a8>
>>> print(MyClass.my_property.fget)
<function MyClass.my_property at 0x7f477fc4a1e0>
>>> m = MyClass(42)
>>> print(m.__dict__)
{'_value': 42}
>>> print(m.my_property)
I got the value: 42
42
>>>
</code>```

As a conclusion: if you hope to do anything usefull with a language, you have to learn this language - you cannot just expect it to work as other languages you know. While some features are based on common concepts (ie functions, classes etc), they can actually be implemented in a totally different way (Python's object model has almost nothing in common with Java's one), so just trying to write Java (or C or C++ etc) in Python will not work (just like trying to write Python in Java FWIW).

NB: just for the sake of completeness: Python objects can actually be made "struct-based" by using __slots__ - but the aim here is not to prevent dynamically adding attributes (that's only a side effect) but to make instances of those classes "lighter" in size (which is useful when you know you're going to have thousands or more instances of them at a given time).

Body:
From other languages I am used to code a class property and afterwards I can access this without having it in the constructor like

Class MyClass:
    def __init__(self):
        self._value = 0
    @property
    my_property(self):
        print('I got the value:' & self._value)

In almost every example I worked through the property variable was in the constructor self._value like this

Class MyClass:
    def __init__(self, value = 0):
        self._value = value

To me this makes no sence since you want to set it in the property. Could anyone explain to me what is the use of placing the value variable in the constructor?

Body:
Python objects are not struct-based (like C++ or Java), they are dict-based (like Javascript). This means that the instances attributes are dynamic (you can add new attributes or delete existing ones at runtime), and are not defined at the class level but at the instance level, and they are defined quite simply by assigning to them. While they can technically be defined anywhere in the code (even outside the class), the convention (and good practice) is to define them (eventually to default values) in the initializer (the __init__ method - the real constructor is named __new__ but there are very few reasons to override it) to make clear which attributes an instance of a given class is supposed to have.

Note the use of the term "attribute" here - in python, we don't talk about "member variables" or "member functions" but about "attributes" and "methods". Actually, since Python classes are objects too (instance of the type class or a subclass of), they have attributes too, so we have instance attributes (which are per-instance) and class attributes (which belong to the class object itself, and are shared amongst instances). A class attribute can be looked up on an instance, as long as it's not shadowed by an instance attribute of the same name.

Also, since Python functions are objects too (hint: in Python, everything - everything you can put on the RHS of an assignment that is - is an object), there are no distinct namespaces for "data" attributes and "function" attributes, and Python's "methods" are actually functions defined on the class itself - IOW they are class attributes that happen to be instances of the function type. Since methods need to access the instance to be able to work on it, there's a special mechanism that allow to "customize" attribute access so a given object - if it implements the proper interface - can return something else than itself when it's looked up on an instance but resolved on the class. This mechanism is used by functions so they turn themselves into methods (callable objects that wraps the function and instance together so you don't have to pass the instance to the function), but also more generally as the support for computed attributes.

The property class is a generic implementation of computed attributes that wraps a getter function (and eventually a setter and a deleter) - so in Python "property" has a very specific meaning (the property class itself or an instance of it). Also, the @decorator syntax is nothing magical (and isn't specific to properties), it's just syntactic sugar so given a "decorator" function:

 def decorator(func):
     return something

this:

 @decorator
 def foo():
     # code here

is just a shortcut for:

 def foo():
     # code here

 foo = decorator(foo)

Here I defined decorator as a function, but just any callable object (a "callable" object is an instance of a class that defines the __call__ magic method) can be used instead - and Python classes are callables (that's even actually by calling a class that you instanciate it).

So back to your code:

# in py2, you want to inherit from `object` for
# descriptors and other fancy things to work.
# this is useless in py3 but doesn't break anything either...

class MyClass(object):

    # the  `__init__` function will become an attribute
    # of the `MyClass` class object

    def __init__(self, value=0):
        # defines the instance attribute named `_value`
        # the leading underscore denotes an "implementation attribute"
        # - something that is not part of the class public interface
        # and should not be accessed externally (IOW a protected attribute)
        self._value = value

    # this first defines the `my_property` function, then
    # pass it to `property()`, and rebinds the `my_property` name
    # to the newly created `property` instance. The `my_property` function
    # will then become the property's getter (it's `fget` instance attribute)
    # and will be called when the `my_property` name is resolved on a `MyClass` instance

    @property
    my_property(self):
        print('I got the value: {}'.format(self._value))
        # let's at least return something
        return self._value

You may then want to inspect both the class and an instance of it:

>>> print(MyClass.__dict__)
{'__module__': 'oop', '__init__': <function MyClass.__init__ at 0x7f477fc4a158>, 'my_property': <property object at 0x7f477fc639a8>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
>>> print(MyClass.my_property)
<property object at 0x7f477fc639a8>
>>> print(MyClass.my_property.fget)
<function MyClass.my_property at 0x7f477fc4a1e0>
>>> m = MyClass(42)
>>> print(m.__dict__)
{'_value': 42}
>>> print(m.my_property)
I got the value: 42
42
>>>

As a conclusion: if you hope to do anything usefull with a language, you have to learn this language - you cannot just expect it to work as other languages you know. While some features are based on common concepts (ie functions, classes etc), they can actually be implemented in a totally different way (Python's object model has almost nothing in common with Java's one), so just trying to write Java (or C or C++ etc) in Python will not work (just like trying to write Python in Java FWIW).

NB: just for the sake of completeness: Python objects can actually be made "struct-based" by using __slots__ - but the aim here is not to prevent dynamically adding attributes (that's only a side effect) but to make instances of those classes "lighter" in size (which is useful when you know you're going to have thousands or more instances of them at a given time).


问:
Remove Screen from navigation stack

App structure -

Home Screen - Have button navigate to shopping cart

ShoppingCart Screen - have button navigate to shop screen

Shop Screen - Have button navigate to shopping cart

Using - react-native: 0.59.5, react-navigation: ^3.8.1

step 1 - go to shopping cart from home

step 2 - go to shop from shopping cart

step 3 - add some items to cart in shop

step 4 - go to shopping cart from shop - problem goes here.

in step 4 action show the previous screen of shoppingCart( that appeared screen at step 1 ).There are no new added items in the cart only have previous states.

I haven't any idea how to slolve this ? can anyone help ?

答: use navigation-events to add onWillFocus/onDidFocus listener on shoppingCart and refresh the scene in that callback</p>

Title: Remove Screen from navigation stack


问:
Getting the GUI of an app that went poof!
Today my Visual Studio disappeared. I can see devenv.exe in the 'Processes' tab in Task Manager but not in the Applications tab. I have unsaved changes. Is there a way to "revive" VS so changes can be saved?</p>

答:
Sounds like you are toast.

But some versions of Visual Studio (and by that I mean the later releases) will save a current copy of open documents and you may find that it will ask if you want to recover them when you open it again.

Otherwise. No.  I think they have gone.

OwnerDisplayName: Abdu

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Brody


问:
django msg.send() not working as it should
when i send mail through django view (code below):

```<code>subject = "Audit report for all staff  "
email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin'
report_name = response['Content-Disposition'].split('=')[1]

msg = EmailMessage(
            subject = subject,
            body = email_msg,
            attachments=(('%s' % report_name,f.read(), 'text/csv'),),
            to = ['prateekm@localhost','prateek@gmail.com' ],
       )
    msg.send()
</code>```

My mail is only being sent  to the localhost email id and not to the gmail id . How to rectify this?

答:
Django does not automatically send to remote servers. It does it through SMTP backend. You need to configure it.

http://docs.djangoproject.com/en/1.3/topics/email/#e-mail-backends

Body:
when i send mail through django view (code below):

subject = "Audit report for all staff  "
email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin'
report_name = response['Content-Disposition'].split('=')[1]

msg = EmailMessage(
            subject = subject,
            body = email_msg,
            attachments=(('%s' % report_name,f.read(), 'text/csv'),),
            to = ['prateekm@localhost','prateek@gmail.com' ],
       )
    msg.send()

My mail is only being sent  to the localhost email id and not to the gmail id . How to rectify this?


问:
Neo4j bad performance with OR operator
I am using neo4j-3.5 community version .And have built a huge graph using neo4j containing ~20 million nodes on movie data. I have also inserted genres & keywords and constructed the graph.
The following query takes > 5 seconds

```<code>MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50
</code>```

whereas if i replace OR with AND, it takes < 100 ms.

```<code>MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) AND (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50
</code>```

Indexes are there on genre id and keyword id.

The PROFILE response for 'OR' :

THE PROFILE response for 'AND' :

Any better way to write the query with OR operator?

答:
Your query builds a cartesian product between 3 disconnected patterns.

Try the following query:

```<code>  MATCH
    (k:Keyword)<-[key_rel:associated_keyword]-(p:Program)-[genre:of_genre]->(g:Genre)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50
</code>```

Title: Neo4j bad performance with OR operator

Body:
I am using neo4j-3.5 community version .And have built a huge graph using neo4j containing ~20 million nodes on movie data. I have also inserted genres & keywords and constructed the graph.
The following query takes > 5 seconds

MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50

whereas if i replace OR with AND, it takes < 100 ms.

MATCH
    (p:`Program`),
    (p:Program)-[genre:of_genre]->(g:Genre),
    (p:Program)-[key_rel:associated_keyword]->(k:Keyword)
  WHERE
    ((g.id IN [1010]) AND (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND
    (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50

Indexes are there on genre id and keyword id.

The PROFILE response for 'OR' :

THE PROFILE response for 'AND' :

Any better way to write the query with OR operator?

Body:
Your query builds a cartesian product between 3 disconnected patterns.

Try the following query:

  MATCH
    (k:Keyword)<-[key_rel:associated_keyword]-(p:Program)-[genre:of_genre]->(g:Genre)
  WHERE
    ((g.id IN [1010]) OR (k.id IN ['keyword_121'])) AND
    ((p.show_type IN ['movie'])) AND (p.imdb_score > 0)
  RETURN distinct p.id, p.imdb_score
  ORDER BY p.imdb_score desc
  LIMIT 50


问:
Excel VBA - Speed Up Copy Macro
I am using this macro, which works fine, albeit very slowly. Is there a way to speed it up (perhaps with arrays) so that the whole operation is performed only once?

What my code does is that it filters an Excel Table and then extracts only certain columns and pastes them into another sheet (in a different order).

```<code>Set lo_b1 = x_bf1.ListObjects(1)
s_date = CLng(ThisWorkbook.Names("in_fre_m").RefersToRange(1, 1))
s_des = ThisWorkbook.Names("dr_no").RefersToRange(1, 1)
s_code = ThisWorkbook.Names("dr_co").RefersToRange(1, 1)
lastrow_d = lo_dr.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Set pasterange1 = x_drill.Range("C" & lastrow_d)

    With lo_b1.Range
    .AutoFilter Field:=13, Criteria1:=s_code
    .AutoFilter Field:=1, Criteria1:="<=" & s_date
    End With

lastrow_s = lo_b1.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

If lastrow_s > 7 Then
    Set copyrange1 = x_bf1.Range("D8:D" & lastrow_s) 'Date
    Set copyrange2 = copyrange1.Offset(0, 1)  'Description
    Set copyrange3 = copyrange1.Offset(0, 16)  'Calculation
    Set copyrange5 = copyrange1.Offset(0, 5)  'Classification
    Set copyrange6 = copyrange1.Offset(0, 6)  'Notes
    Set copyrange7 = copyrange1.Offset(0, 11) '§
    Set copyrange8 = copyrange1.Offset(0, 12) 'Code
    Set copyrange9 = copyrange1.Offset(0, 20) 'Statutory
    Set copyrange10 = copyrange1.Offset(0, 14) 'Ref

    copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
    pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date
    pasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange5.SpecialCells(xlCellTypeVisible).Copy 'Account Name
    pasterange1.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange2.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange8.SpecialCells(xlCellTypeVisible).Copy 'Code
    pasterange1.Offset(0, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange7.SpecialCells(xlCellTypeVisible).Copy '§
    pasterange1.Offset(0, 5).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange3.SpecialCells(xlCellTypeVisible).Copy 'Calculation
    pasterange1.Offset(0, 6).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange9.SpecialCells(xlCellTypeVisible).Copy 'Statutory
    pasterange1.Offset(0, 7).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange6.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 8).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    Set copyrange1 = Nothing
    Set copyrange2 = Nothing
    Set copyrange3 = Nothing
    Set copyrange4 = Nothing
    Set copyrange5 = Nothing
    Set copyrange6 = Nothing
    Set copyrange7 = Nothing
    Set copyrange8 = Nothing
    Set copyrange9 = Nothing
    Set copyrange10 = Nothing
    End If
</code>```

答:
To add to the comments about screen updating, events and calculation try changing

```<code>copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone
</code>```

to

```<code>pasterange1.Value=copyrange1.SpecialCells(xlCellTypeVisible).Value
</code>```

In my experience it is much faster than copy and paste (and it also prevents issues with another application using the clipboard)

Title: Excel VBA - Speed Up Copy Macro

Body:
I am using this macro, which works fine, albeit very slowly. Is there a way to speed it up (perhaps with arrays) so that the whole operation is performed only once?

What my code does is that it filters an Excel Table and then extracts only certain columns and pastes them into another sheet (in a different order).

Set lo_b1 = x_bf1.ListObjects(1)
s_date = CLng(ThisWorkbook.Names("in_fre_m").RefersToRange(1, 1))
s_des = ThisWorkbook.Names("dr_no").RefersToRange(1, 1)
s_code = ThisWorkbook.Names("dr_co").RefersToRange(1, 1)
lastrow_d = lo_dr.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
Set pasterange1 = x_drill.Range("C" & lastrow_d)

    With lo_b1.Range
    .AutoFilter Field:=13, Criteria1:=s_code
    .AutoFilter Field:=1, Criteria1:="<=" & s_date
    End With

lastrow_s = lo_b1.Range.Columns(1).Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

If lastrow_s > 7 Then
    Set copyrange1 = x_bf1.Range("D8:D" & lastrow_s) 'Date
    Set copyrange2 = copyrange1.Offset(0, 1)  'Description
    Set copyrange3 = copyrange1.Offset(0, 16)  'Calculation
    Set copyrange5 = copyrange1.Offset(0, 5)  'Classification
    Set copyrange6 = copyrange1.Offset(0, 6)  'Notes
    Set copyrange7 = copyrange1.Offset(0, 11) '§
    Set copyrange8 = copyrange1.Offset(0, 12) 'Code
    Set copyrange9 = copyrange1.Offset(0, 20) 'Statutory
    Set copyrange10 = copyrange1.Offset(0, 14) 'Ref

    copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
    pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange1.SpecialCells(xlCellTypeVisible).Copy 'Date
    pasterange1.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange5.SpecialCells(xlCellTypeVisible).Copy 'Account Name
    pasterange1.Offset(0, 2).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange2.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange8.SpecialCells(xlCellTypeVisible).Copy 'Code
    pasterange1.Offset(0, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange7.SpecialCells(xlCellTypeVisible).Copy '§
    pasterange1.Offset(0, 5).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange3.SpecialCells(xlCellTypeVisible).Copy 'Calculation
    pasterange1.Offset(0, 6).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange9.SpecialCells(xlCellTypeVisible).Copy 'Statutory
    pasterange1.Offset(0, 7).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    copyrange6.SpecialCells(xlCellTypeVisible).Copy 'Notes
    pasterange1.Offset(0, 8).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

    Set copyrange1 = Nothing
    Set copyrange2 = Nothing
    Set copyrange3 = Nothing
    Set copyrange4 = Nothing
    Set copyrange5 = Nothing
    Set copyrange6 = Nothing
    Set copyrange7 = Nothing
    Set copyrange8 = Nothing
    Set copyrange9 = Nothing
    Set copyrange10 = Nothing
    End If

Body:
To add to the comments about screen updating, events and calculation try changing

copyrange10.SpecialCells(xlCellTypeVisible).Copy 'Ref
pasterange1.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone

to

pasterange1.Value=copyrange1.SpecialCells(xlCellTypeVisible).Value

In my experience it is much faster than copy and paste (and it also prevents issues with another application using the clipboard)


问:
Control outputs / signal queue in CONNECT platform?
I'm trying to prevent an empty item to go through to an object (in this case at the end of the list to simplify the case). Does the control output "signals" have any kind of queue where they are consumed or is it going to trigger the node if the signal is sent at least once?

The question is specific to this example where it is returning an empty object at the end which it shouldn't be but I am still interested to know how control outputs behave in different scenarios (this being one such interesting scenario). In a normal case, the array would be first filtered to eliminate any "incompatible" (e.g undefined) elements.

答:
there is no queue for control signals. all control signals of a node must activate in order for the node to activate as well though.

once a node finishes its execution, its control flag is reset, but its data input pins are not. as a result, the control signals should all be emitted again for the node to activate, however the parameters it received via its input pins will persist.

when you resend data to an input pin, the previous value will be overridden, so for the next execution of the node, the overridden value will be used. note that the node will still wait for all control signals to green-light the execution.

these should answer your question generally. but to be more specific to the use-case you have at hand: you are forgetting that these nodes execute asynchronously, and probably thats why your graph is not behaving as you desire. this is how that could occur:

#iterate will feed a step with non empty item to the expression.

the expression will feed this step to the switch and to /user/key/delete.

#iterate will feed another step, this time with an empty item to the expression.

the expression will feed false to /user/key/delete.

the switch will give a green-light to /user/key/delete when it finishes its previous execution (with the non-empty step).

as you can see, you would then have /user/key/delete be executed on false, which is something that it seems you want to avoid. to side-step this issue, I would recommend simply filtering the array before feeding it to #iterate to begin with.

a clearer example of this phenomenon can be seen with a graph like this:

running this sub-graph will lead to 3 numbers being printed, but not necessarily even numbers, due to the same phenomenon.


问:
Align footer at the bottom of the content, push to right of the sidebar
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

```<code><div class="wrapper">
   <!-- Navbar -->
   <nav class="navbar navbar-expand-sm fixed-top navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
      <div class="container-fluid">
      </div>
   </nav>
   <!-- Sidebar -->
   <div id="sidebar" class="shadow-sm"></div>
   <!-- Page Content -->
   <div id="content">
      <div class="container-fluid">
         <div class="card">
            <div class="card-body">
               <h1>
                  Collapsing Menu
                  <small class="text-muted">Version 2.1</small>
               </h1>
            </div>
         </div>
      </div>
   </div>
</div>
<footer id="page-footer" class="py-3 bg-dark text-light">
   <div class="container">

   </div>
</footer>
</code>```

CSS for the footer and sidebar:

```<code>footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}
</code>```

答:
$(document).ready(function(){
  var wheight= $(window).height();
  var contentheight=$(".content").height();
  if(wheight>contentheight){
    $("footer").addClass("fixedfooter");
  }
  else{
     $("footer").removeClass("fixedfooter");
}
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
margin:0;
padding:0;
}
.sidebar {
   height: 100vh;
  float:left;
  width:20%;
  background:red;
}
.wrapper{
  overflow:hidden;
}
.page{
  width:80%;
  float:left;

}
.content{
  width:100%;
  height:200px;
  background-color:green;
}
footer {
  width:calc(100%);
  height:50px;
  background-color:blue;
}

.fixedfooter{
  position:fixed;
  right:0;
  bottom:0;
  width:calc(100% - 20%)!important;
}</code>```

sidebar

my content

    my footer

```

this is it with jquery! applying a class with fixed position to the footer when the content height is not higher then windows height!
try changing height of content to check result!

Body:
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

                  Collapsing Menu
                  Version 2.1

CSS for the footer and sidebar:

footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}

Body:
$(document).ready(function(){
  var wheight= $(window).height();
  var contentheight=$(".content").height();
  if(wheight>contentheight){
    $("footer").addClass("fixedfooter");
  }
  else{
     $("footer").removeClass("fixedfooter");
}
})

*{
margin:0;
padding:0;
}
.sidebar {
   height: 100vh;
  float:left;
  width:20%;
  background:red;
}
.wrapper{
  overflow:hidden;
}
.page{
  width:80%;
  float:left;

}
.content{
  width:100%;
  height:200px;
  background-color:green;
}
footer {
  width:calc(100%);
  height:50px;
  background-color:blue;
}

.fixedfooter{
  position:fixed;
  right:0;
  bottom:0;
  width:calc(100% - 20%)!important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="sidebar">sidebar</div>
  <div class="page">
    <div class="content">my content</div>
    <footer>my footer </footer>
  </div>
</div>

this is it with jquery! applying a class with fixed position to the footer when the content height is not higher then windows height!
try changing height of content to check result!