问:
how to flush the ZipOutputStream periodically in java
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

```<code>try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}
</code>```

```<code>public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}
</code>```

答: I guess you are digging in a wrong direction. Try to replace the servlet output stream by a file stream and see if the issue is still here. I suspect your web container tries to collect whole servlet output to calculate content-length before sending http headers.</p>

Body:
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}

public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}


来源: stackexchange

问:
Regex to get nth occurrence of pattern (Trino)
```<code>WITH t(x,y) AS (

    VALUES
    (1,'[2]'),
    (2,'[1, 2]'),
    (3,'[2, 1]'),
    (4,'[3, 2, 5]'),
    (5,'[3, 2, 5, 2, 4]'),
    (6,'[3, 2, 2, 0, 4]')

)

--- my wrong answer below

SELECT

REGEXP_EXTRACT(y, '(\d+,\s)?(2)(,\s\d+)?') AS _1st,
REGEXP_EXTRACT(y,'(.*?(2)){1}.*?(\d+,\s(2)(,\s\d+)?)',3) AS _2nd,
REGEXP_EXTRACT(y,'(.*?(2)){2}.*?(\d+,\s(2)(,\s\d+)?)',3) AS _3rd

FROM t

</code>```
```<code>Expected ans:
| x |        y        |   1st   |   2nd   |   nth   |
| - | --------------- | ------- | ------- | ------- |
| 1 | [2]             | 2       |         |         |
| 2 | [1, 2]          | 1, 2    |         |         |
| 3 | [2, 1]          | 2, 1    |         |         |
| 4 | [3, 2, 5]       | 3, 2, 5 |         |         |
| 5 | [3, 2, 5, 2, 4] | 3, 2, 5 | 5, 2, 4 |         |
| 6 | [3, 2, 2, 0, 4] | 3, 2, 2 | 2, 2, 0 |         |
</code>```

Need help on the Regex for REGEXP_EXTRACT function in Presto to get the nth occurrence of number '2' and include the figures before and after it (if any)

Additional info:

The figures in column y are not necessary single digit.

Orders of the numbers are important

1st, 2nd, 3rd refers to the nth occurrence of the number that I am seeking

Will be looking for a list of numbers, not just 2. Using 2 for illustration purpose.

答:
Must it be a regular-expression?

If you see the text (VARCHAR) [1,2,3] as array-representation (JSON or internal data-type Array), you have more functions available to solve your task.

See related functions supported by Presto:

JSON functions

Array function

I would recommend to cast it as array of integers: CAST('[1,23,456]' AS ARRAY(INTEGER))

Finding the n-th occurrence

From Array functions, array_position(x, element, instance) → bigint to find the n-th occurrence:

If instance > 0, returns the position of the instance-th occurrence of the element in array x.

If instance < 0, returns the position of the instance-to-last occurrence of the element in array x.

If no matching element instance is found, 0 is returned.

Example:

```<code>SELECT CAST('[1,2,23,2,456]' AS ARRAY(INTEGER));
SELECT array_position(2, CAST('[1,2,23,2,456]' AS ARRAY(INTEGER)), 1); -- found in position 2
</code>```

Now use the found position to build your slice (relatively from that).

Slicing and extracting sub-arrays

either parse it as JSON to a JSON-array. Then use a JSON-path to slice (extract a sub-array) as desired: Array slice operator in JSON-path: [start, stop, step]

or cast it as Array and then use slice(x, start, length) → array

Subsets array x starting from index start (or starting from the end if start is negative) with a length of length.

Examples:

```<code>SELECT json_extract(json_parse('[1,2,3]'), '$[-2, -1]');  -- the last two elements

SELECT slice(CAST('[1,23,456]' AS ARRAY(INTEGER)), -2, 2); -- [23, 456]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
WITH t(x,y) AS (

    VALUES
    (1,'[2]'),
    (2,'[1, 2]'),
    (3,'[2, 1]'),
    (4,'[3, 2, 5]'),
    (5,'[3, 2, 5, 2, 4]'),
    (6,'[3, 2, 2, 0, 4]')

)

--- my wrong answer below

SELECT

REGEXP_EXTRACT(y, '(\d+,\s)?(2)(,\s\d+)?') AS _1st,
REGEXP_EXTRACT(y,'(.*?(2)){1}.*?(\d+,\s(2)(,\s\d+)?)',3) AS _2nd,
REGEXP_EXTRACT(y,'(.*?(2)){2}.*?(\d+,\s(2)(,\s\d+)?)',3) AS _3rd

FROM t

Expected ans:
| x |        y        |   1st   |   2nd   |   nth   |
| - | --------------- | ------- | ------- | ------- |
| 1 | [2]             | 2       |         |         |
| 2 | [1, 2]          | 1, 2    |         |         |
| 3 | [2, 1]          | 2, 1    |         |         |
| 4 | [3, 2, 5]       | 3, 2, 5 |         |         |
| 5 | [3, 2, 5, 2, 4] | 3, 2, 5 | 5, 2, 4 |         |
| 6 | [3, 2, 2, 0, 4] | 3, 2, 2 | 2, 2, 0 |         |

Need help on the Regex for REGEXP_EXTRACT function in Presto to get the nth occurrence of number '2' and include the figures before and after it (if any)

Additional info:

The figures in column y are not necessary single digit.

Orders of the numbers are important

1st, 2nd, 3rd refers to the nth occurrence of the number that I am seeking

Will be looking for a list of numbers, not just 2. Using 2 for illustration purpose.

Body:
Must it be a regular-expression?

If you see the text (VARCHAR) [1,2,3] as array-representation (JSON or internal data-type Array), you have more functions available to solve your task.

See related functions supported by Presto:

JSON functions

Array function

I would recommend to cast it as array of integers: CAST('[1,23,456]' AS ARRAY(INTEGER))

Finding the n-th occurrence

From Array functions, array_position(x, element, instance) → bigint to find the n-th occurrence:

If instance > 0, returns the position of the instance-th occurrence of the element in array x.

If instance < 0, returns the position of the instance-to-last occurrence of the element in array x.

If no matching element instance is found, 0 is returned.

Example:

SELECT CAST('[1,2,23,2,456]' AS ARRAY(INTEGER));
SELECT array_position(2, CAST('[1,2,23,2,456]' AS ARRAY(INTEGER)), 1); -- found in position 2

Now use the found position to build your slice (relatively from that).

Slicing and extracting sub-arrays

either parse it as JSON to a JSON-array. Then use a JSON-path to slice (extract a sub-array) as desired: Array slice operator in JSON-path: [start, stop, step]

or cast it as Array and then use slice(x, start, length) → array

Subsets array x starting from index start (or starting from the end if start is negative) with a length of length.

Examples:

SELECT json_extract(json_parse('[1,2,3]'), '$[-2, -1]');  -- the last two elements

SELECT slice(CAST('[1,23,456]' AS ARRAY(INTEGER)), -2, 2); -- [23, 456]


问:
How to use the Google Sign In access token instead of authorization code for getting the data from the Google Search Console?
I want to access the listed websites data in the Google Search Console using the Google Sign-In access_token (that one can get as the response when using Google Sign-In).

But, the thing is I can access that data only by using the authorization_code that can be copied from the OAuth2-Consent screen by going to the generated authorize_url and signing in using the registered Google account.

Here's the minimum reproducible version of the code:

```<code>from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build

CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()

print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()

credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

def get_property_list(webmasters_service):
    '''
    Get a list of validated properties from GSC
    '''
    site_list = webmasters_service.sites().list().execute()

    # Filter for verified websites
    verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                        if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'][:4] == 'http']
    return verified_sites_urls

print({"available_websites": get_property_list(webmasters_service)})
</code>```

Consider that I'll be provided with the Google Sign-In access-token as the request-parameter from another server which has implemented Google Sign-In feature.

So, again my question is how can I access the same data using that token instead of manually getting the auth_code from the OAuth2 consent screen ?

答:
I have followed the documentation shared by DaImTo in the comments above. And modified the code as shown below:

```<code>from oauth2client.client import  OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client import tools, file

CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Acquire and store oauth token.
storage = file.Storage('token.json')
credentials = storage.get()

if credentials is None or credentials.invalid:
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    credentials = tools.run_flow(flow, storage)

http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

def get_property_list(webmasters_service):
    '''
    Get a list of validated properties from GSC
    '''
    site_list = webmasters_service.sites().list().execute()

    # Filter for verified websites
    verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                        if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'][:4] == 'http']
    return verified_sites_urls

print({"available_websites": get_property_list(webmasters_service)})
</code>```

It's working fine now, without any manual interaction for copying and pasting the authorization_code from the OAuth2-Consent screen.

Body:
I want to access the listed websites data in the Google Search Console using the Google Sign-In access_token (that one can get as the response when using Google Sign-In).

But, the thing is I can access that data only by using the authorization_code that can be copied from the OAuth2-Consent screen by going to the generated authorize_url and signing in using the registered Google account.

Here's the minimum reproducible version of the code:

from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build

CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()

print ('Go to the following link in your browser: ' + authorize_url)
code = input('Enter verification code: ').strip()

credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

def get_property_list(webmasters_service):
    '''
    Get a list of validated properties from GSC
    '''
    site_list = webmasters_service.sites().list().execute()

    # Filter for verified websites
    verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                        if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'][:4] == 'http']
    return verified_sites_urls

print({"available_websites": get_property_list(webmasters_service)})

Consider that I'll be provided with the Google Sign-In access-token as the request-parameter from another server which has implemented Google Sign-In feature.

So, again my question is how can I access the same data using that token instead of manually getting the auth_code from the OAuth2 consent screen ?

Body:
I have followed the documentation shared by DaImTo in the comments above. And modified the code as shown below:

from oauth2client.client import  OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client import tools, file

CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Acquire and store oauth token.
storage = file.Storage('token.json')
credentials = storage.get()

if credentials is None or credentials.invalid:
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    credentials = tools.run_flow(flow, storage)

http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

def get_property_list(webmasters_service):
    '''
    Get a list of validated properties from GSC
    '''
    site_list = webmasters_service.sites().list().execute()

    # Filter for verified websites
    verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                        if s['permissionLevel'] != 'siteUnverifiedUser'
                            and s['siteUrl'][:4] == 'http']
    return verified_sites_urls

print({"available_websites": get_property_list(webmasters_service)})

It's working fine now, without any manual interaction for copying and pasting the authorization_code from the OAuth2-Consent screen.


问:
Increases physical memory continuously Visual C++ CryptMsgClose and CryptReleaseContext
I am using C++ and Visual Studio 2005.

I have a project that memory Increases in a very abnormal. When debug the code I Realized That there are Several parts That Contribute to it. Like this for example:

```<code> // has to add crypt32.lib to link
#include <windows.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

void memoryUP( const unsigned char *pData, int cData )
{
    HCRYPTMSG  msg  = NULL;
    HCRYPTPROV hProv        = NULL;

    CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,0);

    msg = CryptMsgOpenToDecode(MY_ENCODING_TYPE,0,0,hProv,NULL,NULL);

    if(!(CryptMsgUpdate( msg, pData, cData, TRUE)))
    {
        if(msg != NULL)
        {
            CryptMsgClose(msg);
            msg = NULL;
        }
    }

    if (hProv != NULL)
        CryptReleaseContext(hProv,0);

    if (msg != NULL)
    {
        CryptMsgClose(msg);
        msg = NULL;
    }
}

int main(int argc, char** argv)
{
    MyFile myfile = myReadFile("c:\\file.p7s");

    {
        for(int i=0; i<100000; ++i)
        {
            memoryUP( myfile._data, myfile._length );
        }
    }

    delete myfile;

    return 0;
}
</code>```

When I run this code, the memory goes up continuously "when call CryptMsgUpdate". Am I deallocating wrong?

I tried to use Memory Leak Detection Enabling method to detect memory leak but nothing appears:

```<code>#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

and

_CrtDumpMemoryLeaks();
</code>```

Thanks in Advance

答:
You have to release resources in reverse order of their acquisition:

```<code> CryptAcquireContext();

 if (success)
 {
   CryptMsgOpenToDecode();

   if (success)
   {
      CryptMsgClose();
   }
   // else: nothing to close, opening failed

   CryptReleaseContext();
 }
 // else: nothing to release, acquisition failed
</code>```

The deeper nested constructions depend on the outer ones and may lock up resources, so you can only release the prerequisite resources after you've released the dependent ones.

Since you tagged this C++, I would be remiss to mention that those sort of things should be handled with RIAA, and you should make a class that takes responsibility for the resource. As you can see even in this simple example, writing the correct error checking paths very quickly become onerous, so it'd be much better and more modular to have a class that cleans up after itself, which automatically happens in the correct order.

ContentLicense: CC BY-SA 3.0

Body:
I am using C++ and Visual Studio 2005.

I have a project that memory Increases in a very abnormal. When debug the code I Realized That there are Several parts That Contribute to it. Like this for example:

 // has to add crypt32.lib to link
#include <windows.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

void memoryUP( const unsigned char *pData, int cData )
{
    HCRYPTMSG  msg  = NULL;
    HCRYPTPROV hProv        = NULL;

    CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,0);

    msg = CryptMsgOpenToDecode(MY_ENCODING_TYPE,0,0,hProv,NULL,NULL);

    if(!(CryptMsgUpdate( msg, pData, cData, TRUE)))
    {
        if(msg != NULL)
        {
            CryptMsgClose(msg);
            msg = NULL;
        }
    }

    if (hProv != NULL)
        CryptReleaseContext(hProv,0);

    if (msg != NULL)
    {
        CryptMsgClose(msg);
        msg = NULL;
    }
}

int main(int argc, char** argv)
{
    MyFile myfile = myReadFile("c:\\file.p7s");

    {
        for(int i=0; i<100000; ++i)
        {
            memoryUP( myfile._data, myfile._length );
        }
    }

    delete myfile;

    return 0;
}

When I run this code, the memory goes up continuously "when call CryptMsgUpdate". Am I deallocating wrong?

I tried to use Memory Leak Detection Enabling method to detect memory leak but nothing appears:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

and

_CrtDumpMemoryLeaks();

Thanks in Advance

Body:
You have to release resources in reverse order of their acquisition:

 CryptAcquireContext();

 if (success)
 {
   CryptMsgOpenToDecode();

   if (success)
   {
      CryptMsgClose();
   }
   // else: nothing to close, opening failed

   CryptReleaseContext();
 }
 // else: nothing to release, acquisition failed

The deeper nested constructions depend on the outer ones and may lock up resources, so you can only release the prerequisite resources after you've released the dependent ones.

Since you tagged this C++, I would be remiss to mention that those sort of things should be handled with RIAA, and you should make a class that takes responsibility for the resource. As you can see even in this simple example, writing the correct error checking paths very quickly become onerous, so it'd be much better and more modular to have a class that cleans up after itself, which automatically happens in the correct order.


问:
How to compare each row of a data frame to each row of another dataframe and calculate overlap
I have two dataframes with start and end time. I want to compare each row of df2 to each row of df1 and calculate the overlap.

```<code>df1
    #    start    end
    #1    5       15
    #2    20      28
    #3    46      68
    #4    80      87

df2
    #    start    end
    #1    20      40
    #2    65      85
</code>```

So the results should be a vector with results

```<code>overlaping_duration_1= 8 (overlap from df2 row 1 with df1 row 1)
overlaping_duration_2= 3+5 = overlap from df2 row 2 with df1 row 3 + overlap from df2 row 2 with df1 row 4
</code>```

I tried it with an ifelse approach and cover the different conditions. This is only for the first row for df2.

```<code>overlap =  ifelse ( df2$start <= df1$start & df1$start <= df2$end & df2$end <= df1$end, df2$end-df1$start, 0)

overlap2 =  ifelse ( df2$start <= df1$start & df1$end <= df2$end, df1$end-df1$start, 0)

overlap3 =  ifelse ( df1$start < df2$start & df2$end <= df1$end, df2$end-df2$start, 0)

overlap4 =  ifelse ( df1$start < df2$start & df2$start <= df1$end & df1$end <= df2$end, df1$end-df2$start, 0)
</code>```

Afterwards the different overlap vectors can be merged. This could be applied over a for loop over df2.
This approach is quite cumbersome. Is there a more comfortable way?

答:
```<code>library(data.table)
df1 = data.table(start=c(5,20,46,80),end=c(15,28,68,87))
df2 = data.table(start=c(20,65), end=c(40,85))

# add row identifer (`rn`) and dummy var (`id`) for cartesian join
df1[,`:=`(id=1, rn=.I)]
df2[,`:=`(id=1, rn=.I)]

# do full join
df = df1[df2,on="id", allow.cartesian=T]

# estimate overlap, by row
result = df[,overlap:=.(min(i.end,end)-max(i.start,start)), by=1:nrow(df)]

# retain positive overlaps, and sum by df2 row number
result[overlap>0, .(total = sum(overlap)), by = .(rn=i.rn)]
</code>```

Output:

```<code>   rn total
1:  1     8
2:  2     8
</code>```

Update: You can also avoid the full join, by instead keying df2 on start and end and using data.table::foverlaps:

```<code>library(data.table)
df1 = data.table(start=c(5,20,46,80),end=c(15,28,68,87))
df2 = data.table(start=c(20,65), end=c(40,85))
setkey(df2,start,end)
df = foverlaps(df1,df2[,rn:=.I], nomatch=NULL)
df[,overlap:=.(min(i.end,end)-max(i.start,start)), by=1:nrow(df)][, .(total =sum(overlap,na.rm=T)),by=rn]
</code>```

Output:

```<code>   rn total
1:  1     8
2:  2     8
</code>```

Body:
I have two dataframes with start and end time. I want to compare each row of df2 to each row of df1 and calculate the overlap.

df1
    #    start    end
    #1    5       15
    #2    20      28
    #3    46      68
    #4    80      87

df2
    #    start    end
    #1    20      40
    #2    65      85

So the results should be a vector with results

overlaping_duration_1= 8 (overlap from df2 row 1 with df1 row 1)
overlaping_duration_2= 3+5 = overlap from df2 row 2 with df1 row 3 + overlap from df2 row 2 with df1 row 4

I tried it with an ifelse approach and cover the different conditions. This is only for the first row for df2.

overlap =  ifelse ( df2$start <= df1$start & df1$start <= df2$end & df2$end <= df1$end, df2$end-df1$start, 0)

overlap2 =  ifelse ( df2$start <= df1$start & df1$end <= df2$end, df1$end-df1$start, 0)

overlap3 =  ifelse ( df1$start < df2$start & df2$end <= df1$end, df2$end-df2$start, 0)

overlap4 =  ifelse ( df1$start < df2$start & df2$start <= df1$end & df1$end <= df2$end, df1$end-df2$start, 0)

Afterwards the different overlap vectors can be merged. This could be applied over a for loop over df2.
This approach is quite cumbersome. Is there a more comfortable way?

Body:
library(data.table)
df1 = data.table(start=c(5,20,46,80),end=c(15,28,68,87))
df2 = data.table(start=c(20,65), end=c(40,85))

# add row identifer (`rn`) and dummy var (`id`) for cartesian join
df1[,`:=`(id=1, rn=.I)]
df2[,`:=`(id=1, rn=.I)]

# do full join
df = df1[df2,on="id", allow.cartesian=T]

# estimate overlap, by row
result = df[,overlap:=.(min(i.end,end)-max(i.start,start)), by=1:nrow(df)]

# retain positive overlaps, and sum by df2 row number
result[overlap>0, .(total = sum(overlap)), by = .(rn=i.rn)]

Output:

   rn total
1:  1     8
2:  2     8

Update: You can also avoid the full join, by instead keying df2 on start and end and using data.table::foverlaps:

library(data.table)
df1 = data.table(start=c(5,20,46,80),end=c(15,28,68,87))
df2 = data.table(start=c(20,65), end=c(40,85))
setkey(df2,start,end)
df = foverlaps(df1,df2[,rn:=.I], nomatch=NULL)
df[,overlap:=.(min(i.end,end)-max(i.start,start)), by=1:nrow(df)][, .(total =sum(overlap,na.rm=T)),by=rn]

Output:

   rn total
1:  1     8
2:  2     8


问:
List the queries running on SQL Server
Is there a way to list the queries that are currently running on MS SQL Server (either through the Enterprise Manager or SQL) and/or who's connected?

I think I've got a very long running query is being execute on one of my database servers and I'd like to track it down and stop it (or the person who keeps starting it).

答:
Trying to put things together (hope to be helpful):</p>
```<code>SELECT
    p.spid,
    RIGHT(CONVERT(varchar, DATEADD(ms, DATEDIFF(ms, p.last_batch, GETDATE()), '1900-01-01'), 121), 12) AS [batch_duration],
    p.[program_name],
    p.hostname,
    MAX(p.loginame) AS loginame,
    (SELECT SUBSTRING(text, COALESCE(NULLIF(spid.stmt_start, 0), 1) + 1, CASE spid.stmt_end WHEN -1 THEN DATALENGTH(text) ELSE (spid.stmt_end - spid.stmt_start) END) FROM ::fn_get_sql(spid.[sql_handle])) AS [sql]
FROM
    master.dbo.sysprocesses p
    LEFT JOIN (
        SELECT
            ROW_NUMBER() OVER(PARTITION BY spid ORDER BY ecid) AS i,
            spid,
            [sql_handle],
            CASE stmt_start WHEN 0 THEN 0 ELSE stmt_start / 2 END AS stmt_start,
            CASE stmt_end WHEN -1 THEN -1 ELSE stmt_end / 2 END AS stmt_end
        FROM sys.sysprocesses
    ) spid ON p.spid = spid.spid AND spid.i = 1
WHERE
    p.spid > 50
    AND p.status NOT IN ('background', 'sleeping')
    AND p.cmd NOT IN ('AWAITING COMMAND', 'MIRROR HANDLER', 'LAZY WRITER', 'CHECKPOINT SLEEP', 'RA MANAGER')
GROUP BY
    p.spid,
    p.last_batch,
    p.[program_name],
    p.hostname,
    spid.stmt_start,
    spid.stmt_end,
    spid.[sql_handle]
ORDER BY
    batch_duration DESC,
    p.spid
;
</code>```

ContentLicense: CC BY-SA 2.5

Title: List the queries running on SQL Server

Body:
Trying to put things together (hope to be helpful):

SELECT
    p.spid,
    RIGHT(CONVERT(varchar, DATEADD(ms, DATEDIFF(ms, p.last_batch, GETDATE()), '1900-01-01'), 121), 12) AS [batch_duration],
    p.[program_name],
    p.hostname,
    MAX(p.loginame) AS loginame,
    (SELECT SUBSTRING(text, COALESCE(NULLIF(spid.stmt_start, 0), 1) + 1, CASE spid.stmt_end WHEN -1 THEN DATALENGTH(text) ELSE (spid.stmt_end - spid.stmt_start) END) FROM ::fn_get_sql(spid.[sql_handle])) AS [sql]
FROM
    master.dbo.sysprocesses p
    LEFT JOIN (
        SELECT
            ROW_NUMBER() OVER(PARTITION BY spid ORDER BY ecid) AS i,
            spid,
            [sql_handle],
            CASE stmt_start WHEN 0 THEN 0 ELSE stmt_start / 2 END AS stmt_start,
            CASE stmt_end WHEN -1 THEN -1 ELSE stmt_end / 2 END AS stmt_end
        FROM sys.sysprocesses
    ) spid ON p.spid = spid.spid AND spid.i = 1
WHERE
    p.spid > 50
    AND p.status NOT IN ('background', 'sleeping')
    AND p.cmd NOT IN ('AWAITING COMMAND', 'MIRROR HANDLER', 'LAZY WRITER', 'CHECKPOINT SLEEP', 'RA MANAGER')
GROUP BY
    p.spid,
    p.last_batch,
    p.[program_name],
    p.hostname,
    spid.stmt_start,
    spid.stmt_end,
    spid.[sql_handle]
ORDER BY
    batch_duration DESC,
    p.spid
;


问:
Enum variables in Swift?
I would like to associate multiple values with an enum value, in a generic way.

This can be done in Java:

```<code>enum Test {

    A("test", 2);

    final String var1;
    final int var2;

    Test (String var1, int var2) {
        this.var1 = var1;
        this.var2 = var2;
    }
}

 public static void main(String []args){
    Test test = Test.A;
    System.out.println(test.var1);
 }
</code>```

But it looks like it's not possible with Swift? So far, according to docs, there are:

Associated values. Example (from docs):

```<code>enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}
</code>```

But this is not what I need.

Raw value. Example (from docs):

```<code>enum ASCIIControlCharacter: Character {
    case Tab = "\t"
    case LineFeed = "\n"
    case CarriageReturn = "\r"
}
</code>```

This would be what I need, but it can have only one value!

Is there an elegant solution for this...? Seems like a language design decision, as it would conflict with the associated values concept, at least in the current form. I know I could use e.g. a dictionary to map the enum values to the rest, but really missing to do this in one safe step, like in Java.

答:
I'm not familiar enough with Swift's history to know if this was possible back when the question was asked. But this is what I would do today in Swift 5.x:

```<code>enum Direction {
    case north
    case east
    case south
    case west

    func name() -> String {
        switch self {
        case .north: return "North"
        case .east: return "East"
        case .south: return "South"
        case .west: return "West"
        }
    }

    func degress() -> Double {
        switch self {
        case .north: return 0.0
        case .east: return 90.0
        case .south: return 180.0
        case .west: return 270.0
        }
    }
}
</code>```

It retains all the benefits of Swift enums, chief of all, IMO, the ability for the compiler to infer when your code is exhaustive when pattern matching.

Title: Enum variables in Swift?

Body:
I would like to associate multiple values with an enum value, in a generic way.

This can be done in Java:

enum Test {

    A("test", 2);

    final String var1;
    final int var2;

    Test (String var1, int var2) {
        this.var1 = var1;
        this.var2 = var2;
    }
}

 public static void main(String []args){
    Test test = Test.A;
    System.out.println(test.var1);
 }

But it looks like it's not possible with Swift? So far, according to docs, there are:

Associated values. Example (from docs):

enum Barcode {
    case UPCA(Int, Int, Int, Int)
    case QRCode(String)
}

But this is not what I need.

Raw value. Example (from docs):

enum ASCIIControlCharacter: Character {
    case Tab = "\t"
    case LineFeed = "\n"
    case CarriageReturn = "\r"
}

This would be what I need, but it can have only one value!

Is there an elegant solution for this...? Seems like a language design decision, as it would conflict with the associated values concept, at least in the current form. I know I could use e.g. a dictionary to map the enum values to the rest, but really missing to do this in one safe step, like in Java.

Body:
I'm not familiar enough with Swift's history to know if this was possible back when the question was asked. But this is what I would do today in Swift 5.x:

enum Direction {
    case north
    case east
    case south
    case west

    func name() -> String {
        switch self {
        case .north: return "North"
        case .east: return "East"
        case .south: return "South"
        case .west: return "West"
        }
    }

    func degress() -> Double {
        switch self {
        case .north: return 0.0
        case .east: return 90.0
        case .south: return 180.0
        case .west: return 270.0
        }
    }
}

It retains all the benefits of Swift enums, chief of all, IMO, the ability for the compiler to infer when your code is exhaustive when pattern matching.


问:
SwiftUI: Setting individual colors for .toolbar ToolbarItem?
Generally I like to stick with default color options for accessibility reasons, but I have a specific use case and I am unable to change an individual .toolbar ToolbarItem color.

I can override all ToolbarItem colors by using the commented out code at top of my snippet, but I want to color individual icons.

```<code>import SwiftUI

struct ContentView: View {

//    init() {
//        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIToolbar.self]).tintColor = .systemRed
//    }

    var body: some View {

        NavigationView {

            Text("Hello, world!")
                .toolbar {

                    // To be colored RED
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon One", systemImage: "stop.fill")})
                    }

                    // To be colored BLACK
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon Two", systemImage: "play.fill")})
                    }

                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

答:
Sadly this trick only works on iOS.

But on the bright side it also works for Menu as well:

```<code>Menu {
    Button("A title") {}
} label : {
    HStack {
            Label("Star"), systemImage: "star")
                .labelStyle(.iconOnly)
                .foregroundColor(.red)
                Spacer(minLength: 0)
    }
}

</code>```

Body:
Generally I like to stick with default color options for accessibility reasons, but I have a specific use case and I am unable to change an individual .toolbar ToolbarItem color.

I can override all ToolbarItem colors by using the commented out code at top of my snippet, but I want to color individual icons.

import SwiftUI

struct ContentView: View {

//    init() {
//        UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIToolbar.self]).tintColor = .systemRed
//    }

    var body: some View {

        NavigationView {

            Text("Hello, world!")
                .toolbar {

                    // To be colored RED
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon One", systemImage: "stop.fill")})
                    }

                    // To be colored BLACK
                    ToolbarItem(placement: .bottomBar) {
                        Button(action: {}, label: {Label("Icon Two", systemImage: "play.fill")})
                    }

                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Body:
Sadly this trick only works on iOS.

But on the bright side it also works for Menu as well:

Menu {
    Button("A title") {}
} label : {
    HStack {
            Label("Star"), systemImage: "star")
                .labelStyle(.iconOnly)
                .foregroundColor(.red)
                Spacer(minLength: 0)
    }
}


问:
Facebook\WebDriver\Exception\UnknownErrorException: unknown error: net::ERR_CONNECTION_REFUSED (Session info: headless chrome=96.0.4664.110)
I have tried changing the APP_URL in env,
Updated Chrome driver.

Tried dusk outside sail shell using "sail dusk" and getting..

Facebook\WebDriver\Exception\UnknownErrorException: unknown error: net::ERR_CONNECTION_REFUSED   (Session info: headless chrome=96.0.4664.110)

If I try inside sail shell, I'm getting..

Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"capabilities":{"firstMatch":[{"browserName":"chrome","goog:chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}]},"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"args":["--window-size=1920,1080","--disable-gpu","--headless"]}}}

Failed to connect to localhost port 9515: Connection refused.

I couldn't find any answers anywhere.

答: You can update the chrome version and find the chromewebdriver compatible with it</p>


问:
GIT downloaded dev and branched to feature
I have one local dev branch coming from the origin master.
I created a feature branch off of the local dev.

Did some work and pushed the feature up-stream back to origin.  It now appears on the server branches.

However, now dev has had changes by other developers... so I did a git pull to my local dev branch, which is now sync-ed up to the server.

Now I need to get those changes into my feature from the local dev before I push feature back up to the origin server.  (OR do I directly merge/pull/whatever from server dev into the feature).

Obviously Im confused.

Thanks in advance for you help/clarification.

答:
If the idea is to update your feature branch to catch up with the current state of dev, then pull dev (you did that), switch to feature, and merge dev into feature.

Alternatively, if you have not pushed feature yet, you can pull dev (you did that), switch to feature, and rebase feature onto dev.


问:
Python: how to plot data coming from different excel sheets in the same chart
I need to create an interactive chart on python taking data from different sheets of an Excel file. I tried to create a for loop to take data from all the sheets automatically, but I manage to graph only data coming from the last sheet of the file.
I also would like to create a legend with the names of the sheets where data come from. This is my code, can you help me improving it?</p>
```<code>import openpyxl as xl
import os, os.path
import pandas as pd
import plotly.express as px

output_data2=r'C:\\Users\\Desktop\\Vibration data analysis'

wb=xl.load_workbook(os.path.join(output_data2, "RMS Comparison.xlsx"))
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(os.path.join(output_data2, "RMS Comparison.xlsx"),sheet_name=sheet.title)
        fig = px.line(df, x='Unnamed: 0', y='Unnamed: 2')
fig.show()
</code>```

答:
have simulated a workbook to demonstrate plotly code

create a figure, then add a line per worksheet

```<code>import openpyxl as xl
from pathlib import Path
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

f = Path.cwd().joinpath("RMS Comparison.xlsx")

# create an Excel with multiple sheets
with pd.ExcelWriter(f) as writer:
    for s in "ABCDEF":
        pd.DataFrame({c:np.random.randint(1,10,30) if c[-1]!="0" else np.linspace(1,20, 30) for c in ['Unnamed: 0', 'Unnamed: 2']}).to_excel(writer, sheet_name=s)

# create a figure with a line per worksheet
wb=xl.load_workbook(f)
fig = go.Figure()
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(f,sheet_name=sheet.title)
        fig = fig.add_traces(px.line(df, x='Unnamed: 0', y='Unnamed: 2').update_traces(name=sheet.title, showlegend=True).data)

fig.show()
</code>```

Body:
I need to create an interactive chart on python taking data from different sheets of an Excel file. I tried to create a for loop to take data from all the sheets automatically, but I manage to graph only data coming from the last sheet of the file.
I also would like to create a legend with the names of the sheets where data come from. This is my code, can you help me improving it?

import openpyxl as xl
import os, os.path
import pandas as pd
import plotly.express as px

output_data2=r'C:\\Users\\Desktop\\Vibration data analysis'

wb=xl.load_workbook(os.path.join(output_data2, "RMS Comparison.xlsx"))
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(os.path.join(output_data2, "RMS Comparison.xlsx"),sheet_name=sheet.title)
        fig = px.line(df, x='Unnamed: 0', y='Unnamed: 2')
fig.show()

Body:
have simulated a workbook to demonstrate plotly code

create a figure, then add a line per worksheet

import openpyxl as xl
from pathlib import Path
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

f = Path.cwd().joinpath("RMS Comparison.xlsx")

# create an Excel with multiple sheets
with pd.ExcelWriter(f) as writer:
    for s in "ABCDEF":
        pd.DataFrame({c:np.random.randint(1,10,30) if c[-1]!="0" else np.linspace(1,20, 30) for c in ['Unnamed: 0', 'Unnamed: 2']}).to_excel(writer, sheet_name=s)

# create a figure with a line per worksheet
wb=xl.load_workbook(f)
fig = go.Figure()
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(f,sheet_name=sheet.title)
        fig = fig.add_traces(px.line(df, x='Unnamed: 0', y='Unnamed: 2').update_traces(name=sheet.title, showlegend=True).data)

fig.show()


问:
Ajax Call return error like "The POST method is not supported for this route. Supported methods: OPTIONS " in Laravel
I am fetching some data from server using ajax on page loading. But these calls always returns error as The POST method is not supported for this route. Supported methods: OPTIONS. I have tried all the options I can but no use. Here is my code.

```<code>        var today = new Date();
        var monthYear = moment(today).format('MMM/YYYY');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: baseUrl + 'statisticalboxes',
            method: 'POST',
            data: {
                'project-month': monthYear
            },
            success: function(data) {
                console.log(data);
            },
            error:function(e) {
                console.log(e);
            }
        });
</code>```

web.php

```<code>Route::post('statisticalboxes', ['as' => 'statisticalboxes','uses' => 'DashboardController@getStasticalBoxData']);
</code>```

I have changed method into all other options, but no use.
When I look into the network tab, the requested url look like
Request URL: http://127.0.0.1:8000/nullstatisticalboxes, but the actual one is Request URL: http://127.0.0.1:8000/statisticalboxes

答:
Your baseUrl variable return null value.

Where you define baseUrl?

Define baseUrl variable.

--- OR ---

Use url like this.

url: '/statisticalboxes',
```

Body:
I am fetching some data from server using ajax on page loading. But these calls always returns error as The POST method is not supported for this route. Supported methods: OPTIONS. I have tried all the options I can but no use. Here is my code.

        var today = new Date();
        var monthYear = moment(today).format('MMM/YYYY');
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: baseUrl + 'statisticalboxes',
            method: 'POST',
            data: {
                'project-month': monthYear
            },
            success: function(data) {
                console.log(data);
            },
            error:function(e) {
                console.log(e);
            }
        });

web.php

Route::post('statisticalboxes', ['as' => 'statisticalboxes','uses' => 'DashboardController@getStasticalBoxData']);

I have changed method into all other options, but no use.
When I look into the network tab, the requested url look like
Request URL: http://127.0.0.1:8000/nullstatisticalboxes, but the actual one is Request URL: http://127.0.0.1:8000/statisticalboxes


问:
Google Directions API don't consider depature dates for temporarily closed routes
I want to use the directions API from Google Maps to get a route between two waypoints.

For example take these two:

Barcelonnette, 04400, France

Cime de la Bonette, 04850 Jausiers, France

There is a temporarily closed route between those waypoints, if I change the destination date in Google Maps to 2022-02-25, the route is used (which is correct, cause it is opened than).

If I try to get the same result with directions API, with this payload

{
  key: 'xxx',
  origin: 'place_id:ChIJPW2q1MfszBIRRpzUj4a7mFE',
  destination: 'place_id:ChIJGVSqBcnxzBIRMQdNNe4usKw',
  alternatives: true,
  mode: 'driving',
  language: 'de',
  departure_time: 1645803229
}
```

I only get the longer route, that I also get in Maps with date 2022-01-03.

Is there any other way to get the API to recognize my date?

答: We did some further checks and it seemed to be only an error in our implementation. It's important to send the departure_time in seconds and not in milliseconds, as for example javascripts getTime() method provide them. In the same time we are testing this change, the opening days of the route had changed and let's us think that this change did not solve the issue.

Body:
I want to use the directions API from Google Maps to get a route between two waypoints.

For example take these two:

Barcelonnette, 04400, France

Cime de la Bonette, 04850 Jausiers, France

There is a temporarily closed route between those waypoints, if I change the destination date in Google Maps to 2022-02-25, the route is used (which is correct, cause it is opened than).

If I try to get the same result with directions API, with this payload

{
  key: 'xxx',
  origin: 'place_id:ChIJPW2q1MfszBIRRpzUj4a7mFE',
  destination: 'place_id:ChIJGVSqBcnxzBIRMQdNNe4usKw',
  alternatives: true,
  mode: 'driving',
  language: 'de',
  departure_time: 1645803229
}

I only get the longer route, that I also get in Maps with date 2022-01-03.

Is there any other way to get the API to recognize my date?


问:
JavaScript/DOM - Is there a difference between a "CSS Selector" and an attribute?
Excluding declarative event handlers:

href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

href='#' my-data-node-type='1'/>

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?

答:
A CSS selector is used within the CSS document. It is the string which selects the element you wish to style, by element name, id, css or whatever else.

.myDiv, #myDivid are selectors.

"my-data-node-type" could be used to select your element, #myDiv a[my-data-node-type='1']

Attributes are what you use to style the element itself.

```<code>#myDiv a[my-data-node-type='1']
{
    color: #000; /*this is an attribute*/
}
</code>```

Hope this helps.

Body:
Excluding declarative event handlers:

<a href='#' onclick=<handler> ... />

Is there any material difference between an Attribute and a CSS Selector?  If I provide my own attribute:

Is "my-data-node-type" an attribute, a CSS Selector or both?  I think what I'm really asking here is, are the terms "attribute" and "css selector" synonymous?  Or is a "css selector" only an attribute recognized by CSS as eligible for styling?

Body:
A CSS selector is used within the CSS document. It is the string which selects the element you wish to style, by element name, id, css or whatever else.

.myDiv, #myDivid are selectors.

"my-data-node-type" could be used to select your element, #myDiv a[my-data-node-type='1']

Attributes are what you use to style the element itself.

#myDiv a[my-data-node-type='1']
{
    color: #000; /*this is an attribute*/
}

Hope this helps.


问:
python : generate month between date with boundaries
let's first put my code

```<code>start = datetime(2022,1,5)
end = datetime(2022,5,9)
date_range = (pd.date_range(start, end, freq='MS').to_pydatetime().tolist())
print(test)
if start not in date_range:
    test.insert(0,start)
if end not in date_range:
    test.append(end)
</code>```

What I am trying to do is to generate a list of month between 2 dates, containing these 2 dates.
So if I take 5/1/2021 and 9/5/2022 the list generated should be :

```<code>[5/1/2021, 1/2/2021, 1/3/2021, 1/4/2021, 1/5/2021, 9/5/2021]
</code>```

my issue is pandas date_range return only the month between the date if I choose frequence 'MS', I need to check right after if I have to insert the date or not (basically, if I take 1/1/2021 and 1/5/2021 as start date and end date, they will be here)

Is there a better way to do that in python or I am forced to used these two if after my generation?

Thanks

答:
Let us use Index.union after generating the date_range:

```<code>pd.date_range(start, end, freq='MS').union([start, end])
</code>```

```<code>DatetimeIndex(['2022-01-05', '2022-02-01', '2022-03-01', '2022-04-01',
               '2022-05-01', '2022-05-09'],
              dtype='datetime64[ns]', freq=None)
</code>```

Body:
let's first put my code

start = datetime(2022,1,5)
end = datetime(2022,5,9)
date_range = (pd.date_range(start, end, freq='MS').to_pydatetime().tolist())
print(test)
if start not in date_range:
    test.insert(0,start)
if end not in date_range:
    test.append(end)

What I am trying to do is to generate a list of month between 2 dates, containing these 2 dates.
So if I take 5/1/2021 and 9/5/2022 the list generated should be :

[5/1/2021, 1/2/2021, 1/3/2021, 1/4/2021, 1/5/2021, 9/5/2021]

my issue is pandas date_range return only the month between the date if I choose frequence 'MS', I need to check right after if I have to insert the date or not (basically, if I take 1/1/2021 and 1/5/2021 as start date and end date, they will be here)

Is there a better way to do that in python or I am forced to used these two if after my generation?

Thanks

Body:
Let us use Index.union after generating the date_range:

pd.date_range(start, end, freq='MS').union([start, end])

DatetimeIndex(['2022-01-05', '2022-02-01', '2022-03-01', '2022-04-01',
               '2022-05-01', '2022-05-09'],
              dtype='datetime64[ns]', freq=None)


问:
Why does my functions seem to integrate and not differentiate? (pywt.cwt)
I am really confused by the function pywt.cwt, as I've not been able to get it to work. The function seems to integrate instead of differentiating. I would like to work it as the following: Example CWT, but my graph looks like this: My CWT. The idea is to integrate the raw signal (av) with cumtrapz, then differentiate with a gaussian CWT (=> S1), and then once more differentiate with gaussian CWT (=> S2).

As you can see in the pictures, the bottom peaks of the red line should line up in the valleys, but the land under the top peaks for me, and the green line should move 1/4th period to the left but moves to the right... Which makes me think it integrates for some reason.

I currently have no idea what causes this... Does anyone happen to know what is going on?

Thanks in advance!

```<code>#Get data from pandas
av = dfRange['y']

#remove gravity & turns av right way up
av = av - dfRange['y'].mean()
av = av * -1

#Filter
[b,a] = signal.butter(4, [0.9/(55.2/2), 20/(55.2/2)], 'bandpass')
av = signal.filtfilt(b,a, av)

#Integrate and differentiate av => S1
integrated_av = integrate.cumtrapz(av)
[CWT_av1, frequency1] = pywt.cwt(integrated_av, 8.8 , 'gaus1', 1/55.2)
CWT_av1 = CWT_av1[0]
CWT_av1 = CWT_av1 * 0.05

#differentiate S1 => S2
[CWT_av2, frequency2] = pywt.cwt(CWT_av1, 8.8 , 'gaus1', 1/55.2)
CWT_av2 = CWT_av2[0]
CWT_av2 = CWT_av2 * 0.8

#Find Peaks
inv_CWT_av1 = CWT_av1 * -1
av1_min, _ = signal.find_peaks(inv_CWT_av1)
av2_max, _ = signal.find_peaks(CWT_av2)

#Plot
plt.style.use('seaborn')
plt.figure(figsize=(25, 7), dpi = 300)
plt.plot_date(dfRange['recorded_naive'], av, linestyle = 'solid', marker = None, color = 'steelblue')
plt.plot_date(dfRange['recorded_naive'][:-1], CWT_av1[:], linestyle = 'solid', marker = None, color = 'red')
plt.plot(dfRange['recorded_naive'].iloc[av1_min], CWT_av1[av1_min], "ob", color = 'red')
plt.plot_date(dfRange['recorded_naive'][:-1], CWT_av2[:], linestyle = 'solid', marker = None, color = 'green')
plt.plot(dfRange['recorded_naive'].iloc[av2_max], CWT_av2[av2_max], "ob", color = 'green')
plt.gcf().autofmt_xdate()
plt.show()
</code>```

答:
I'm not sure this is your answer, but an observation from playing with pywt...

From the documentation the wavelets are basically given by the differentials of a Gaussian but there is an order dependent normalisation constant.

Plotting the differentials of a Guassian against the wavelets (extracted by putting in an impulse response) gives the following:

The interesting observation is that the order dependent normalisation constant sometimes seems to include a '-1'. In particular, it does for the first order gaus1.

So, my question is, could you actually have differentiation as you expect, but also multiplication by -1?

Code for the graph:

import numpy as np
import matplotlib.pyplot as plt

import pywt

dt = 0.01
t = dt * np.arange(100)

# Calculate the differentials of a gaussian by quadrature:
# start with the gaussian y = exp(-(x - x_0) ^ 2 / dt)
ctr = t[len(t) // 2]
gaus = np.exp(-np.power(t - ctr, 2)/dt)
gaus_quad = [np.gradient(gaus, dt)]
for i in range(7):
    gaus_quad.append(np.gradient(gaus_quad[-1], dt))

# Extract the wavelets using the impulse half way through the dataset
y = np.zeros(len(t))
y[len(t) // 2] = 1
gaus_cwt = list()
for i in range(1, 9):
    cwt, cwt_f = pywt.cwt(y, 10, f'gaus{i}', dt)
    gaus_cwt.append(cwt[0])

fig, axs = plt.subplots(4, 2)

for i, ax in enumerate(axs.flatten()):
    ax.plot(t, gaus_cwt[i] / np.max(np.abs(gaus_cwt[i])))
    ax.plot(t, gaus_quad[i] / np.max(np.abs(gaus_quad[i])))
    ax.set_title(f'gaus {i+1}', x=0.2, y=1.0, pad=-14)
    ax.axhline(0, c='k')
    ax.set_xticks([])
    ax.set_yticks([])
```

Body:
I am really confused by the function pywt.cwt, as I've not been able to get it to work. The function seems to integrate instead of differentiating. I would like to work it as the following: Example CWT, but my graph looks like this: My CWT. The idea is to integrate the raw signal (av) with cumtrapz, then differentiate with a gaussian CWT (=> S1), and then once more differentiate with gaussian CWT (=> S2).

As you can see in the pictures, the bottom peaks of the red line should line up in the valleys, but the land under the top peaks for me, and the green line should move 1/4th period to the left but moves to the right... Which makes me think it integrates for some reason.

I currently have no idea what causes this... Does anyone happen to know what is going on?

Thanks in advance!

#Get data from pandas
av = dfRange['y']

#remove gravity & turns av right way up
av = av - dfRange['y'].mean()
av = av * -1

#Filter
[b,a] = signal.butter(4, [0.9/(55.2/2), 20/(55.2/2)], 'bandpass')
av = signal.filtfilt(b,a, av)

#Integrate and differentiate av => S1
integrated_av = integrate.cumtrapz(av)
[CWT_av1, frequency1] = pywt.cwt(integrated_av, 8.8 , 'gaus1', 1/55.2)
CWT_av1 = CWT_av1[0]
CWT_av1 = CWT_av1 * 0.05

#differentiate S1 => S2
[CWT_av2, frequency2] = pywt.cwt(CWT_av1, 8.8 , 'gaus1', 1/55.2)
CWT_av2 = CWT_av2[0]
CWT_av2 = CWT_av2 * 0.8

#Find Peaks
inv_CWT_av1 = CWT_av1 * -1
av1_min, _ = signal.find_peaks(inv_CWT_av1)
av2_max, _ = signal.find_peaks(CWT_av2)

#Plot
plt.style.use('seaborn')
plt.figure(figsize=(25, 7), dpi = 300)
plt.plot_date(dfRange['recorded_naive'], av, linestyle = 'solid', marker = None, color = 'steelblue')
plt.plot_date(dfRange['recorded_naive'][:-1], CWT_av1[:], linestyle = 'solid', marker = None, color = 'red')
plt.plot(dfRange['recorded_naive'].iloc[av1_min], CWT_av1[av1_min], "ob", color = 'red')
plt.plot_date(dfRange['recorded_naive'][:-1], CWT_av2[:], linestyle = 'solid', marker = None, color = 'green')
plt.plot(dfRange['recorded_naive'].iloc[av2_max], CWT_av2[av2_max], "ob", color = 'green')
plt.gcf().autofmt_xdate()
plt.show()


问:
Upgrading Angular in 2022
I read https://update.angular.io/?v=12.0-13.0
So in Visual Studio

npx @angular/cli@13 update @angular/core@13 @angular/cli@13

All looks good, but I am confused by various versions listed in various places.

> ng v

Shows

```<code>...
Angular CLI: 13.2.3
Node: 14.18.0
Package Manager: npm 6.14.15
OS: win32 x64

Angular: 13.2.2
... animations, cdk, common, compiler, compiler-cli, core, forms
... language-service, material, platform-browser
... platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1302.3
@angular-devkit/build-angular   13.2.3
@angular-devkit/core            12.1.4
@angular-devkit/schematics      12.1.4
@angular/cli                    13.2.3
@schematics/angular             12.1.4
rxjs                            6.6.7
typescript                      4.5.5
</code>```

Hmm, I guess all those 12 are okay, but I don't know.  Are they?  Should I upgrade and how do I upgrade them?

But if I try

```<code>> npm outdated -g
Package       Current   Wanted  Latest  Location
@angular/cli   12.2.4  12.2.16  13.2.3  global
</code>```

Outside of Visual Studio I'm told ng is using a version 12.

```<code>> ng v
Angular CLI: 12.2.4
[...]
Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1202.4 (cli-only)
@angular-devkit/core         12.2.4 (cli-only)
@angular-devkit/schematics   12.2.4 (cli-only)
@schematics/angular          12.2.4 (cli-only)
</code>```

Why does two different ng v commands and npm outdated appear to differ (or maybe my understanding of the ng v isn't correct) and what might I do to straighten these things out so I can use all the latest stuff?

答:
You can have two different versions in two places (the local project and globally), and that is normal.

The reason is that you have installed Angular once globally (The version which is displayed when you run ng v anywhere, but the local project) and when you create a new project with ng new the global version will be taken, but will have separate node_modules which is local for just the new project created.

Now if you update the version in the project you have created, that will update only the local version for that project, the global Angular version will remain the same.

In order to update the global version, you can achieve with the same command but just with -g as an argument.

And the answer to your latest question:

ng v run outside of the local project gives the same results as npm outdated -g - consider the global version.

ng v run inside the local project should give the same results as npm outdated run inside the local project - consider the local project version.

Title: Upgrading Angular in 2022

Body:
I read https://update.angular.io/?v=12.0-13.0
So in Visual Studio

npx @angular/cli@13 update @angular/core@13 @angular/cli@13

All looks good, but I am confused by various versions listed in various places.

> ng v

Shows

...
Angular CLI: 13.2.3
Node: 14.18.0
Package Manager: npm 6.14.15
OS: win32 x64

Angular: 13.2.2
... animations, cdk, common, compiler, compiler-cli, core, forms
... language-service, material, platform-browser
... platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1302.3
@angular-devkit/build-angular   13.2.3
@angular-devkit/core            12.1.4
@angular-devkit/schematics      12.1.4
@angular/cli                    13.2.3
@schematics/angular             12.1.4
rxjs                            6.6.7
typescript                      4.5.5

Hmm, I guess all those 12 are okay, but I don't know.  Are they?  Should I upgrade and how do I upgrade them?

But if I try

> npm outdated -g
Package       Current   Wanted  Latest  Location
@angular/cli   12.2.4  12.2.16  13.2.3  global

Outside of Visual Studio I'm told ng is using a version 12.

> ng v
Angular CLI: 12.2.4
[...]
Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.1202.4 (cli-only)
@angular-devkit/core         12.2.4 (cli-only)
@angular-devkit/schematics   12.2.4 (cli-only)
@schematics/angular          12.2.4 (cli-only)

Why does two different ng v commands and npm outdated appear to differ (or maybe my understanding of the ng v isn't correct) and what might I do to straighten these things out so I can use all the latest stuff?


问:
Simulate mouseenter with pure css
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

```<code>*:hover {
    border-color: red;
}
</code>```

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div>

    </div>
  </article>
</main></code>```

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

答:
You can't avoid the parent :hover with pure CSS today. There are quite a few topics on SO discussing this:

How to apply child:hover but not parent:hover

Safari has introduced support for a :has parent selector, and might solve this if other browsers support it as well. But it's still not a viable option today.

You asked if you can achieve this with javascript, and yes you can hack a solution in javascript using mouseenter and mouseleave events, toggling a CSS class.

https://jsfiddle.net/sq1kcwdt/4/

Title: Simulate mouseenter with pure css

Body:
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

*:hover {
    border-color: red;
}

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?


问:
How do I convert a nested array of Woocommerce products into a Javascript object?
I am trying to access the stock_quantity, ID and SKU for woocommerce products in a php array.

I need to get the SKU to compare it against a value in my JavaScript code so that I can display the stock_quantity for the selected product and update an add to cart link with the selected product ID.

I am getting the products by creating a query that returns any product with a SKU containing the $tag variable I am passing it like this:

```<code>// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();
</code>```

Ideally I would like to convert this php array into a javacript array with all the nested arrays/objects in tact. This snippet will successfully log the array to the console and I can see that the array does in fact contain the products I need access to.

```<code>echo "<script>console.log(".json_encode(var_export($products, true)).");</script>";
</code>```

If its not possible to simply convert the array and all the nested content into a javscript array, Im wondering if perhaps there is a way to recursively loop through the php array and push the content to a javascript array.

Any help would be greatly appreciated! This is my first stack overflow post!

答:
If you want to send data from php to javascript you can use such a thing.

In php:

```<code>$vars = [
    'data1' => ["first" => 1, "second" => 2],
     ... some many proprieties
];

wp_localize_script('name_of_script', 'name_of_variables', $vars);
</code>```

In javascript :

```<code> console.log(name_of_variables.data1)
</code>```

Maybe the IDE will tell you that he cannot find the variable, because the variable is in PHP page.
Then in javascript you can use it as you like

I hope it will be useful to you
Best regards

Body:
I am trying to access the stock_quantity, ID and SKU for woocommerce products in a php array.

I need to get the SKU to compare it against a value in my JavaScript code so that I can display the stock_quantity for the selected product and update an add to cart link with the selected product ID.

I am getting the products by creating a query that returns any product with a SKU containing the $tag variable I am passing it like this:

// Get any products with SKU that includes tag
$query = new WC_Product_Query();
$query->set( 'sku', $tag );
$products = $query->get_products();

Ideally I would like to convert this php array into a javacript array with all the nested arrays/objects in tact. This snippet will successfully log the array to the console and I can see that the array does in fact contain the products I need access to.

echo "";

If its not possible to simply convert the array and all the nested content into a javscript array, Im wondering if perhaps there is a way to recursively loop through the php array and push the content to a javascript array.

Any help would be greatly appreciated! This is my first stack overflow post!

Body:
If you want to send data from php to javascript you can use such a thing.

In php:

$vars = [
    'data1' => ["first" => 1, "second" => 2],
     ... some many proprieties
];

wp_localize_script('name_of_script', 'name_of_variables', $vars);

In javascript :

 console.log(name_of_variables.data1)

Maybe the IDE will tell you that he cannot find the variable, because the variable is in PHP page.
Then in javascript you can use it as you like

I hope it will be useful to you
Best regards


问:
C++ and STL refresher course
I know C and C++ quite well. I know in much detail about pointers and well versed with pointer arithmetic and worked on Win32 API and a bit of MFC as well in my university days. In my previous job, I had no chance to look on these matters and worked in some other domain. Now what I want is a crash or refresher course in:

C++

STL

I do not want to go through 500+ pages of books because I know C#, Java, Ruby, Python and even x86 Assembly as well. What I want is to cover advanced and dark corners of C++ and intermediate STL.

Can anyone point out good links about it?
I know about Google! ;-)
But an intelligent human recommendation is something else yet Google has not implemented.

答: A quick read through of one or more of the 'Effective' books by Meyers and/or the 'Exceptional' books by Sutter would make a nice refresher course.  They're short and generally easy reads for someone who's not a novice, but they'll refresh your memory on some of the edge cases you need to know about.</p>

OwnerDisplayName: Mohsin Hijazee

Title: C++ and STL refresher course

LastEditorDisplayName: Ferruccio

OwnerDisplayName: Michael Burr


问:
flutter_offline library issue: Conflicts of library for Reachability in iOS
My flutter app was running well even with Xcode 13.2.1. After making some changes to the code, I tried to build it with iOS. It's building alright. But when I try to Archive the project for Testflight I am having the following error.

Multiple commands produce
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework':

Target 'Reachability' has create directory command with output
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework'

Target 'ReachabilitySwift' has create directory command with output
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework'

There is also a Target Integrity issue.

Multiple targets match implicit dependency for linker flags
'-framework Reachability'. Consider adding an explicit dependency on
the intended target to resolve this ambiguity. (in target 'Runner'
from project 'Runner')

Target 'Reachability' (in project 'Pods')

Target 'ReachabilitySwift' (in project 'Pods')

I have tried all the solutions I could fing over the last 4 days. Still no luck. I am currently on Flutter (Channel master, 2.11.0-0.0.pre.450, on macOS 12.1) with M1 Max processor. Following is the Podfile

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

</code>```

答: You have added more than one connectivity plugins in your pubspec.yaml file. Please remove all of the other plugins and put only one.

Body:
My flutter app was running well even with Xcode 13.2.1. After making some changes to the code, I tried to build it with iOS. It's building alright. But when I try to Archive the project for Testflight I am having the following error.

Multiple commands produce
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework':

Target 'Reachability' has create directory command with output
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework'

Target 'ReachabilitySwift' has create directory command with output
'/Users/mdhasanrahman/Library/Developer/Xcode/DerivedData/Runner-fgzktmibyndpbgfkmsizqhgncvxe/Build/Intermediates.noindex/ArchiveIntermediates/Runner/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Reachability.framework'

There is also a Target Integrity issue.

Multiple targets match implicit dependency for linker flags
'-framework Reachability'. Consider adding an explicit dependency on
the intended target to resolve this ambiguity. (in target 'Runner'
from project 'Runner')

Target 'Reachability' (in project 'Pods')

Target 'ReachabilitySwift' (in project 'Pods')

I have tried all the solutions I could fing over the last 4 days. Still no luck. I am currently on Flutter (Channel master, 2.11.0-0.0.pre.450, on macOS 12.1) with M1 Max processor. Following is the Podfile

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end


问:
Android Volley: How to flush and disable cache?
On my Android phone, I use Volley to do an HTTP POST request. The server sent an error response indicating a problem in the JSON data that I have passed. I have fixed the error but the server still display the same error. I have tried to pass an empty JSON file and I still get the same error response so the response clearly comes from some cached data.

I have tried to use those 2 things to clear and disable the cache but it doesn't help:

```<code>mRequestQueue = Volley.newRequestQueue(this);

mRequestQueue.getCache().clear(); // <==== Here

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, dataObject, ...);

jsonObjReq.setShouldCache(false);  // <==== Here

mRequestQueue.add(jsonObjReq);
</code>```

How can I disable the Cache used by Volley or Android?

If I use Curl to execute the same request it works.

Thanks

答:
I have been able to fix the issue. I was using JsonObjectRequest and the server didn't understand the JSON file that I was sending.

I'm now using StringRequest() and it works.

Here is the non working code using JsonObjectRequest:
https://www.thethingsnetwork.org/forum/t/error-when-trying-to-add-an-end-device-from-http-api/55088/18?u=oliviergrenoble

And here is the working code using StringRequest:
https://www.thethingsnetwork.org/forum/t/error-when-trying-to-add-an-end-device-from-http-api/55088/21?u=oliviergrenoble

I have probably done something wrong in JsonObjectRequest version!

Body:
On my Android phone, I use Volley to do an HTTP POST request. The server sent an error response indicating a problem in the JSON data that I have passed. I have fixed the error but the server still display the same error. I have tried to pass an empty JSON file and I still get the same error response so the response clearly comes from some cached data.

I have tried to use those 2 things to clear and disable the cache but it doesn't help:

mRequestQueue = Volley.newRequestQueue(this);

mRequestQueue.getCache().clear(); // <==== Here

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, dataObject, ...);

jsonObjReq.setShouldCache(false);  // <==== Here

mRequestQueue.add(jsonObjReq);

How can I disable the Cache used by Volley or Android?

If I use Curl to execute the same request it works.

Thanks


问:
How to generate combinations of elements of different lists?
I have a list of lists that goes like

```<code>[[1,2,3],[3,4,5],[5,6,7,8]]
</code>```

I want to create a program/function that creates a combinations like

```<code>1,3,5
1,3,6
1,3,7
1,3,8
1,4,5
1,4,6
.
.
.
</code>```

If there's a way you can do it without using the itertools module, that would be even more appreciated.

Body:
I have a list of lists that goes like

[[1,2,3],[3,4,5],[5,6,7,8]]

I want to create a program/function that creates a combinations like

1,3,5
1,3,6
1,3,7
1,3,8
1,4,5
1,4,6
.
.
.

If there's a way you can do it without using the itertools module, that would be even more appreciated.

Body:
you can use  itertools.product

import itertools
a = [[1,2,3],[3,4,5],[5,6,7,8]]
list(itertools.product(*a))
#output
[(1, 3, 5),
 (1, 3, 6),
 (1, 3, 7),
 (1, 3, 8),
 (1, 4, 5),
 (1, 4, 6),
 (1, 4, 7),
 (1, 4, 8),
 (1, 5, 5),
 (1, 5, 6),
 (1, 5, 7),
 (1, 5, 8),
 (2, 3, 5),
 (2, 3, 6),
 (2, 3, 7),
 (2, 3, 8),
 (2, 4, 5),
 (2, 4, 6),
 (2, 4, 7),
 (2, 4, 8),
 (2, 5, 5),
 (2, 5, 6),
 (2, 5, 7),
 (2, 5, 8),
 (3, 3, 5),
 (3, 3, 6),
 (3, 3, 7),
 (3, 3, 8),
 (3, 4, 5),
 (3, 4, 6),
 (3, 4, 7),
 (3, 4, 8),
 (3, 5, 5),
 (3, 5, 6),
 (3, 5, 7),
 (3, 5, 8)]


问:
IntelliJ: Could not target platform: 'Java SE 12' using tool chain: 'JDK 11 (11)'
First of all, I read similar questions and none of them could help me solve it. I use Gradle for building the project. Although I'm using Java 12 (Java 12 is written in the project structure, module settings and run configs) and I tried invalidating the caches and restart. I still keep getting the error I mentioned in the title when I start running my program. Does anyone have any idea on the possible solution?</p>

答:
In my case, I was using IntelliJ Idea. I tried setting SDK from 'Project Structure' as well as setting gradle JVM, but it did not work until I set JAVA_HOME in intellij terminal.

```<code>set JAVA_HOME="C:/Program Files/Java/java12"
</code>```

Then, I ran gradle build. And, it worked.

Body:
In my case, I was using IntelliJ Idea. I tried setting SDK from 'Project Structure' as well as setting gradle JVM, but it did not work until I set JAVA_HOME in intellij terminal.

set JAVA_HOME="C:/Program Files/Java/java12"

Then, I ran gradle build. And, it worked.


问:
How to get a list of every video from a channel using the YouTube API?
I have created a program where the user enters a YouTube channel name and it does a search and returns and displays YouTube channels with similar names based on their relevancy. Then the user picks what channel that they want and the program saves the ChannelID. Then I want to get a list of all of the channels videos so i can display a random video to the user from that channel. The issue is that the old method of using a channels "Uploads" playlist no longer works as I believe that channels don't have this playlist anymore by default. The code I am currently using to get the channels videos has its own issues.

```<code>   SearchListResponse response;
                var search = service.Search.List(repeatable);
                search.Type = "video";
                search.ChannelId = Session["ChannelID"].ToString();
                search.MaxResults = 500;

                do
                {
                    response = search.ExecuteAsync().Result;

                    foreach (SearchResult sr in response.Items)
                    {
                        videoIds.Add(sr.Id.VideoId);
                    }

                    search.PageToken = response.NextPageToken;

                } while (response.NextPageToken != "");
</code>```

The issue with this method is that it uses 100 quota per search but only returns 50 videos at a time. And if a user has 1000 videos it would take 20 searches aka 2000 quota (20% of daily quota) just to get the channels VideoID's.

I believe there are two ways to fix this:

From a single request, get a random video from the channel

OR

Get all VideoIDs from the channel and then pick a random one.

答:
The issue is that the old method of using a channels "Uploads" playlist no longer works as I believe that channels don't have this playlist anymore by default.

Not sure where you get that info, but, you can retrieve the videos from the "Uploads" playlist - see this answer for more info.

Basically, its changing one letter from the channelId and then you save another request for bring the "Uploads" playlist.

See this working sample I made for an guidance to get the uploaded videos from a channel - check that this channel UCyztLS0dr85vRqpKZHFfbmQ has 91 uploaded videos up to this date (11/02/2022), then, the nextPageToken is needed for get the next results.

The maximum value for maxresults is 50 - this applies for all requests as far as I read in the documentation.

Since you mention the random video picker, you could use the results from the playlistItems endpoint and pick one random video result (after making one single request) and - since it's random, you can't control which video is picked randomly.

If you follow this line of thinking and want to save more quota, then use this endpoint for get the latest uploaded videos from a given channel:

```<code>https://www.youtube.com/feeds/videos.xml?channel_id=<CHANNEL_ID>
</code>```

Example:

```<code>https://www.youtube.com/feeds/videos.xml?channel_id=UCypzG0nv9B65DwOLJ578rZQ
</code>```

N.B: if you want to get more videos, you have to make more requests - as far as I know, there is no request that brings you all info from a given channel - that's why you use the NextPageToken for results pagination.

Body:
I have created a program where the user enters a YouTube channel name and it does a search and returns and displays YouTube channels with similar names based on their relevancy. Then the user picks what channel that they want and the program saves the ChannelID. Then I want to get a list of all of the channels videos so i can display a random video to the user from that channel. The issue is that the old method of using a channels "Uploads" playlist no longer works as I believe that channels don't have this playlist anymore by default. The code I am currently using to get the channels videos has its own issues.

   SearchListResponse response;
                var search = service.Search.List(repeatable);
                search.Type = "video";
                search.ChannelId = Session["ChannelID"].ToString();
                search.MaxResults = 500;

                do
                {
                    response = search.ExecuteAsync().Result;

                    foreach (SearchResult sr in response.Items)
                    {
                        videoIds.Add(sr.Id.VideoId);
                    }

                    search.PageToken = response.NextPageToken;

                } while (response.NextPageToken != "");

The issue with this method is that it uses 100 quota per search but only returns 50 videos at a time. And if a user has 1000 videos it would take 20 searches aka 2000 quota (20% of daily quota) just to get the channels VideoID's.

I believe there are two ways to fix this:

From a single request, get a random video from the channel

OR

Get all VideoIDs from the channel and then pick a random one.

Body:
The issue is that the old method of using a channels "Uploads" playlist no longer works as I believe that channels don't have this playlist anymore by default.

Not sure where you get that info, but, you can retrieve the videos from the "Uploads" playlist - see this answer for more info.

Basically, its changing one letter from the channelId and then you save another request for bring the "Uploads" playlist.

See this working sample I made for an guidance to get the uploaded videos from a channel - check that this channel UCyztLS0dr85vRqpKZHFfbmQ has 91 uploaded videos up to this date (11/02/2022), then, the nextPageToken is needed for get the next results.

The maximum value for maxresults is 50 - this applies for all requests as far as I read in the documentation.

Since you mention the random video picker, you could use the results from the playlistItems endpoint and pick one random video result (after making one single request) and - since it's random, you can't control which video is picked randomly.

If you follow this line of thinking and want to save more quota, then use this endpoint for get the latest uploaded videos from a given channel:

https://www.youtube.com/feeds/videos.xml?channel_id=<CHANNEL_ID>

Example:

https://www.youtube.com/feeds/videos.xml?channel_id=UCypzG0nv9B65DwOLJ578rZQ

N.B: if you want to get more videos, you have to make more requests - as far as I know, there is no request that brings you all info from a given channel - that's why you use the NextPageToken for results pagination.


问:
Spotify's "player state" is available in the editor, but in a packaged app, it gets only "«constant ****kPSP»"
Here's a testing code:

```<code>tell application "Spotify"
    set playerState to player state as string
end tell
display dialog playerState
</code>```

Works fine from the AppleScript editor. However, when I export my script as an app, all I get is this:

Why is this happening?

答:
I wasn't able to comment adayzdone's answer yet here's an alternative:

```<code>if player state is playing or player state is paused then
</code>```

E.G

```<code>if application "Spotify" is running then

    tell application "Spotify"

        if player state is playing or player state is paused then

            set trackID to (get id of current track)

        end if

    end tell

end if
</code>```

This atleast worked on Catalina (10.15.7) when working on a Spotify-Applescript project of my own.

The source of the idea came from this thread.

Body:
Here's a testing code:

tell application "Spotify"
    set playerState to player state as string
end tell
display dialog playerState

Works fine from the AppleScript editor. However, when I export my script as an app, all I get is this:

Why is this happening?

Body:
I wasn't able to comment adayzdone's answer yet here's an alternative:

if player state is playing or player state is paused then

E.G

if application "Spotify" is running then

    tell application "Spotify"

        if player state is playing or player state is paused then

            set trackID to (get id of current track)

        end if

    end tell

end if

This atleast worked on Catalina (10.15.7) when working on a Spotify-Applescript project of my own.

The source of the idea came from this thread.


问:
Dynamic variable declaration. Is this even the right method?
A little new to JS so be gentle :)

I'm trying to create a program that holds 5000+ boolean values that dynamically change based on other vars.

const chars = "abcdefghijklmnopqrstuvwxyz0";
const charsC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
const maxNum = 48;
const maxTile = 6;
var tile1, tile2, tile3, tile4, tile5, tile6
// test vars
var tile4 = "A27"
var t4a27 = false

// this snippet will be in an interval loop
for (let i = 1; i <= maxTile; ++i) {
    for (let n = 0; n < chars.length; ++n) {
        for (let j = 1; j <= maxNum; ++j) {
            // this obviously doesnt work
            var t[i][`${chars[n]}`][j];
            // ^ ^ ^
            if (tile[i] == `${charsC[n]}${j}`) {
                t[i][h][j] = true;
                console.log(t4a27)
            } else {
                t[i][h][j] = false;
            }
        }
    }
}```

For clarification a better word than "tile" for the vars could be "sprite" rather because its a point on the sprite.

The basic concept is the tile vars are designed to output their current position as a string value e.g. "A27". Then this loop will take that information and scan each tile subset to be true/false. So if the sprite lower right quadrant is inside "A27" the output would be t4a27 = true

In practice I can do this with just a lot of code (over 20,000 lines) but I figured their has to be an easier way that requires far less code.

答:
This is probably not the right approach for your problem.

If you really need to store this amount of variables, it is probably best to put them in an object like so:

var tiles = {}

var tileName = 'abc'

// Dynamic setting:
tile[tileName] = true

// Dynamic reading:
console.log(tile[tileName])
```

I am wondering if you really want to store 5000 variables or if there is another way to calculate them at the time you need time, but that requires a bit more knowledge of the problem.

Body:
A little new to JS so be gentle :)

I'm trying to create a program that holds 5000+ boolean values that dynamically change based on other vars.

const chars = "abcdefghijklmnopqrstuvwxyz0";
const charsC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
const maxNum = 48;
const maxTile = 6;
var tile1, tile2, tile3, tile4, tile5, tile6
// test vars
var tile4 = "A27"
var t4a27 = false

// this snippet will be in an interval loop
for (let i = 1; i <= maxTile; ++i) {
    for (let n = 0; n < chars.length; ++n) {
        for (let j = 1; j <= maxNum; ++j) {
            // this obviously doesnt work
            var t[i][`${chars[n]}`][j];
            // ^ ^ ^
            if (tile[i] == `${charsC[n]}${j}`) {
                t[i][h][j] = true;
                console.log(t4a27)
            } else {
                t[i][h][j] = false;
            }
        }
    }
}

For clarification a better word than "tile" for the vars could be "sprite" rather because its a point on the sprite.

The basic concept is the tile vars are designed to output their current position as a string value e.g. "A27". Then this loop will take that information and scan each tile subset to be true/false. So if the sprite lower right quadrant is inside "A27" the output would be t4a27 = true

In practice I can do this with just a lot of code (over 20,000 lines) but I figured their has to be an easier way that requires far less code.

Body:
This is probably not the right approach for your problem.

If you really need to store this amount of variables, it is probably best to put them in an object like so:

var tiles = {}

var tileName = 'abc'

// Dynamic setting:
tile[tileName] = true

// Dynamic reading:
console.log(tile[tileName])

I am wondering if you really want to store 5000 variables or if there is another way to calculate them at the time you need time, but that requires a bit more knowledge of the problem.


问:
Swift UIApplication not in scope
I want to change isIdleTimerDisabled when a specific view appears. In SwiftUI I use
.onAppear { UIApplication.shared.isIdleTimerDisabled = true } .onDisappear { UIApplication.shared.isIdleTimerDisabled = false }
but even with import UIKit I get the warning "Cannot find 'UIApplication' in scope". How can I fix that? I didn't find a solution after searching for more than an hour.

答:
You should not need to import UIKit, it should work with SwiftUI.

The problem may be your target. Is the file used only on an iOS or iPadOS application target?

Or is it also used, for instance, in an extension, like ShareExtension, and so on?

If it is, you cannot access UIApplication within your code. If this code is shared between extensions and app, you should use conditional compilation to avoid this problem.

Title: Swift UIApplication not in scope


问:
Cross compile for .NET 4 and Silverlight 4 in VS2010 without duplicating files
We have a large number of projects within a solution mostly simple class libraries (which are later loaded through MEF) targetting .NET 4.0.

We would like to compile a large number of these for both .NET 4.0 and the Silverlight runtime without duplicating files.

Is there a way to create a new Silverlight class library and link the source files from the other projects so both the .NET 4.0 library and the Silverlight 4.0 library will be compiled?

I'm aware .NET 4.0 can load silverlight 4 assemblies, but I would like to compile both versions anyway instead of compiling everything for Silverlight.

Update:
I saw a solution once where some of the projects contained links to other files in other projects, so when you changed a file in one project it would be updated in the other one as well. This is what I mean.

A screenshot of the solution, the Vialis.Led.Interfaces project contains the original files, in the silverlight project I want to create links to these files.

答:
Microsoft recently released the Portable Library Tools:
http://msdn.microsoft.com/en-us/library/gg597391.aspx

I'll definitely have a look at these.


问:
How do you conditionally add a character string to certain values in a column?
I found that leading 0s had dropped from my data set at some point. Maybe someone had opened a CSV file and the leading 0s had fallen off or the data had been read in as an integer and the 0s had been removed. I'd been expecting all my ids to be 5 characters long and noticed an issue when some of them weren't.

TLDR: How do you conditionally add a string onto observations in a column?

答:
Thought I'd share how to do this in case anyone runs into similar issues. This is useful to add leading 0s back into a data frame where they may have been dropped (E.G. loaded in as an integer data type, someone opened a CSV file and the 0s dropped, for example). In this case, I expected all of my IDs to be 5 digits long, so corrected for the conditionally dropped 0s. This solution has an emphasis on the tidyverse.</p>
```<code>dataset <-
  dataset %>%
  mutate(id = as.character(id)) %>%
  mutate(id = case_when(nchar(id) == 4 ~ paste("0", id, sep =""),
                         nchar(id) == 5~ id))

</code>```

Body:
Thought I'd share how to do this in case anyone runs into similar issues. This is useful to add leading 0s back into a data frame where they may have been dropped (E.G. loaded in as an integer data type, someone opened a CSV file and the 0s dropped, for example). In this case, I expected all of my IDs to be 5 digits long, so corrected for the conditionally dropped 0s. This solution has an emphasis on the tidyverse.

dataset <-
  dataset %>%
  mutate(id = as.character(id)) %>%
  mutate(id = case_when(nchar(id) == 4 ~ paste("0", id, sep =""),
                         nchar(id) == 5~ id))


问:
How to specify a data frame and column in a function containing a `for` loop?
I am trying to write a function that returns all the observations in a specified data frame and column that have a number of letters < 5. For example if an observation was dogs it would be returned, but if another observation was store it would not be returned.

This is the code I have written:

```<code>count_length <- function(dataset, column_named){

  for (i in dataset$column_named)
    if (nchar(dataset$column_named[i] < 5)){
      paste("problem with ",i)
    }

}

count_length(dataset = df,
             column_named = pets)

</code>```

The following error is returning:

```<code>Warning message:
Unknown or uninitialised column: `column_named`.

</code>```

Does anyone know how to fix this and why it is happening? Is it related to the use of $ I wonder?

答:
You're right. It's indeed related to the use of $, as it is a function and cannot evaluate variables inside it.

You can try dataset$[column_named] for a dataframe or dataset$[[column_named]] for a vector

Longer explanation in this answer

Body:
I am trying to write a function that returns all the observations in a specified data frame and column that have a number of letters < 5. For example if an observation was dogs it would be returned, but if another observation was store it would not be returned.

This is the code I have written:

count_length <- function(dataset, column_named){

  for (i in dataset$column_named)
    if (nchar(dataset$column_named[i] < 5)){
      paste("problem with ",i)
    }

}

count_length(dataset = df,
             column_named = pets)

The following error is returning:

Warning message:
Unknown or uninitialised column: `column_named`.

Does anyone know how to fix this and why it is happening? Is it related to the use of $ I wonder?