问:
How to set up catalina.out log files on jasperserver for multiple instances?
I have jasperserver with two instances. And in both instances here /var/log/tomcat9_first_instance, /var/log/tomcat9_second_instance I have catalina.out log file. But I did not get there logs from my instances, instead all logs go to /var/log/tomcat9/catalina.out.

I want log from first instance in /var/log/tomcat9_first_instance/catalina.out and from second instance in /var/log/tomcat9_second_instance/catalina.out. How to fix this?


来源: stackexchange

问:
Convert html to Pdf with with very big data
I have implemented html to pdf conversion using openhtmltopdf and I use it in Struts 2 action and it works very well. However, in the case of very large data, e.g. the html data is > 3Mb (pdf file ~1.6Mb) when I test it with JMeter for 50 hits the application crashes with message java.lang.OutOfMemoryError: Java heap space.
If I increase the java limit with the -Xmx option I just get some extra hits

The code i use is like this:

First clean html

```<code>public class HtmlToXhtmlConverterHTMLCleaner2 extends AbstractHtmlToXhtmlConverter
        implements IHtmlToXhtmlConverter {

    public HtmlToXhtmlConverterHTMLCleaner2(String htmlData) {
        super(htmlData);
    }

    @Override
    public void convert() {

        final HtmlCleaner cleaner =  new HtmlCleaner();

        CleanerProperties cleanerProperties = cleaner.getProperties();
        cleanerProperties.setAdvancedXmlEscape(true);
        cleanerProperties.setOmitXmlDeclaration(true);
        cleanerProperties.setOmitDoctypeDeclaration(false);
        cleanerProperties.setTranslateSpecialEntities(true);
        cleanerProperties.setTransResCharsToNCR(true);
        cleanerProperties.setRecognizeUnicodeChars(true);
        cleanerProperties.setIgnoreQuestAndExclam(true);
        cleanerProperties.setUseEmptyElementTags(false);
        cleanerProperties.setPruneTags("script");

        final XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);

        try {

            final TagNode rootTagNode = cleaner.clean(htmlData);

            this.xhtmlData = xmlSerializer.getAsString(rootTagNode);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
</code>```

then convert cleaned html to pdf

```<code>public class PDFConverterHtmlToPdf extends AbstractPDFConverter implements IPDFConverter {

    ByteArrayOutputStream psfData;

       public PDFConverterHtmlToPdf(String xhtmlData, String cssFile) {
        super();
        this.xhtmlData = xhtmlData;
        this.cssFile = cssFile;
    }

   @Override
    public void convert() {

            pdfData = new ByteArrayOutputStream();
            try {

                // There are more options on the builder than shown below.
                PdfRendererBuilder builder = new PdfRendererBuilder();
                 if(cssFile != null && cssFile.length() > 0){
                    builder.withHtmlContent(xhtmlData, cssFile);
                 } else {
                     builder.withHtmlContent(xhtmlData, "");
                 }
                builder.toStream(pdfData);
                builder.run();
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

}
</code>```

then send data from strus2 action to request

```<code> private void buildPdfContent(String htmlContent) {
        String pdfConverterCssFile = "http://localhost:8080/DocumentConverterApi/css/htmlToPdf.css";
        PDFConverterHelp pdfConverterHelp = new PDFConverterHelp("demo.pdf",
                htmlContent, pdfConverterCssFile);
        pdfConverterHelp.build();
        inputStream = new ByteArrayInputStream(pdfConverterHelp.getPDFFile().toByteArray());
        pdfConverterHelp.closePdfData();
        contentDisposition = "inline;filename=\"" + "demo.pdf\"";
    }
</code>```

I'm doing something wron?

Is there any other way to implement it without the risk of crashing the application?

ContentLicense: CC BY-SA 4.0

Body:
I have implemented html to pdf conversion using openhtmltopdf and I use it in Struts 2 action and it works very well. However, in the case of very large data, e.g. the html data is > 3Mb (pdf file ~1.6Mb) when I test it with JMeter for 50 hits the application crashes with message java.lang.OutOfMemoryError: Java heap space.
If I increase the java limit with the -Xmx option I just get some extra hits

The code i use is like this:

First clean html

public class HtmlToXhtmlConverterHTMLCleaner2 extends AbstractHtmlToXhtmlConverter
        implements IHtmlToXhtmlConverter {

    public HtmlToXhtmlConverterHTMLCleaner2(String htmlData) {
        super(htmlData);
    }

    @Override
    public void convert() {

        final HtmlCleaner cleaner =  new HtmlCleaner();

        CleanerProperties cleanerProperties = cleaner.getProperties();
        cleanerProperties.setAdvancedXmlEscape(true);
        cleanerProperties.setOmitXmlDeclaration(true);
        cleanerProperties.setOmitDoctypeDeclaration(false);
        cleanerProperties.setTranslateSpecialEntities(true);
        cleanerProperties.setTransResCharsToNCR(true);
        cleanerProperties.setRecognizeUnicodeChars(true);
        cleanerProperties.setIgnoreQuestAndExclam(true);
        cleanerProperties.setUseEmptyElementTags(false);
        cleanerProperties.setPruneTags("script");

        final XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);

        try {

            final TagNode rootTagNode = cleaner.clean(htmlData);

            this.xhtmlData = xmlSerializer.getAsString(rootTagNode);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

then convert cleaned html to pdf

public class PDFConverterHtmlToPdf extends AbstractPDFConverter implements IPDFConverter {

    ByteArrayOutputStream psfData;

       public PDFConverterHtmlToPdf(String xhtmlData, String cssFile) {
        super();
        this.xhtmlData = xhtmlData;
        this.cssFile = cssFile;
    }

   @Override
    public void convert() {

            pdfData = new ByteArrayOutputStream();
            try {

                // There are more options on the builder than shown below.
                PdfRendererBuilder builder = new PdfRendererBuilder();
                 if(cssFile != null && cssFile.length() > 0){
                    builder.withHtmlContent(xhtmlData, cssFile);
                 } else {
                     builder.withHtmlContent(xhtmlData, "");
                 }
                builder.toStream(pdfData);
                builder.run();
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

}

then send data from strus2 action to request

 private void buildPdfContent(String htmlContent) {
        String pdfConverterCssFile = "http://localhost:8080/DocumentConverterApi/css/htmlToPdf.css";
        PDFConverterHelp pdfConverterHelp = new PDFConverterHelp("demo.pdf",
                htmlContent, pdfConverterCssFile);
        pdfConverterHelp.build();
        inputStream = new ByteArrayInputStream(pdfConverterHelp.getPDFFile().toByteArray());
        pdfConverterHelp.closePdfData();
        contentDisposition = "inline;filename=\"" + "demo.pdf\"";
    }

I'm doing something wron?

Is there any other way to implement it without the risk of crashing the application?


问:
spark/scala - How to create map from dataframe. Key first string column, value second string column
spark/scala - How to create map from dataframe. Key first string column, value second string column

df:

```<code>column 1 | column 2
-------- | -------------
abc      | ssasgsaljsdfj
def      | asdfoaonefinf
</code>```

Expected Output

```<code>scala.collection.Map[String,String] = Map(abc -> ssasgsaljsdfj, def -> asdfoaonefinf)
</code>```

If i use below code then it is creating map with key as 0, 1, ...   and value as tuple(column1,column2),...

```<code>df.rdd.map(x=>  (x.getString(0),x.getString(1))).collectAsMap()
</code>```

current output:

```<code>scala.collection.Map[Int,String] = Map(0 -> (abc,ssasgsaljsdfj), 1 -> (def,asdfoaonefinf))
</code>```

Body:
spark/scala - How to create map from dataframe. Key first string column, value second string column

df:

column 1 | column 2
-------- | -------------
abc      | ssasgsaljsdfj
def      | asdfoaonefinf

Expected Output

scala.collection.Map[String,String] = Map(abc -> ssasgsaljsdfj, def -> asdfoaonefinf)

If i use below code then it is creating map with key as 0, 1, ...   and value as tuple(column1,column2),...

df.rdd.map(x=>  (x.getString(0),x.getString(1))).collectAsMap()

current output:

scala.collection.Map[Int,String] = Map(0 -> (abc,ssasgsaljsdfj), 1 -> (def,asdfoaonefinf))


问:
Input dispatching timed out with HttpURLConnection.getResponseCode()
I get lot of ANR reports (google play console) for which I have no clue how to solve it. I wrapped the problematic code with try and catch, but still it hangs at a specific codeline. I myself can't reproduce, but I ANR reports in the console.

Does anyone that understands the exception below in combination with the code and knows how to handle it?

```<code>private static boolean urlExists(String urlString) {
    HttpURLConnection huc;
    try {
        URL url = new URL(urlString);
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        int responseCode = huc.getResponseCode(); <-------------- line 246. Here is the problem.
        return responseCode != 404;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
</code>```

ANR Report looks like this:

```<code>Thread

"main" tid=1 Native

  #00  pc 0x000000000009b114  /apex/com.android.runtime/lib/bionic/libc.so (recvfrom+16)
  #01  pc 0x000000000001aceb  /apex/com.android.art/lib/libopenjdk.so (NET_Read+36)
  #02  pc 0x000000000001b3d5  /apex/com.android.art/lib/libopenjdk.so (SocketInputStream_socketRead0+176)
  at java.net.SocketInputStream.socketRead0 (Native method)
  at java.net.SocketInputStream.socketRead (SocketInputStream.java:118)
  at java.net.SocketInputStream.read (SocketInputStream.java:173)
  at java.net.SocketInputStream.read (SocketInputStream.java:143)
  at com.android.okhttp.okio.Okio$2.read (Okio.java:138)
  at com.android.okhttp.okio.AsyncTimeout$2.read (AsyncTimeout.java:213)
  at com.android.okhttp.okio.RealBufferedSource.indexOf (RealBufferedSource.java:307)
  at com.android.okhttp.okio.RealBufferedSource.indexOf (RealBufferedSource.java:301)
  at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:197)
  at com.android.okhttp.internal.http.Http1xStream.readResponse (Http1xStream.java:188)
  at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders (Http1xStream.java:129)
  at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse (HttpEngine.java:750)
  at com.android.okhttp.internal.http.HttpEngine.readResponse (HttpEngine.java:622)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute (HttpURLConnectionImpl.java:475)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse (HttpURLConnectionImpl.java:411)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode (HttpURLConnectionImpl.java:542)
  at mycompany.mypackage.images.ImageFetcher.urlExists (ImageFetcher.java:246)
</code>```

Body:
I get lot of ANR reports (google play console) for which I have no clue how to solve it. I wrapped the problematic code with try and catch, but still it hangs at a specific codeline. I myself can't reproduce, but I ANR reports in the console.

Does anyone that understands the exception below in combination with the code and knows how to handle it?

private static boolean urlExists(String urlString) {
    HttpURLConnection huc;
    try {
        URL url = new URL(urlString);
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        int responseCode = huc.getResponseCode(); <-------------- line 246. Here is the problem.
        return responseCode != 404;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

ANR Report looks like this:

Thread

"main" tid=1 Native

  #00  pc 0x000000000009b114  /apex/com.android.runtime/lib/bionic/libc.so (recvfrom+16)
  #01  pc 0x000000000001aceb  /apex/com.android.art/lib/libopenjdk.so (NET_Read+36)
  #02  pc 0x000000000001b3d5  /apex/com.android.art/lib/libopenjdk.so (SocketInputStream_socketRead0+176)
  at java.net.SocketInputStream.socketRead0 (Native method)
  at java.net.SocketInputStream.socketRead (SocketInputStream.java:118)
  at java.net.SocketInputStream.read (SocketInputStream.java:173)
  at java.net.SocketInputStream.read (SocketInputStream.java:143)
  at com.android.okhttp.okio.Okio$2.read (Okio.java:138)
  at com.android.okhttp.okio.AsyncTimeout$2.read (AsyncTimeout.java:213)
  at com.android.okhttp.okio.RealBufferedSource.indexOf (RealBufferedSource.java:307)
  at com.android.okhttp.okio.RealBufferedSource.indexOf (RealBufferedSource.java:301)
  at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict (RealBufferedSource.java:197)
  at com.android.okhttp.internal.http.Http1xStream.readResponse (Http1xStream.java:188)
  at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders (Http1xStream.java:129)
  at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse (HttpEngine.java:750)
  at com.android.okhttp.internal.http.HttpEngine.readResponse (HttpEngine.java:622)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute (HttpURLConnectionImpl.java:475)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse (HttpURLConnectionImpl.java:411)
  at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode (HttpURLConnectionImpl.java:542)
  at mycompany.mypackage.images.ImageFetcher.urlExists (ImageFetcher.java:246)


问:
nodeJS : Connection between tables within a JSON structure
I have a Question object and a Tags object
Tags contains the topics that match the question
Each question can have several tags
I want to connect them in a one-to-many relationship but I dont know how.

my code:

Question.Json:

```<code>`[
    {
        "id": "0f16b716-450c-4468-8096-74e6e4d4c16f",
        "lastUpdate": "13/01/2023 09:13:15",
        "title": "aaa",
        "typeId": 1,
        "textBelow": "aaa",
        "tags": [
            {
                "id": "57f2aa4c-5ad2-438a-a1b4-9c5c018d66b4",
                "name": "math"
            }
        ]
    }
]`
</code>```

Tags.Json:

```<code>`[
    {
        "id": "57f2aa4c-5ad2-438a-a1b4-9c5c018d66b4",
        "name": "math"
    }
]
`
</code>```

my Repositorey:

```<code>const { readFile, updateItem, removeItem, insertItem } = require('../fs/fs');
const { v4 } = require('uuid');

class DBQuestionsRepository {
  async getAllQuestions() {
    const data = await readFile('./data/jsonAsDb.json');
    const types = await readFile('./data/questionType.json');
    data.forEach((data) => {
      data.type = types.find((type) => type.id === Number(data.typeId));
      delete data.typeId;
    });
    return data;
  }

  async addQuestion(body) {
    const currentDate = new Date();
    const formattedDate = `${currentDate.getDate().toString().padStart(2, '0')}/${(currentDate.getMonth() + 1).toString().padStart(2, '0')}/${currentDate.getFullYear()} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`;
    const item = insertItem
    ('./data/jsonAsDb.json', { id: v4(), lastUpdate: formattedDate,...body });
    return item;
  }
  async getQuestionById(id) {
    const data = await readFile('./data/jsonAsDb.json');
    const item = data.find(i => i.id === id);
    return item;
  }
</code>```

I tried to connect the tables

Body:
I have a Question object and a Tags object
Tags contains the topics that match the question
Each question can have several tags
I want to connect them in a one-to-many relationship but I dont know how.

my code:

Question.Json:

`[
    {
        "id": "0f16b716-450c-4468-8096-74e6e4d4c16f",
        "lastUpdate": "13/01/2023 09:13:15",
        "title": "aaa",
        "typeId": 1,
        "textBelow": "aaa",
        "tags": [
            {
                "id": "57f2aa4c-5ad2-438a-a1b4-9c5c018d66b4",
                "name": "math"
            }
        ]
    }
]`

Tags.Json:

`[
    {
        "id": "57f2aa4c-5ad2-438a-a1b4-9c5c018d66b4",
        "name": "math"
    }
]
`

my Repositorey:

const { readFile, updateItem, removeItem, insertItem } = require('../fs/fs');
const { v4 } = require('uuid');

class DBQuestionsRepository {
  async getAllQuestions() {
    const data = await readFile('./data/jsonAsDb.json');
    const types = await readFile('./data/questionType.json');
    data.forEach((data) => {
      data.type = types.find((type) => type.id === Number(data.typeId));
      delete data.typeId;
    });
    return data;
  }

  async addQuestion(body) {
    const currentDate = new Date();
    const formattedDate = `${currentDate.getDate().toString().padStart(2, '0')}/${(currentDate.getMonth() + 1).toString().padStart(2, '0')}/${currentDate.getFullYear()} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`;
    const item = insertItem
    ('./data/jsonAsDb.json', { id: v4(), lastUpdate: formattedDate,...body });
    return item;
  }
  async getQuestionById(id) {
    const data = await readFile('./data/jsonAsDb.json');
    const item = data.find(i => i.id === id);
    return item;
  }

I tried to connect the tables


问:
How to make competitive coding solutions more efficient (BIT wise operations)?
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div  4):

(Problem) Chef has an array A of length N.  Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .

Determine the minimum possible value of X. If no possible value of X exists, output -1.

Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .

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

int* binary_number(int n)     // returns pointer to a array of length 20(based on given constrains)     representing binary
{
    int* ptc;
    ptc = (int*) malloc(20*sizeof(int));
    for(int i = 0; i < 20; i++)
    {
        if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
        else {*(ptc + i) = 0;}
        n = n % (int) pow(2,19-i) ;
    }
    return ptc;
}

int or_value(int* ptc, int n)    // Takes in pointers containing 1 or zero and gives the logical OR
{
    for(int k = 0; k < n; n++)
    {
        if(*ptc == *(ptc + 20*k)){continue;}        // pointers are 20 units apart
        else{return 1;break;}
    }

    return *ptc;

}

int main(void) {

int t; scanf("%d", &t);

for (int i = 0; i < t; i++)
{
    int n, y;
    scanf("%d %d", &n, &y);
    int a[n];

    for(int j = 0; j < n ; j++)
    {
        scanf("%d", &a[j]);
    }

    int b[20*n];
    for (int j = 0; j < n; j++)
    {
        for (int k = 0; k < 20; k++)
        {
            b[20*j + k] = *(binary_number(a[n])+k);
        }
    }

    int c = 0;
    int p = 0;
    for (int j = 0; j < 20; j++)
    {

        if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
        else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
    }

    if (p==1){printf("-1");}
    else {printf("%d\n", c);}
}

return 0;
}
</code>```

Body:
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div  4):

(Problem) Chef has an array A of length N.  Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .

Determine the minimum possible value of X. If no possible value of X exists, output -1.

Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .

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

int* binary_number(int n)     // returns pointer to a array of length 20(based on given constrains)     representing binary
{
    int* ptc;
    ptc = (int*) malloc(20*sizeof(int));
    for(int i = 0; i < 20; i++)
    {
        if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
        else {*(ptc + i) = 0;}
        n = n % (int) pow(2,19-i) ;
    }
    return ptc;
}

int or_value(int* ptc, int n)    // Takes in pointers containing 1 or zero and gives the logical OR
{
    for(int k = 0; k < n; n++)
    {
        if(*ptc == *(ptc + 20*k)){continue;}        // pointers are 20 units apart
        else{return 1;break;}
    }

    return *ptc;

}

int main(void) {

int t; scanf("%d", &t);

for (int i = 0; i < t; i++)
{
    int n, y;
    scanf("%d %d", &n, &y);
    int a[n];

    for(int j = 0; j < n ; j++)
    {
        scanf("%d", &a[j]);
    }

    int b[20*n];
    for (int j = 0; j < n; j++)
    {
        for (int k = 0; k < 20; k++)
        {
            b[20*j + k] = *(binary_number(a[n])+k);
        }
    }

    int c = 0;
    int p = 0;
    for (int j = 0; j < 20; j++)
    {

        if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
        else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
    }

    if (p==1){printf("-1");}
    else {printf("%d\n", c);}
}

return 0;
}


问:
Cordova redirecting to a downloaded file within Library
I am using cordova-app-updater and cordova-plugin-file to download an amended html file from a remote server and then redirect the app to it.

The plugin allows the file to be downloaded to file:///var/mobile/Containers/Data/Application/7465E774.../Library/files/cache[custom]/www[custom]/ and redirects the app to the downloaded file.

I can download the file but when I try to redirect to it window.location.href = file:///var/mobile/Containers/Data/Application/7465E774.../Library/files/cache/www/index.html I receive the message [Not allowed to load local resource].

It sounds like a permissions problem with IOS (I havent tried Android yet) but I have searched for days and and got no closer.

My config.xml has:

```<code><preference name="iosPersistentFileLocation" value="Library" >
<preference name="allowFileAccessFromFileURLs" value="true" />
<preference name="allowUniversalAccessFromFileURLs" value="true" />
<access origin='*' allows-arbitrary-loads-for-media='true' allows-arbitrary-loads-in-web-content='true' allows-local-networking='true' />
<preference name="scheme" value="app" />
</code>```

Body:
I am using cordova-app-updater and cordova-plugin-file to download an amended html file from a remote server and then redirect the app to it.

The plugin allows the file to be downloaded to file:///var/mobile/Containers/Data/Application/7465E774.../Library/files/cache[custom]/www[custom]/ and redirects the app to the downloaded file.

I can download the file but when I try to redirect to it window.location.href = file:///var/mobile/Containers/Data/Application/7465E774.../Library/files/cache/www/index.html I receive the message [Not allowed to load local resource].

It sounds like a permissions problem with IOS (I havent tried Android yet) but I have searched for days and and got no closer.

My config.xml has:

<preference name="iosPersistentFileLocation" value="Library" >
<preference name="allowFileAccessFromFileURLs" value="true" />
<preference name="allowUniversalAccessFromFileURLs" value="true" />
<access origin='*' allows-arbitrary-loads-for-media='true' allows-arbitrary-loads-in-web-content='true' allows-local-networking='true' />
<preference name="scheme" value="app" />


问:
CSS How to selector previous element
I want to select class AAA if class BBB has class CCC

.AAA+.CCC {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="AAA">Test1</div> <!-- red color -->
<div class="BBB CCC">Test2</div>
<div class="AAA">Test3</div>
<div class="BBB">Test4</div></code>```

Title: CSS How to selector previous element

Body:
I want to select class AAA if class BBB has class CCC

.AAA+.CCC {
  color: red;
}

Test1

Test2

Test3

Test4


问:
how can I use multiple ModelMetaDataProvider's w/asp.net-mvc3
I have a custom ModelMetadataProvider which takes care of everything so far. But I have a couple of new classes where I am going to let users customize the metadata in the database and store settings like display name, sql query for combo's and some other stuff like that.

Well I am happy with my current ModelMetadataProvider, so I do not want to inject new functionality into it, I'd rather have a new ModelMetadataProvider for this, and a way of telling the !dependency resolver! to pick the right  data provider for a given class?

Is this possible, and if so how?
Thanks in advance...

ContentLicense: CC BY-SA 3.0


问:
dotnet restore is taking too much time on gitlab-ci
I've set up a dotnet solution in Gitlab-CI for almost 6 months, and recently, job are slowing when pipelines are triggered.
From at most 5 minutes, my jobs are now failing due to timeout limitation of 1 hour.

I'd like diagnose the issue, but the verbosity in dotnet restore does not show significant information for me.

My CI config is as follows :

```<code>image: mcr.microsoft.com/dotnet/sdk:6.0

variables:
  PROJECT_NAME: "App"
before_script:
  - echo "starting build for $PROJECT_NAME"
  - echo "Restoring NuGet Packages..."
  - dotnet restore "$PROJECT_NAME.sln"

stages:
  - build
  - test
  - deploy
build:
  stage: build
  script:
    - cp src/Server/appsettings.json.default src/Server/appsettings.json
    - cp src/Server/appsettings.json.default src/Server/appsettings.Development.json
    - echo "Release build..."
    - dotnet build -v n "$PROJECT_NAME.sln"
  only:
    - Develop
</code>```

The output of a job

```<code>Running with gitlab-runner 14.1.0 (8925d9a0)
  on run_sentry.otr.lan qxRh1bkx

Preparing the "docker" executor
00:08
Using Docker executor with image mcr.microsoft.com/dotnet/sdk:6.0 ...
Pulling docker image mcr.microsoft.com/dotnet/sdk:6.0 ...
Using docker image sha256:6a9a891a94b307091a0366de4d0aa755b5cbf24204a5a25e7fe83322b607d491 for mcr.microsoft.com/dotnet/sdk:6.0 with digest mcr.microsoft.com/dotnet/sdk@sha256:23abf93a047e6f1bf1659bd0ff787facd6c80dcbf3421dd655f10bac209d1fde ...
Preparing environment
00:01
Running on runner-qxrh1bkx-project-141-concurrent-0 via run_sentry.otr.lan...
Getting source from Git repository
00:04
Fetching changes with git depth set to 50...
Initialized empty Git repository in /builds/dccfe/cadastre/front-end/.git/
Created fresh repository.
Checking out 61878ffe as feature/Opposition...
Skipping Git submodules setup
Executing "step_script" stage of the job script
59:47
Using docker image sha256:6a9a891a94b307091a0366de4d0aa755b5cbf24204a5a25e7fe83322b607d491 for mcr.microsoft.com/dotnet/sdk:6.0 with digest mcr.microsoft.com/dotnet/sdk@sha256:23abf93a047e6f1bf1659bd0ff787facd6c80dcbf3421dd655f10bac209d1fde ...
$ echo "starting build for $PROJECT_NAME"
starting build for Otr.Dccfe
$ echo "Restoring NuGet Packages..."
Restoring NuGet Packages...
$ dotnet restore "$PROJECT_NAME.sln"
  Determining projects to restore...
  Restored /builds/dccfe/cadastre/front-end/src/Shared/Shared.csproj (in 24.86 sec).
  Restored /builds/dccfe/cadastre/front-end/src/Domain/Domain.csproj (in 24.86 sec).
ERROR: Job failed: execution took longer than 1h0m0s seconds
</code>```

Body:
I've set up a dotnet solution in Gitlab-CI for almost 6 months, and recently, job are slowing when pipelines are triggered.
From at most 5 minutes, my jobs are now failing due to timeout limitation of 1 hour.

I'd like diagnose the issue, but the verbosity in dotnet restore does not show significant information for me.

My CI config is as follows :

image: mcr.microsoft.com/dotnet/sdk:6.0

variables:
  PROJECT_NAME: "App"
before_script:
  - echo "starting build for $PROJECT_NAME"
  - echo "Restoring NuGet Packages..."
  - dotnet restore "$PROJECT_NAME.sln"

stages:
  - build
  - test
  - deploy
build:
  stage: build
  script:
    - cp src/Server/appsettings.json.default src/Server/appsettings.json
    - cp src/Server/appsettings.json.default src/Server/appsettings.Development.json
    - echo "Release build..."
    - dotnet build -v n "$PROJECT_NAME.sln"
  only:
    - Develop

The output of a job

Running with gitlab-runner 14.1.0 (8925d9a0)
  on run_sentry.otr.lan qxRh1bkx

Preparing the "docker" executor
00:08
Using Docker executor with image mcr.microsoft.com/dotnet/sdk:6.0 ...
Pulling docker image mcr.microsoft.com/dotnet/sdk:6.0 ...
Using docker image sha256:6a9a891a94b307091a0366de4d0aa755b5cbf24204a5a25e7fe83322b607d491 for mcr.microsoft.com/dotnet/sdk:6.0 with digest mcr.microsoft.com/dotnet/sdk@sha256:23abf93a047e6f1bf1659bd0ff787facd6c80dcbf3421dd655f10bac209d1fde ...
Preparing environment
00:01
Running on runner-qxrh1bkx-project-141-concurrent-0 via run_sentry.otr.lan...
Getting source from Git repository
00:04
Fetching changes with git depth set to 50...
Initialized empty Git repository in /builds/dccfe/cadastre/front-end/.git/
Created fresh repository.
Checking out 61878ffe as feature/Opposition...
Skipping Git submodules setup
Executing "step_script" stage of the job script
59:47
Using docker image sha256:6a9a891a94b307091a0366de4d0aa755b5cbf24204a5a25e7fe83322b607d491 for mcr.microsoft.com/dotnet/sdk:6.0 with digest mcr.microsoft.com/dotnet/sdk@sha256:23abf93a047e6f1bf1659bd0ff787facd6c80dcbf3421dd655f10bac209d1fde ...
$ echo "starting build for $PROJECT_NAME"
starting build for Otr.Dccfe
$ echo "Restoring NuGet Packages..."
Restoring NuGet Packages...
$ dotnet restore "$PROJECT_NAME.sln"
  Determining projects to restore...
  Restored /builds/dccfe/cadastre/front-end/src/Shared/Shared.csproj (in 24.86 sec).
  Restored /builds/dccfe/cadastre/front-end/src/Domain/Domain.csproj (in 24.86 sec).
ERROR: Job failed: execution took longer than 1h0m0s seconds


问:
AWS ELB- HealthChecker sends unique request to app from different virtual hosts
Currently hosting a nodeJS API back-end using AWS Elastic Beanstalk, where all unique requests generates a session data (IP address, userAgent...), and the session data is stored as a mongoDB document. However, I recently noticed that ELB-HealthChecker/2.0 sends unique request after about 30sec, thereby creating a new session, which will result in my app reaching the dreaded 16MB document limit of mongoDB in no time. I want to solve this by ensuring that ELB-HealthChecker sends non-unique request. However, this approach depends if the ELB-HealthChecker stores Cookies (as the app uses request cookies to identify unique requests).

Questions:

Is the approach above feasible? If yes, how do I ensure ELB-HealthChecker/2.0 sends request from a single virtual host?

What better (scalable, sustainable) way(s) is there to solve this problem.

I have tried extending the ELB-HealthChecker/2.0 interval, but this is not healthy for the app, and it still does not solve the underlying issue.

I have tried checking userAgent for ELB-HealthChecker/2.0, but this will have to change if the hosting provider is changed.


问:
Amplify Datastore.Observe skipping subscription

I configure my Datastore with sync Expression like this

```<code>syncExpression(MyTable, () => {
 return data => data.tenant_id('eq', "123")
 }
</code>```

i recieve all updation in datastore.observe() but when i update "tenant_id" 123 to 345 then datastore subscription doesnot work on this case.

How do i get change in datastore on doing this scenario, I want subscription on this case to complete my relevant task

Body:
I configure my Datastore with sync Expression like this

syncExpression(MyTable, () => {
 return data => data.tenant_id('eq', "123")
 }

i recieve all updation in datastore.observe() but when i update "tenant_id" 123 to 345 then datastore subscription doesnot work on this case.

How do i get change in datastore on doing this scenario, I want subscription on this case to complete my relevant task


问:
Why does my app behave strangely on Android 13?
Do you have any idea what could be the possible causes for the next app strange behavior on Android 13?
Recently (6th January 2023) I published my android game, Focus Pocus, on Google Play. Game link: https://play.google.com/store/apps/details?id=com.JarekApps.FocusPocus

It works as expected on Android versions older than Android 13. It used to work ok also on Android 13, but after last Android 13 software update, android draws a thin white horizontal line at the top of the screen, over my game. It is like a line under the Android notification bar (exactly under the front camera of my Samsung Galaxy A53).
Basically, the game has the portrait screen divided in two: the top half is a canvas and the bottom half is a table arrangement with buttons.
In android 13, the canvas part doesn't work well...if I hold the finger on the image sprite in the canvas (the floating number) while i click the same number on the keyboard, it doesn't work or the sprite is "jumpping" to another position and i lose a life in the game (it should not have this behavior).
The strange thing is that if i restart my phone, THE FIRST TIME when i play the game after the phone restart, it works as expected, but, after i close the game and reopen it, Android 13 makes the changes with the line and the canvas/touch bugs appear.
My game targets API 31
I tested it on another phone with Android 13 (samsung galaxy A51) and it has the same problem.
Thanks in advance for your suggestions.


问:
How to exit a pygame.midi script properly (to make the midi synthesizer available again)
Trying to replicate Playing note with pygame.midi I'm doing the following to listen to MIDI output generated by a Python script:

Run TiMidity to have a MIDI synthesizer

```<code>timidity -iA
</code>```

Run a Python script which outputs just one note and then exits:

```<code>import pygame.midi
import time

pygame.midi.init()

player = pygame.midi.Output(5)

player.set_instrument(0)
time.sleep(1)
player.note_on(64, 127)
time.sleep(1)
player.note_off(64, 127)

# (sleep() statements to avoid race conditions)
time.sleep(1)
player.close()        # just tried it, without effect..
time.sleep(1)
del player            # for some reasons tutorials tell me to `del` the output instance
pygame.midi.quit()
</code>```

This scripts works insofar it's playing note_on(64, 127) and note_off(64, 127) but only once. After running the script the first time, timidity doesn't play anything any more and I have to restart it to get it running again.

I tried to close() player, to del it, quit() the midi interface, and any possible combination and I even introduced some sleep() statements in order to make sure, it's not some race condition thing. All with no effect.

What am I doing wrong here? Is there a way to reliably close/terminate the midi output to be able to re-use it?

Body:
Trying to replicate Playing note with pygame.midi I'm doing the following to listen to MIDI output generated by a Python script:

Run TiMidity to have a MIDI synthesizer

timidity -iA

Run a Python script which outputs just one note and then exits:

import pygame.midi
import time

pygame.midi.init()

player = pygame.midi.Output(5)

player.set_instrument(0)
time.sleep(1)
player.note_on(64, 127)
time.sleep(1)
player.note_off(64, 127)

# (sleep() statements to avoid race conditions)
time.sleep(1)
player.close()        # just tried it, without effect..
time.sleep(1)
del player            # for some reasons tutorials tell me to `del` the output instance
pygame.midi.quit()

This scripts works insofar it's playing note_on(64, 127) and note_off(64, 127) but only once. After running the script the first time, timidity doesn't play anything any more and I have to restart it to get it running again.

I tried to close() player, to del it, quit() the midi interface, and any possible combination and I even introduced some sleep() statements in order to make sure, it's not some race condition thing. All with no effect.

What am I doing wrong here? Is there a way to reliably close/terminate the midi output to be able to re-use it?


问:
.NET: Add .dll app.config settings to parent's web.config?
I have a class library project "A" with some web references that are added to its app.config as following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>
    </configSections>
    <applicationSettings>
        <projA.Properties.Settings>
            <setting name="projA_wsA_SrvA" serializeAs="String">
                <value>http://...</value>
            </setting>
            <setting name="projA_wsB_SrvB" serializeAs="String">
                <value>http://...</value>
            </setting>
        </projA.Properties.Settings>
    </applicationSettings>
</configuration>
```

Then I have a "B" project where I include "A" as a nuget package.

When adding, no <projA.Properties.Settings> is included on "B" web.config.

If I manually add that section to the "B" project's web.config, the .dll takes the URL from the "B" project, which is is the desired behaviour (I just update the "B" web.config when deploying in prod environment).

The problem comes when I forgot adding settings on the "B" web.config. It takes "A" default setting and it fails in production environment.

Is it possible to automatically add the "A" settings when adding the nuget package on "B"?

Body:
I have a class library project "A" with some web references that are added to its app.config as following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>
    </configSections>
    <applicationSettings>
        <projA.Properties.Settings>
            <setting name="projA_wsA_SrvA" serializeAs="String">
                <value>http://...</value>
            </setting>
            <setting name="projA_wsB_SrvB" serializeAs="String">
                <value>http://...</value>
            </setting>
        </projA.Properties.Settings>
    </applicationSettings>
</configuration>

Then I have a "B" project where I include "A" as a nuget package.

When adding, no <projA.Properties.Settings> is included on "B" web.config.

If I manually add that section to the "B" project's web.config, the .dll takes the URL from the "B" project, which is is the desired behaviour (I just update the "B" web.config when deploying in prod environment).

The problem comes when I forgot adding settings on the "B" web.config. It takes "A" default setting and it fails in production environment.

Is it possible to automatically add the "A" settings when adding the nuget package on "B"?


问:
Marshmallow schema from pydantic model
Given pydantic models, what are the best/easiest ways to generate equivalent marshmallow schemas from them (if it's even possible)?

I found this snippet and some other similar links which do the opposite (generate pydantic models from marshmallow schemas), but couldn't manage to find the direction I need.

Title: Marshmallow schema from pydantic model


问:
SharePoint (SPFx) & Graph API: Where is the "access_token" stored in SharePoint client-side (or) how to read the "access_token" from Javascript?
Through SPFx, I know there is a way to retrieve "access_token" from Microsoft Graph using aadTokenProviderFactory. Such as:

```<code>this.context.aadTokenProviderFactory.getTokenProvider()
.then((tokenProvider: AadTokenProvider): Promise<string> => {
    return tokenProvider.getToken('https://graph.microsoft.com', false);
})
.then((accessToken: string): void => {
    console.log("[graph] accessToken:", accessToken);
})
.catch(error => {
    console.error(error);
});
</code>```

But

The same token was retrieved earlier by SharePoint itself which can be found inside Web-browser's "Network" logs. This very same token can be used further to call Graph API with even "delegated access".

So I'm just curious is there a simple way to just read/retrieve the same token via Javascript by looking at cookies or session storage or stored variables (without needing to use the aadTokenProviderFactory)?

Thanks!

Body:
Through SPFx, I know there is a way to retrieve "access_token" from Microsoft Graph using aadTokenProviderFactory. Such as:

this.context.aadTokenProviderFactory.getTokenProvider()
.then((tokenProvider: AadTokenProvider): Promise<string> => {
    return tokenProvider.getToken('https://graph.microsoft.com', false);
})
.then((accessToken: string): void => {
    console.log("[graph] accessToken:", accessToken);
})
.catch(error => {
    console.error(error);
});

But

The same token was retrieved earlier by SharePoint itself which can be found inside Web-browser's "Network" logs. This very same token can be used further to call Graph API with even "delegated access".

So I'm just curious is there a simple way to just read/retrieve the same token via Javascript by looking at cookies or session storage or stored variables (without needing to use the aadTokenProviderFactory)?

Thanks!


问:
Is it possible to "reset" docker from previous runs?
I am fiddling with a MLFlow + MinIO docker set up, at the moment doing it locally and I have nothing important in the docker, I'm just learning.

Trying to update the MinIO docker image to a jan 2023 one, I am greeted with an error message regarding /data backends, which could be solved using this issue. However, as I said, I'm inexperienced with this stack (so the task seems daunting to me) and also I don't have anything worh saving and/or migrating from the previous docker, so my question is:

how would I "reset" whatever cache docker has from previous image runs so I start anew?


问:
Formatting a Double to show only the first 2 decimals
I have a management software for invoices that creates a pdf document with the values inputed by the user in the various fields (product's price, quantity, reference etc.).

I need to modify the code that controls the displaying of the product's price to obtain the price always formatted to show only the first two decimals.

Example: when the user inputs the value 12,36789 €, in the pdf this value is displayed exactly as it is (12,36789 €); I would like to display 12,36 €.

The code is the following:
$V{Formatter}.format(new Double($F{importoUnitario}.replaceAll(",",".")))+" "+$P{valutaSimbolo}

the first part
$V{Formatter}.format(new Double($F{importoUnitario}.replaceAll(",",".")))
controls the value itself (12,36)

the middle part
+" "
it's just a blank space between the value and the symbol

the last part
+$P{valutaSimbolo}
is the currency symbol

How do I do this?


问:
Airflow 2.x PythonSensor failing for STS token expiration
Requirement : Trigger a script placed in EC2 machine and monitor its run. script can run for several hours.

Design:

create boto3 sts client, do an assume role and push credentials(access key, secret key and STS token) in xcoms. All this is in refresh_credential() function

create ssm client by pulling credentials from xcoms.

Use ssm_client.send_command() to trigger the command

Use a python sensor to call a function is_complete() to poke for the status every 60 sec. ssm_client is again created by pulling credentials from xcoms and poke is done using ssm_client.list_command_invocations()

Issue: Python sensor is failing as the STS token is getting expired after 60 min (as per the design).

Tried Solution: Catch the Timeout exception in is_complete() function and do a credential refresh by calling refresh_credential() function (Step 1)
This solution is not working, I am able to catch the exception but while calling refresh_credentials it is failing with below error 'exception': KeyError {'task_instance'}

Expecting: I was expecting refresh_credential() function to push the new credential in xcom and my python sensor to use it for polling.


问:
Unable to post form data using axios in Reactjs
i am working with Reactjs and i am using nextjs framework,Right now i am trying to post "Formdata"
using "axios" but unable to get anything in server(api side),I tried with 2 different way

```<code>var emails=email;
      var passwords=password;

      const data = {
        email: emails,
        password: passwords
      };
</code>```

I tried with following way

```<code> axios.post('https://xxxxxxxxxxxx.com/email-monitor/api/testinfo3/', data).then(function (response) {
            console.log(response);
      })

</code>```

I tried with following code also but not working for me

```<code>formData.append('email', emails);
formData.append('password', password);

const response = await axios({
    method: "post",
    url: "https://xxxxxxxxxxxx.com/email-monitor/api/testinfo3/",
    data: FormData,
    headers: { "Content-Type": "multipart/form-data" },
  }).then(function (response) {
     alert(response);
    }).catch(function (error) {
    alert('error is ' + error);
    });
</code>```

Body:
i am working with Reactjs and i am using nextjs framework,Right now i am trying to post "Formdata"
using "axios" but unable to get anything in server(api side),I tried with 2 different way

var emails=email;
      var passwords=password;

      const data = {
        email: emails,
        password: passwords
      };

I tried with following way

 axios.post('https://xxxxxxxxxxxx.com/email-monitor/api/testinfo3/', data).then(function (response) {
            console.log(response);
      })

I tried with following code also but not working for me

formData.append('email', emails);
formData.append('password', password);

const response = await axios({
    method: "post",
    url: "https://xxxxxxxxxxxx.com/email-monitor/api/testinfo3/",
    data: FormData,
    headers: { "Content-Type": "multipart/form-data" },
  }).then(function (response) {
     alert(response);
    }).catch(function (error) {
    alert('error is ' + error);
    });


问:
Pie chart - legend between two values
In google sheets I trie to make a pie chart.
I want to change my legend.

My example:

Example

The values are 1, 2, 8, 12. They are shown all seperate on the pie chart.

I want to change my legend to: 0-6 and 7-14

So 1 & 2 would be in 0-6 and 8 & 12 would be in 7-14.
With this the pie chart would be 50% 0-6 and 50% 7-14

I don't see so much possibilities to change the legend.
Is there a way to fix this?

Title: Pie chart - legend between two values


问:
Laravel model factory seeder assigning two models to a model
I'm working on a Laravel 9 project and need to create mass amounts of test data. I have a few models and I'd like to link them up automatically via my model factories, here's my model relationships:

User

Company - a user can have one company, but they might not have one.

Affiliate - an affiliate has a user_id column, and a nullable company_id column, thus a user that owns a company and created an affiliate would populate both these columns.

Right now, this is how I'm linking up the user_id of my models:

$users = User::factory(10)->create();

foreach ($users as $user) {
    Company::factory()->count(1)->for($user)->create();
    Country::factory()->count(10)->for($user)->create();
    Affiliate::factory()->count(25)->for($user)->create();
}
```
<p>Would I need to create another <code>->for()</code> on all of the models after the <code>Company</code> so it would look something like:</p>
<pre class="lang-php prettyprint-override"><code>$users = User::factory(10)->create();

foreach ($users as $user) {
    $company = Company::factory()->count(1)->for($user)->create();

    Country::factory()->count(10)->for($user)->for($company)->create();
    Affiliate::factory()->count(25)->for($user)->for($company)->create();
}
</code>```

So that the company and user are associated to my Affiliate?

Body:
I'm working on a Laravel 9 project and need to create mass amounts of test data. I have a few models and I'd like to link them up automatically via my model factories, here's my model relationships:

User

Company - a user can have one company, but they might not have one.

Affiliate - an affiliate has a user_id column, and a nullable company_id column, thus a user that owns a company and created an affiliate would populate both these columns.

Right now, this is how I'm linking up the user_id of my models:

$users = User::factory(10)->create();

foreach ($users as $user) {
    Company::factory()->count(1)->for($user)->create();
    Country::factory()->count(10)->for($user)->create();
    Affiliate::factory()->count(25)->for($user)->create();
}

Would I need to create another ->for() on all of the models after the Company so it would look something like:

$users = User::factory(10)->create();

foreach ($users as $user) {
    $company = Company::factory()->count(1)->for($user)->create();

    Country::factory()->count(10)->for($user)->for($company)->create();
    Affiliate::factory()->count(25)->for($user)->for($company)->create();
}

So that the company and user are associated to my Affiliate?


问:
Camunda performance for standalone edition v/s embedded edition
I am planning to use camunda in my project which is based on microservice architecture with spring boot. I have simple workflow for example from rest api it will get some data in instance and on each service it’s calling one class to print data. I checked some concepts for both edition (standalone and embedded).

Can anyone help me with some statistics data?

performance wise which one is better to use in my project? standalone or embedded?


问:
Why I got a AIC vector instead of a single value in maxnet in R
I calculated the AIC of a Maxent output from maxnet package in R. I expected a single value as in AIC for a stardanrd glm but I got a vector. I do not understand why and if it is possible to have a single value.

Example:

```<code>library(maxnet)

data("bradypus")

fit <- maxnet(p=bradypus$presence, data = bradypus[-1],
              regmult = 2,  # to adjust regularization
              classes = "q")

library(ENMeval)

p.occs <- predict(fit, bradypus, clamp=T, type = "exponential")
ncoefs <- fit$betas

aic.maxnet <- aic.maxent(p.occs, ncoefs)
head(aic.maxnet)

      AICc delta.AICc      w.AIC
1 19565.07   7.056598 0.01451207
2 19565.14   7.123900 0.01403185
3 19565.11   7.095729 0.01423089
4 19565.11   7.095745 0.01423078
5 19565.11   7.095564 0.01423206
6 19565.11   7.095450 0.01423288
</code>```

I would like to have a sigle value of AIC (or AICc), also because this is a single model.

Body:
I calculated the AIC of a Maxent output from maxnet package in R. I expected a single value as in AIC for a stardanrd glm but I got a vector. I do not understand why and if it is possible to have a single value.

Example:

library(maxnet)

data("bradypus")

fit <- maxnet(p=bradypus$presence, data = bradypus[-1],
              regmult = 2,  # to adjust regularization
              classes = "q")

library(ENMeval)

p.occs <- predict(fit, bradypus, clamp=T, type = "exponential")
ncoefs <- fit$betas

aic.maxnet <- aic.maxent(p.occs, ncoefs)
head(aic.maxnet)

      AICc delta.AICc      w.AIC
1 19565.07   7.056598 0.01451207
2 19565.14   7.123900 0.01403185
3 19565.11   7.095729 0.01423089
4 19565.11   7.095745 0.01423078
5 19565.11   7.095564 0.01423206
6 19565.11   7.095450 0.01423288

I would like to have a sigle value of AIC (or AICc), also because this is a single model.


问:
Power BI dynamic measure based on slicer
I would like to ask you for you help since I have a DAX formula added as a measure to my 'SalesTable' which contains customers and date of order I got from them.
Now I have hard coded to add blank for orders that are older than a year and true for
to add blank value for orders older than a year and true for those that are younder thank a year.

But now it is hard coded, what I would like to have is to add slicer to my visualisation to show be orders older than a minimum date that comes from this slicer so it looked dynamically?

Is that achievable? I would higly appreciate you help

```<code>NoPurchase=
var currentDate = LASTDATE('Calendar'[Date])
var pastyear = DATESBETWEEN('Calendar'[Date],DATEADD(currentDate,-1,YEAR),currentDate)
var datesinpastyear = CALCULATE(COUNTROWS('SalesTable'), 'Calendar'[Date] IN pastyear)
RETURN IF(datesinpastyear= BLANK(), TRUE, BLANK())
</code>```

Body:
I would like to ask you for you help since I have a DAX formula added as a measure to my 'SalesTable' which contains customers and date of order I got from them.
Now I have hard coded to add blank for orders that are older than a year and true for
to add blank value for orders older than a year and true for those that are younder thank a year.

But now it is hard coded, what I would like to have is to add slicer to my visualisation to show be orders older than a minimum date that comes from this slicer so it looked dynamically?

Is that achievable? I would higly appreciate you help

NoPurchase=
var currentDate = LASTDATE('Calendar'[Date])
var pastyear = DATESBETWEEN('Calendar'[Date],DATEADD(currentDate,-1,YEAR),currentDate)
var datesinpastyear = CALCULATE(COUNTROWS('SalesTable'), 'Calendar'[Date] IN pastyear)
RETURN IF(datesinpastyear= BLANK(), TRUE, BLANK())


问:
Expo/react-native what are the databases that can be integrated together in crossplatform apps
i have tested watermelon db it didnt worked well gave too many errors,
tested pouch had some problem with adapter settings
also tested realm and it also gave alot of bugs,
trying to use sqlite but now before testing something new , just want to ask others what databases can be integrate together to run a app on both ios and android without having to face much of headache, also i have searched on web and youtube no specific answers if there are they are too old like before 2020 or just irreleavant to current react/npm versions
my os: debian based Parrot os
node: 18
target-platform : android|ios|web

just a stable db which is fast , reliable and can be set up easily and can work offline

I apologize first hand but i have spent whole week on just errors and bugs so if you can help me out or just have a good options i will be happy to hear it,,


问:
Pinescript minutes and seconds plotting incorrectly
In pinescript, I have a code to plot CPR lines for the entire day wherein the lines from start to end of day are plotted per the normal Intraday session.
How can I have this for say 16 minutes and 30 seconds?

One_Day = 24 * 60 * 60 * 1000

Half_Day = ((1 * 16 * 60 * 1000) + (1 * 30 * 60 * 1000))

The below plots the first 16 minutes and 30 seconds perfectly but fails to do from the second 16 minutes and 30 seconds trading session. So basically the need is to break a trading session to half and thereafter making further cuts to the session. Meaning a 450 minute session can be minimum of 15 minute each to a maximum of 225 minute which will be termed as the half of that scripts trading session in a day.

```<code>//@version=5
indicator(title="Test", shorttitle="Test", overlay= true, max_labels_count=500, max_lines_count=500,  max_boxes_count=500)
T0 = "Small font size recommended for mobile app or multiple layout"
Transparency = input(defval=75)
i_s_font    = input.string("normal",       "Font size", tooltip = T0, options = ["tiny", "small",  "normal", "large", "huge"])
tointeger    = input.int(defval = 1, title = "To Integer")

i_timeZone = input('GMT+05:30')
f_print(_txt) =>
    var _lbl = label.new(bar_index, ta.highest(10)[1], _txt, xloc.bar_index, yloc.price, #00000000, label.style_none, color.black, size.tiny, text.align_left)
    label.set_xy(_lbl, bar_index, ta.highest(10)[1])
    label.set_text(_lbl, _txt)

// f_print(tostring(hour(timenow), "00:") + tostring(minute(timenow), "00:") + tostring(second(timenow), "00") + " (Exchange)\n")
// f_print(tostring(hour(timenow, i_timeZone), "00:") + tostring(minute(timenow, i_timeZone), "00:") + tostring(second(timenow, i_timeZone), "00") + " (Input: " + i_timeZone + ")")
f_print(str.tostring(dayofmonth(timenow, i_timeZone), '00-') + str.tostring(month(timenow, i_timeZone), '00-') + str.tostring(year(timenow, i_timeZone), '00'))

// ============================ Time Function { ================

is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := ta.change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := ta.change(t) != 0 ? 1 : 0
    ch

// ============================ Time Function } ================

Label_Color         = input.color(defval=color.new(color.white,100),    title='Label_Color' )

Want_Daily          = input.bool(defval=true,                           title='Daily',      inline='Daily'      )
Want_Daily_Lines    = input.bool(defval=true,                           title='Lines',      inline='Daily'      )
Daily_Color         = input.color(defval=color.new(color.blue, 85),     title='Color',      inline='Daily'      )
Daily_Width         = input.int(  defval=1,                             title='Width',      inline='Daily'      )
Daily_HL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )
Daily_LL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )

Want_W188         = input.bool(defval=false,                          title='W188',     inline='W188'     )
Want_W188_Lines   = input.bool(defval=false,                          title='Lines',      inline='W188'     )
W188_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_Width        = input.int(  defval=1,                             title='Width',      inline='W188'     )
W188_HL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_LL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )

Next_CPR(TF, BG_Color, HL_Color, LL_Color, Width, Lines)=>

    // *********  Making Pivot  { ********
    PDH     = request.security(syminfo.ticker, TF, high[1]  , barmerge.gaps_off, barmerge.lookahead_on)
    PDL     = request.security(syminfo.ticker, TF, low[1]   , barmerge.gaps_off, barmerge.lookahead_on)
    PDC     = request.security(syminfo.ticker, TF, close[1] , barmerge.gaps_off, barmerge.lookahead_on)
    PDR     = (PDH - PDL)
    Pivot   = (PDH + PDL + PDC)/3

    // *********  Drawing Pivot  { ********
    var Bars      = 0, Bars  += 1
    var Line_Size = 0

    var label Label_Pivot = na
    Half_Day       = (12 * 60 * 60 * 1000)
    ONE_DAY       = 24 * 60 * 60 * 1000

    END_POINT     =    TF=="188"  ? Half_Day
                     : TF=="D"  ? ONE_DAY

    // if dayofmonth!=dayofmonth[1]
    if is_newbar(TF)
        Bars       := 1
        Line_Size  := math.min( Bars[1], 450 )

        if Lines
            line.new(time, Pivot , time+END_POINT, Pivot , color=color.fuchsia, xloc=xloc.bar_time, width=Width ),
            Label_Pivot := label.new(bar_index+1, Pivot , color=Label_Color, textcolor=color.fuchsia, style=label.style_label_left, text=str.tostring(TF + '_' + 'PIV' + str.tostring(Pivot, format.mintick)) + ' ', size=i_s_font)
            label.set_x(Label_Pivot, bar_index+1)

// *********  Drawing Pivot  } ********

if Want_Daily
    Next_CPR('75',  Daily_Color,   Daily_HL_Color, Daily_LL_Color, Daily_Width,       Want_Daily_Lines    )
if Want_W188
    Next_CPR('188',  W188_Color,   W188_HL_Color, W188_LL_Color, W188_Width,      Want_W188_Lines   )
</code>```

Body:
In pinescript, I have a code to plot CPR lines for the entire day wherein the lines from start to end of day are plotted per the normal Intraday session.
How can I have this for say 16 minutes and 30 seconds?

One_Day = 24 * 60 * 60 * 1000

Half_Day = ((1 * 16 * 60 * 1000) + (1 * 30 * 60 * 1000))

The below plots the first 16 minutes and 30 seconds perfectly but fails to do from the second 16 minutes and 30 seconds trading session. So basically the need is to break a trading session to half and thereafter making further cuts to the session. Meaning a 450 minute session can be minimum of 15 minute each to a maximum of 225 minute which will be termed as the half of that scripts trading session in a day.

//@version=5
indicator(title="Test", shorttitle="Test", overlay= true, max_labels_count=500, max_lines_count=500,  max_boxes_count=500)
T0 = "Small font size recommended for mobile app or multiple layout"
Transparency = input(defval=75)
i_s_font    = input.string("normal",       "Font size", tooltip = T0, options = ["tiny", "small",  "normal", "large", "huge"])
tointeger    = input.int(defval = 1, title = "To Integer")

i_timeZone = input('GMT+05:30')
f_print(_txt) =>
    var _lbl = label.new(bar_index, ta.highest(10)[1], _txt, xloc.bar_index, yloc.price, #00000000, label.style_none, color.black, size.tiny, text.align_left)
    label.set_xy(_lbl, bar_index, ta.highest(10)[1])
    label.set_text(_lbl, _txt)

// f_print(tostring(hour(timenow), "00:") + tostring(minute(timenow), "00:") + tostring(second(timenow), "00") + " (Exchange)\n")
// f_print(tostring(hour(timenow, i_timeZone), "00:") + tostring(minute(timenow, i_timeZone), "00:") + tostring(second(timenow, i_timeZone), "00") + " (Input: " + i_timeZone + ")")
f_print(str.tostring(dayofmonth(timenow, i_timeZone), '00-') + str.tostring(month(timenow, i_timeZone), '00-') + str.tostring(year(timenow, i_timeZone), '00'))

// ============================ Time Function { ================

is_newbar(res) =>
    ch = 0
    if(res == 'Y')
        t  = year(time('D'))
        ch := ta.change(t) != 0 ? 1 : 0
    else
        t = time(res)
        ch := ta.change(t) != 0 ? 1 : 0
    ch

// ============================ Time Function } ================

Label_Color         = input.color(defval=color.new(color.white,100),    title='Label_Color' )

Want_Daily          = input.bool(defval=true,                           title='Daily',      inline='Daily'      )
Want_Daily_Lines    = input.bool(defval=true,                           title='Lines',      inline='Daily'      )
Daily_Color         = input.color(defval=color.new(color.blue, 85),     title='Color',      inline='Daily'      )
Daily_Width         = input.int(  defval=1,                             title='Width',      inline='Daily'      )
Daily_HL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )
Daily_LL_Color         = input.color(defval=color.new(color.red, 85),     title='Color',      inline='Daily'      )

Want_W188         = input.bool(defval=false,                          title='W188',     inline='W188'     )
Want_W188_Lines   = input.bool(defval=false,                          title='Lines',      inline='W188'     )
W188_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_Width        = input.int(  defval=1,                             title='Width',      inline='W188'     )
W188_HL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )
W188_LL_Color        = input.color(defval=color.new(color.orange, 85),   title='Color',      inline='W188'     )

Next_CPR(TF, BG_Color, HL_Color, LL_Color, Width, Lines)=>

    // *********  Making Pivot  { ********
    PDH     = request.security(syminfo.ticker, TF, high[1]  , barmerge.gaps_off, barmerge.lookahead_on)
    PDL     = request.security(syminfo.ticker, TF, low[1]   , barmerge.gaps_off, barmerge.lookahead_on)
    PDC     = request.security(syminfo.ticker, TF, close[1] , barmerge.gaps_off, barmerge.lookahead_on)
    PDR     = (PDH - PDL)
    Pivot   = (PDH + PDL + PDC)/3

    // *********  Drawing Pivot  { ********
    var Bars      = 0, Bars  += 1
    var Line_Size = 0

    var label Label_Pivot = na
    Half_Day       = (12 * 60 * 60 * 1000)
    ONE_DAY       = 24 * 60 * 60 * 1000

    END_POINT     =    TF=="188"  ? Half_Day
                     : TF=="D"  ? ONE_DAY

    // if dayofmonth!=dayofmonth[1]
    if is_newbar(TF)
        Bars       := 1
        Line_Size  := math.min( Bars[1], 450 )

        if Lines
            line.new(time, Pivot , time+END_POINT, Pivot , color=color.fuchsia, xloc=xloc.bar_time, width=Width ),
            Label_Pivot := label.new(bar_index+1, Pivot , color=Label_Color, textcolor=color.fuchsia, style=label.style_label_left, text=str.tostring(TF + '_' + 'PIV' + str.tostring(Pivot, format.mintick)) + ' ', size=i_s_font)
            label.set_x(Label_Pivot, bar_index+1)

// *********  Drawing Pivot  } ********

if Want_Daily
    Next_CPR('75',  Daily_Color,   Daily_HL_Color, Daily_LL_Color, Daily_Width,       Want_Daily_Lines    )
if Want_W188
    Next_CPR('188',  W188_Color,   W188_HL_Color, W188_LL_Color, W188_Width,      Want_W188_Lines   )


问:
MacOS: cannot play local mp4 file using AVPlayer
I am new to swift/apple development and I'm trying to use AVPlayer from AVKit to play a local mp4 file on my disk. Here's my code below:

```<code>playerItem = AVPlayerItem(url: URL(fileURLWithPath: "/path/to/my/video.mp4"))
player = AVPlayer(playerItem: playerItem)
</code>```

The code compiles but the video doesn't show up in the player. Here's the error I got:

```<code>[plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x6000022f8bc0> F8BB1C28-BAE8-11D6-9C31-00039315CD46
</code>```

Some context and checking I've done:

I got the exact same error/looking if I change the path to a random non-existing file.

FileManager tells me that the file exists.

My app can access and display a jpeg image from the exact same folder with the mp4 file I'm trying to play.

When I move the same file into the App bundle and access it using Bundle.main.url(), it works.

playerItem.status is unknown, playerItem.error is nil.

Please help! Any reply will be appreciated!

Body:
I am new to swift/apple development and I'm trying to use AVPlayer from AVKit to play a local mp4 file on my disk. Here's my code below:

playerItem = AVPlayerItem(url: URL(fileURLWithPath: "/path/to/my/video.mp4"))
player = AVPlayer(playerItem: playerItem)

The code compiles but the video doesn't show up in the player. Here's the error I got:

[plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x6000022f8bc0> F8BB1C28-BAE8-11D6-9C31-00039315CD46

Some context and checking I've done:

I got the exact same error/looking if I change the path to a random non-existing file.

FileManager tells me that the file exists.

My app can access and display a jpeg image from the exact same folder with the mp4 file I'm trying to play.

When I move the same file into the App bundle and access it using Bundle.main.url(), it works.

playerItem.status is unknown, playerItem.error is nil.

Please help! Any reply will be appreciated!


问:
Unknown column 'gameApp_questions.id' in 'field django
hi everybody i make a quizz app in django i make choose 6 questions from database  in views.py

```<code> question_list = Questions.objects.filter(grade=15,subject=2).order_by('?')[:6]
    for i, question in enumerate(question_list):
        question.point = i + 1
        question.save()
    context['questions'] = question_list

    return context
</code>```

and i have a eror mesage OperationalError at /gameApp/gameplay
(1054, "Unknown column 'gameApp_questions.id' in 'field list'")

Body:
hi everybody i make a quizz app in django i make choose 6 questions from database  in views.py

 question_list = Questions.objects.filter(grade=15,subject=2).order_by('?')[:6]
    for i, question in enumerate(question_list):
        question.point = i + 1
        question.save()
    context['questions'] = question_list

    return context

and i have a eror mesage OperationalError at /gameApp/gameplay
(1054, "Unknown column 'gameApp_questions.id' in 'field list'")


问:
Compound forms expect an array or NULL on submission
I have a problem with my symfony 5 application. When I try to insert an object with the file field set to null, I get the following error:

```<code>Caused by:
Symfony\Component\Validator\ConstraintViolation {#4637 ▼
  root: Symfony\Component\Form\Form {#4042 ▶}
  path: "children[file]"
  value: ""
}
Symfony\Component\Form\Exception\TransformationFailedException {#4119 ▼
  -invalidMessage: null
  -invalidMessageParameters: []
  #message: "Compound forms expect an array or NULL on submission."
  #code: 0
  #line: 582
  trace: {▶}
}
</code>```

here is the data i am sending :

```<code>WORD\BookStoreBundle\Entity\Summary {#3870 ▼
  -id: 16
  -title: "Contrats à durée déterminée"
  -description: "bonjour ceci est une description"
  -position: 0
  -type: 1
  -createdAt: DateTime @1673427068 {#3872 ▶}
  -updatedAt: DateTime @1673427068 {#3851 ▶}
  -parent: null
  #file: null
  -deleteAt: null
}
</code>```

here is my form with file field not required :

```<code>class SummaryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', Field\TextType::class)
                ->add('description', Field\TextType::class, array(
                    "required" => false
                ))
                ->add('position', Field\IntegerType::class, array(
                    "empty_data" => '0'
                ))
                ->add('parent', SummaryIntegerType::class, array(
                    "required" => false
                ))
                ->add('file', SummaryFileType::class, array(
                    "required" => false,
                ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection'   => false,
            'data_class' => 'WORD\BookStoreBundle\Entity\Summary',
            'validation_groups' => array('rest_bookstore', 'rest_bookstore_summary_file'),
            'file'              => null
        ));
    }

}
</code>```

the file field is defined as required=false so I don't understand why I am getting this error.
did i miss something?

Body:
I have a problem with my symfony 5 application. When I try to insert an object with the file field set to null, I get the following error:

Caused by:
Symfony\Component\Validator\ConstraintViolation {#4637 ▼
  root: Symfony\Component\Form\Form {#4042 ▶}
  path: "children[file]"
  value: ""
}
Symfony\Component\Form\Exception\TransformationFailedException {#4119 ▼
  -invalidMessage: null
  -invalidMessageParameters: []
  #message: "Compound forms expect an array or NULL on submission."
  #code: 0
  #line: 582
  trace: {▶}
}

here is the data i am sending :

WORD\BookStoreBundle\Entity\Summary {#3870 ▼
  -id: 16
  -title: "Contrats à durée déterminée"
  -description: "bonjour ceci est une description"
  -position: 0
  -type: 1
  -createdAt: DateTime @1673427068 {#3872 ▶}
  -updatedAt: DateTime @1673427068 {#3851 ▶}
  -parent: null
  #file: null
  -deleteAt: null
}

here is my form with file field not required :

class SummaryType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', Field\TextType::class)
                ->add('description', Field\TextType::class, array(
                    "required" => false
                ))
                ->add('position', Field\IntegerType::class, array(
                    "empty_data" => '0'
                ))
                ->add('parent', SummaryIntegerType::class, array(
                    "required" => false
                ))
                ->add('file', SummaryFileType::class, array(
                    "required" => false,
                ))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection'   => false,
            'data_class' => 'WORD\BookStoreBundle\Entity\Summary',
            'validation_groups' => array('rest_bookstore', 'rest_bookstore_summary_file'),
            'file'              => null
        ));
    }

}

the file field is defined as required=false so I don't understand why I am getting this error.
did i miss something?


问:
Host Vue.js app on raspberry pi with apache2
I want to build and deploy a Vue.js app (or website) on my Raspberry, where I'm running an Apache2 server that already hosts some simple websites. Just build and copy doesn't seem to work. Am I missing some additional configurations that I need to do for the Apache2 server?

System settings

```<code>>> cat /sys/firmware/devicetree/base/model
Raspberry Pi 3 Model B Rev 1.2

>> cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 11 (bullseye)"
NAME="Raspbian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=raspbian
ID_LIKE=debian
...

>> node --version
v19.3.0

>> npm --version
9.2.0

>> apache2 -v
Server version: Apache/2.4.54 (Raspbian)
</code>```

Procedure: create and deploy vue.js app

I first create a new vue3 app:

```<code>vue create example-app
> Default ([Vue 3] babel, eslint)
</code>```

Running in serve mode works well:

```<code>cd example-app
npm run serve
</code>```

Now I'm building the static website:

```<code>npm run build
</code>```

...and copy the dist files to my apache2 website location:

```<code>sudo cp -r ./dist /var/www/html/exampleApp
</code>```

Error description

Apache is configured to host the pages under /var/www/html. The website is also recognized initially at http://192.168.188.21/exampleApp, but Firefox displays the following error log (sorry, don't know how to switch the log output to englisch):

```<code>Das Skript von "http://192.168.188.21/js/chunk-vendors.b04f6ab6.js" wurde geladen, obwohl sein MIME-Typ ("text/html") kein für JavaScript gültiger MIME-Typ ist. (exampleApp)

Das Skript von "http://192.168.188.21/js/app.41dec64c.js" wurde geladen, obwohl sein MIME-Typ ("text/html") kein für JavaScript gültiger MIME-Typ ist. (exampleApp)

Stylesheet http://192.168.188.21/css/app.2cf79ad6.css wurde nicht geladen, weil sein MIME-Typ, "text/html", nicht "text/css" ist. (exampleApp)

Uncaught SyntaxError: expected expression, got '<' (chunk-vendors.b04f6ab6.js:1:4)

Uncaught SyntaxError: expected expression, got '<' (app.41dec64c.js:1:4)

undefined (pageModifier.js:585:17)

Mutations-Ereignisse sollten nicht mehr verwendet werden. Verwenden Sie MutationObserver stattdessen. (pageModifier.js:81:24)
</code>```

In englisch it should be something like this:

```<code>The script of "http://192.168.188.21/js/chunk-vendors.b04f6ab6.js" was loaded although its MIME type ("text/html") is not a valid MIME type for JavaScript. (exampleApp)

The script of "http://192.168.188.21/js/app.41dec64c.js" was loaded, although its MIME type ("text/html") is not a valid MIME type for JavaScript. (exampleApp)

Stylesheet http://192.168.188.21/css/app.2cf79ad6.css was not loaded because its MIME type, "text/html", is not "text/css". (exampleApp)

Uncaught SyntaxError: expected expression, got '<' (chunk-vendors.b04f6ab6.js:1:4)

Uncaught SyntaxError: expected expression, got '<' (app.41dec64c.js:1:4)

undefined (pageModifier.js:585:17)

Mutation events should no longer be used. Use MutationObserver instead. (pageModifier.js:81:24)
</code>```

Body:
I want to build and deploy a Vue.js app (or website) on my Raspberry, where I'm running an Apache2 server that already hosts some simple websites. Just build and copy doesn't seem to work. Am I missing some additional configurations that I need to do for the Apache2 server?

System settings

>> cat /sys/firmware/devicetree/base/model
Raspberry Pi 3 Model B Rev 1.2

>> cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 11 (bullseye)"
NAME="Raspbian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=raspbian
ID_LIKE=debian
...

>> node --version
v19.3.0

>> npm --version
9.2.0

>> apache2 -v
Server version: Apache/2.4.54 (Raspbian)

Procedure: create and deploy vue.js app

I first create a new vue3 app:

vue create example-app
> Default ([Vue 3] babel, eslint)

Running in serve mode works well:

cd example-app
npm run serve

Now I'm building the static website:

npm run build

...and copy the dist files to my apache2 website location:

sudo cp -r ./dist /var/www/html/exampleApp

Error description

Apache is configured to host the pages under /var/www/html. The website is also recognized initially at http://192.168.188.21/exampleApp, but Firefox displays the following error log (sorry, don't know how to switch the log output to englisch):

Das Skript von "http://192.168.188.21/js/chunk-vendors.b04f6ab6.js" wurde geladen, obwohl sein MIME-Typ ("text/html") kein für JavaScript gültiger MIME-Typ ist. (exampleApp)

Das Skript von "http://192.168.188.21/js/app.41dec64c.js" wurde geladen, obwohl sein MIME-Typ ("text/html") kein für JavaScript gültiger MIME-Typ ist. (exampleApp)

Stylesheet http://192.168.188.21/css/app.2cf79ad6.css wurde nicht geladen, weil sein MIME-Typ, "text/html", nicht "text/css" ist. (exampleApp)

Uncaught SyntaxError: expected expression, got '<' (chunk-vendors.b04f6ab6.js:1:4)

Uncaught SyntaxError: expected expression, got '<' (app.41dec64c.js:1:4)

undefined (pageModifier.js:585:17)

Mutations-Ereignisse sollten nicht mehr verwendet werden. Verwenden Sie MutationObserver stattdessen. (pageModifier.js:81:24)

In englisch it should be something like this:

The script of "http://192.168.188.21/js/chunk-vendors.b04f6ab6.js" was loaded although its MIME type ("text/html") is not a valid MIME type for JavaScript. (exampleApp)

The script of "http://192.168.188.21/js/app.41dec64c.js" was loaded, although its MIME type ("text/html") is not a valid MIME type for JavaScript. (exampleApp)

Stylesheet http://192.168.188.21/css/app.2cf79ad6.css was not loaded because its MIME type, "text/html", is not "text/css". (exampleApp)

Uncaught SyntaxError: expected expression, got '<' (chunk-vendors.b04f6ab6.js:1:4)

Uncaught SyntaxError: expected expression, got '<' (app.41dec64c.js:1:4)

undefined (pageModifier.js:585:17)

Mutation events should no longer be used. Use MutationObserver instead. (pageModifier.js:81:24)


问:
Does db.session.flush() check for all possible exceptions before db.session.commit()?
In SQLAlchemy, if I call db.session.flush() and get no exceptions, am I guaranteed to have no exceptions if I then do db.session.commit()?

In other words, does db.session.flush() check for all possible errors that can happen in db.session.commit()? Is it safe to assume that if there were no errors in  db.session.flush(), I can then run db.session.commit() without checking for any exceptions?


问:
LINQ Query Optimization - joins
I have this query and it's taking more than 20,000 ms to run!
I need to optimize it but I'm struggling a little with it.

var items = (
    from b in sourceBookingItemsQuery
    join ci in Context.ChargeableItemEntities on new { b.Id, OwnerId = ServerUser.PartyId.Value, ChargeTarget = criteria.Target.Value, IsDeleted = false }
        equals new { Id = ci.BookingItemId.Value, ci.OwnerId, ci.ChargeTarget, ci.IsDeleted } into chargeable
    from ci in chargeable.DefaultIfEmpty()
    where
        (criteria.Client == null || ci.ClientId == criteria.Client)
        && (criteria.IsLoaded == null || (criteria.IsLoaded.Value == (b.LoadingCode == "Y" || b.LoadingCode == "B")))
        && (criteria.LoadedFrom == null || b.ShippedOn >= criteria.LoadedFrom)
        && (criteria.LoadedTo == null || b.ShippedOn <= criteria.LoadedTo)
        && (criteria.BookedFrom == null || b.Booking.CreatedOn >= criteria.BookedFrom)
        && (criteria.BookedTo == null || b.Booking.CreatedOn <= criteria.BookedTo)
        && (criteria.SerialNumber == null || b.Parcel.SerialNumber == criteria.SerialNumber)
        && (!b.IsCanceled)
        && !(from y in Context.ChargeEntities
            where y.OwnerId == this.CurrentPartyId
            && y.Type.Target == criteria.Target
            && y.CounterpartRole == ChargeCounterpartRole.Client
            && (y.ItemType == InvoiceItemType.BookingService || y.ItemType == InvoiceItemType.ShippingUnit)
            && !y.IsDeleted
            && b.ParcelId == y.ParcelId
            && y.InvoiceId != null
            select y).Any()
    orderby b.Id descending
    select new BillableItemDetail()
    {
        Id = b.Id,
        OwnerId = b.OwnerId,
        Parcel = new ParcelReference() { Id = b.Parcel.Id, Description = b.Parcel.Description, SerialNumber = b.Parcel.SerialNumber },
        Pod = new PortReference() { Id = b.Pod.Id, Code = b.Pod.Code, Name = b.Pod.Description },
        Pol = new PortReference() { Id = b.Booking.PolId, Code = b.Booking.Pol.Code, Name = b.Booking.Pol.Description },
        Client = ci.Client != null ? new PartyReference() { Id = ci.ClientId.Value, Name = ci.Client.Name } : null,
        VoyageCode = b.Voyage != null ? b.Voyage.Code : null,
        ShippedOn = b.ShippedOn,
        Charges = (from y in Context.ChargeEntities
                where y.OwnerId == this.CurrentPartyId
                && y.Type.Target == criteria.Target
                && y.CounterpartRole == ChargeCounterpartRole.Client
                && (y.ItemType == InvoiceItemType.BookingService || y.ItemType == InvoiceItemType.ShippingUnit)
                && !y.IsDeleted
                && b.ParcelId == y.ParcelId
                && y.InvoiceId == null
                group y by y.Currency.Id into g
                select new BillableItemCharge()
                {
                    Amount = g.Sum(c => c.Amount),
                    Currency = new CurrencyEntry { Id = g.Key, Symbol = g.First().Currency.Symbol },
                    Target = g.First().Type.Target,
                    InvoiceId = g.First().InvoiceId,
                    ItemId = g.First().ItemId,
                }).ToArray()

    }) ;
```
<p>I tried to change the join with ChargeableItems like this:</p>
<pre class="lang-cs prettyprint-override"><code>    from b in sourceBookingItemsQuery
    join ci in Context.ChargeableItemEntities on b.Id equals ci.BookingItemId.Value into chargeable
    from ci in chargeable.DefaultIfEmpty()
    where
    ci.OwnerId == ServerUser.PartyId.Value
    && ci.ChargeTarget== criteria.Target.Value
    && !ci.IsDeleted
</code>```

The weird thing is that I got less rows than the first one.

Title: LINQ Query Optimization - joins

Body:
I have this query and it's taking more than 20,000 ms to run!
I need to optimize it but I'm struggling a little with it.

var items = (
    from b in sourceBookingItemsQuery
    join ci in Context.ChargeableItemEntities on new { b.Id, OwnerId = ServerUser.PartyId.Value, ChargeTarget = criteria.Target.Value, IsDeleted = false }
        equals new { Id = ci.BookingItemId.Value, ci.OwnerId, ci.ChargeTarget, ci.IsDeleted } into chargeable
    from ci in chargeable.DefaultIfEmpty()
    where
        (criteria.Client == null || ci.ClientId == criteria.Client)
        && (criteria.IsLoaded == null || (criteria.IsLoaded.Value == (b.LoadingCode == "Y" || b.LoadingCode == "B")))
        && (criteria.LoadedFrom == null || b.ShippedOn >= criteria.LoadedFrom)
        && (criteria.LoadedTo == null || b.ShippedOn <= criteria.LoadedTo)
        && (criteria.BookedFrom == null || b.Booking.CreatedOn >= criteria.BookedFrom)
        && (criteria.BookedTo == null || b.Booking.CreatedOn <= criteria.BookedTo)
        && (criteria.SerialNumber == null || b.Parcel.SerialNumber == criteria.SerialNumber)
        && (!b.IsCanceled)
        && !(from y in Context.ChargeEntities
            where y.OwnerId == this.CurrentPartyId
            && y.Type.Target == criteria.Target
            && y.CounterpartRole == ChargeCounterpartRole.Client
            && (y.ItemType == InvoiceItemType.BookingService || y.ItemType == InvoiceItemType.ShippingUnit)
            && !y.IsDeleted
            && b.ParcelId == y.ParcelId
            && y.InvoiceId != null
            select y).Any()
    orderby b.Id descending
    select new BillableItemDetail()
    {
        Id = b.Id,
        OwnerId = b.OwnerId,
        Parcel = new ParcelReference() { Id = b.Parcel.Id, Description = b.Parcel.Description, SerialNumber = b.Parcel.SerialNumber },
        Pod = new PortReference() { Id = b.Pod.Id, Code = b.Pod.Code, Name = b.Pod.Description },
        Pol = new PortReference() { Id = b.Booking.PolId, Code = b.Booking.Pol.Code, Name = b.Booking.Pol.Description },
        Client = ci.Client != null ? new PartyReference() { Id = ci.ClientId.Value, Name = ci.Client.Name } : null,
        VoyageCode = b.Voyage != null ? b.Voyage.Code : null,
        ShippedOn = b.ShippedOn,
        Charges = (from y in Context.ChargeEntities
                where y.OwnerId == this.CurrentPartyId
                && y.Type.Target == criteria.Target
                && y.CounterpartRole == ChargeCounterpartRole.Client
                && (y.ItemType == InvoiceItemType.BookingService || y.ItemType == InvoiceItemType.ShippingUnit)
                && !y.IsDeleted
                && b.ParcelId == y.ParcelId
                && y.InvoiceId == null
                group y by y.Currency.Id into g
                select new BillableItemCharge()
                {
                    Amount = g.Sum(c => c.Amount),
                    Currency = new CurrencyEntry { Id = g.Key, Symbol = g.First().Currency.Symbol },
                    Target = g.First().Type.Target,
                    InvoiceId = g.First().InvoiceId,
                    ItemId = g.First().ItemId,
                }).ToArray()

    }) ;

I tried to change the join with ChargeableItems like this:

    from b in sourceBookingItemsQuery
    join ci in Context.ChargeableItemEntities on b.Id equals ci.BookingItemId.Value into chargeable
    from ci in chargeable.DefaultIfEmpty()
    where
    ci.OwnerId == ServerUser.PartyId.Value
    && ci.ChargeTarget== criteria.Target.Value
    && !ci.IsDeleted

The weird thing is that I got less rows than the first one.


问:
How to assign values in a multiindex dataframe derived from a multiindex pivot table?
I have created a df from a multiindex pivot table. The pivot table is created from a merged dataframe of 4 csv files.
Now my task is to iterate through the multiindex df to assign values in the rows. I hv 6 warehouses, 91 stores. Under each warehouse different number of stores are assigned with Ranking (ranging from 1 to 91) and Grades like 'A','B','C'.Depending on the 80% of FINAL_ORDER_QTY I have to allocate stock to the stores, by checking a predefined column "QTY" as reference (Depending on size, dept, brand and store grade,the QTY is predefined for that warehouse)

CONDITIONS:

Checking Style_grade column for allocation, Allocate to ALL, TOP80, TOP70, TOP60, TOP50, TOP40, TOP30, TOP20, TOP10.

Allocate the stock to A grade stores initially.

Maintain the running count column for left over stock
4.Stop allocation if there is less than the predefined qty or equal to zero.

Adding a slice of the dataframe for reference as my dataframe size is 219 rows × 109 columns

Stock Allocation
TOTAL_ALLOCATED_QTY
Loctioncode                                                   71272
Store Rank                                                       7    16     31     78
Store Grade                                                      A     A      B      C
Storecode                                                       1429   1478  1398    1678

```<code>| Brand   | ITEM       | Size| 71272(final_order_qty)|QTY
| -------- | --------  | ------|--------------------------
| Code   | #10009734467 |  18  | 10                  | 3      0      0     0      0
| code   | #10009734469 |  20  | 35                  |  2     0      0     0      0
</code>```

Any help would be really appreciated.!!

enter image description here

An image for reference on how to allocation should be done.
TOTAL_ALLOCATED_QTY
Loctioncode                                                                       71272
Store Rank                                                                         7    16     31     78
Store Grade                                                                        A     A      B      C
Storecode                                                                        1429   1478  1398    1678

```<code>| Brand   | ITEM       | Size| 71272(final_order_qty)|QTY |Store Grade
| -------- | --------  | ------|--------------------------
| Code   | #10009734467 |  18  | 10                  | 3   dressA              3      3     0      0
| code   | #10009734469 |  20  | 5                  |  2   DressA               2     2     0      0
| Code   | #10009734467 |  18  | 10                  | 1   dressB               3     3     1      1
| code   | #10009734469 |  20  | 5                  |  2   DressA               2      2    1      0
</code>```

Body:
I have created a df from a multiindex pivot table. The pivot table is created from a merged dataframe of 4 csv files.
Now my task is to iterate through the multiindex df to assign values in the rows. I hv 6 warehouses, 91 stores. Under each warehouse different number of stores are assigned with Ranking (ranging from 1 to 91) and Grades like 'A','B','C'.Depending on the 80% of FINAL_ORDER_QTY I have to allocate stock to the stores, by checking a predefined column "QTY" as reference (Depending on size, dept, brand and store grade,the QTY is predefined for that warehouse)

CONDITIONS:

Checking Style_grade column for allocation, Allocate to ALL, TOP80, TOP70, TOP60, TOP50, TOP40, TOP30, TOP20, TOP10.

Allocate the stock to A grade stores initially.

Maintain the running count column for left over stock
4.Stop allocation if there is less than the predefined qty or equal to zero.

Adding a slice of the dataframe for reference as my dataframe size is 219 rows × 109 columns

Stock Allocation
TOTAL_ALLOCATED_QTY
Loctioncode                                                   71272
Store Rank                                                       7    16     31     78
Store Grade                                                      A     A      B      C
Storecode                                                       1429   1478  1398    1678

| Brand   | ITEM       | Size| 71272(final_order_qty)|QTY
| -------- | --------  | ------|--------------------------
| Code   | #10009734467 |  18  | 10                  | 3      0      0     0      0
| code   | #10009734469 |  20  | 35                  |  2     0      0     0      0

Any help would be really appreciated.!!

enter image description here

An image for reference on how to allocation should be done.
TOTAL_ALLOCATED_QTY
Loctioncode                                                                       71272
Store Rank                                                                         7    16     31     78
Store Grade                                                                        A     A      B      C
Storecode                                                                        1429   1478  1398    1678

| Brand   | ITEM       | Size| 71272(final_order_qty)|QTY |Store Grade
| -------- | --------  | ------|--------------------------
| Code   | #10009734467 |  18  | 10                  | 3   dressA              3      3     0      0
| code   | #10009734469 |  20  | 5                  |  2   DressA               2     2     0      0
| Code   | #10009734467 |  18  | 10                  | 1   dressB               3     3     1      1
| code   | #10009734469 |  20  | 5                  |  2   DressA               2      2    1      0


问:
Testing a service in angular
How do I test a service in angular? I have a service that calls the API to get a list of communities. But I dont know to test it. Currently I have it imported but I cant call the function.
Does anyone know how I can test if the function in the service returns an array?
My current test code:</p>
```<code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CommunityService } from 'src/app/services/API/community.service';
import { CreateCommunityMenuComponent } from './create-community-menu.component';

describe('CreateCommunityMenuComponent', () => {
  let component: CreateCommunityMenuComponent;
  let fixture: ComponentFixture<CreateCommunityMenuComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ CreateCommunityMenuComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CreateCommunityMenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    const mySpy = spyOn(CommunityService , CommunityService.);

    expect(mySpy).toHaveBeenCalledTimes(1);
  });
});

</code>```

Title: Testing a service in angular

Body:
How do I test a service in angular? I have a service that calls the API to get a list of communities. But I dont know to test it. Currently I have it imported but I cant call the function.
Does anyone know how I can test if the function in the service returns an array?
My current test code:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CommunityService } from 'src/app/services/API/community.service';
import { CreateCommunityMenuComponent } from './create-community-menu.component';

describe('CreateCommunityMenuComponent', () => {
  let component: CreateCommunityMenuComponent;
  let fixture: ComponentFixture<CreateCommunityMenuComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ CreateCommunityMenuComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CreateCommunityMenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    const mySpy = spyOn(CommunityService , CommunityService.);

    expect(mySpy).toHaveBeenCalledTimes(1);
  });
});


问:
Jquery Ajax call Returns [object, Object]
```<code>I tried to call a data engineer based on their service point using ajax, but the result of the ajax is [object Object], where is my mistake?
</code>```

this is my script

```<code>function engineer(url, id, name) {
            // send ajax request to get the cities of the selected province and append to the select tag
            $.ajax({
                url: url,
                type: 'GET',
                data: {
                    id: id
                },
                success: function(data) {
                    $('#' + name).empty();
                    $('#' + name).append('<option>- Choose Option -</option>');
                    $.each(data, function(key, value) {
                        $('#' + name).append('<option value="' + key + '">' + value + '</option>');
                    });
                }
            });
        }
        $(function() {
            $('#servp').on('change', function() {
                engineer('{{ route('engineer') }}', $(this).val(), 'engineer');
            });
        });
</code>```

and this my controller

```<code>return User::all()->where('depart', 6)->where('service_point', $request->id);
</code>```

and this one is the routes

```<code>Route::get('engineer', [TicketController::class,'engineer'])->name('engineer');
</code>```

I want when selecting a service point an engineer appears who is only at that service point

Body:
I tried to call a data engineer based on their service point using ajax, but the result of the ajax is [object Object], where is my mistake?

this is my script

function engineer(url, id, name) {
            // send ajax request to get the cities of the selected province and append to the select tag
            $.ajax({
                url: url,
                type: 'GET',
                data: {
                    id: id
                },
                success: function(data) {
                    $('#' + name).empty();
                    $('#' + name).append('<option>- Choose Option -</option>');
                    $.each(data, function(key, value) {
                        $('#' + name).append('<option value="' + key + '">' + value + '</option>');
                    });
                }
            });
        }
        $(function() {
            $('#servp').on('change', function() {
                engineer('{{ route('engineer') }}', $(this).val(), 'engineer');
            });
        });

and this my controller

return User::all()->where('depart', 6)->where('service_point', $request->id);

and this one is the routes

Route::get('engineer', [TicketController::class,'engineer'])->name('engineer');

I want when selecting a service point an engineer appears who is only at that service point