问:
Access an element while splitting a string
I want to retrieve a last element of the array. Array is a splitted string retrieved as follows:

my @net_info = split(/\//,'10.0.0.2/8');

I am interested only in the last element of the array, that is the CIDR value in one line. I was thinking of:

    my $cidr = ${split(/\//,'10.0.0.2/8')}[-1];

but that resulted in:

Can't use string ("2") as an ARRAY ref while "strict refs" in use at...

Is it possible to get last element directly? What is the right syntax to achieve it?

答:
Looking at the documentation for split() we see this:

Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context

So we can get the list in an array:

```<code>my @net_info = split(/\//,'10.0.0.2/8');
</code>```

And then get the last element of that array:

```<code>my $cidr = $net_info[-1];
</code>```

But you can do it in one line of code by using a list slice. The syntax for a list slice is:

```<code>( LIST )[ INDEX ]
</code>```

You were getting a little lost and using this:

```<code>${ LIST }[ INDEX ]
</code>```

So the correct syntax for your problem is:

```<code>my $cidr = ( split(/\//,'10.0.0.2/8') )[-1];
</code>```

In addition, your code might be a little easier to understand if you used a different delimiter for the regex that is the first argument to split() - thereby getting rid of the need to escape the slash.

```<code>my $cidr = ( split(m[/],'10.0.0.2/8') )[-1];
</code>```

Update: Given that a netmask only ever contains a single slash, it might be easier to write something like:

```<code>my ($ip, $cidr) = split(m[/], '10.0.0.2/8');
</code>```

Or (using undef to drop the first value returned by split():

```<code>my (undef, $cidr) = split(m[/], '10.0.0.2/8');
</code>```

Update 2: And to explain what was going in your original code. You were inadvertently using this construct:

```<code>${ ARRAYREF }[ INDEX ]
</code>```

Which is the general version of one way to get the value of an element of an array when you only have a reference to the array (more commonly, of course, you'd use ARRAYREF->[ INDEX ]).

As the expression within ${ ... } is expected to evaluate to an array reference and as array references are always scalar values, Perl evaluates the expression in scalar context. And as we see from the documentation extract above, in scalar context, split() returns the number of elements in the list - which will be 2. And "2" isn't an array reference, so you get the error that you've seen.

Body:
Looking at the documentation for split() we see this:

Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context

So we can get the list in an array:

my @net_info = split(/\//,'10.0.0.2/8');

And then get the last element of that array:

my $cidr = $net_info[-1];

But you can do it in one line of code by using a list slice. The syntax for a list slice is:

( LIST )[ INDEX ]

You were getting a little lost and using this:

${ LIST }[ INDEX ]

So the correct syntax for your problem is:

my $cidr = ( split(/\//,'10.0.0.2/8') )[-1];

In addition, your code might be a little easier to understand if you used a different delimiter for the regex that is the first argument to split() - thereby getting rid of the need to escape the slash.

my $cidr = ( split(m[/],'10.0.0.2/8') )[-1];

Update: Given that a netmask only ever contains a single slash, it might be easier to write something like:

my ($ip, $cidr) = split(m[/], '10.0.0.2/8');

Or (using undef to drop the first value returned by split():

my (undef, $cidr) = split(m[/], '10.0.0.2/8');

Update 2: And to explain what was going in your original code. You were inadvertently using this construct:

${ ARRAYREF }[ INDEX ]

Which is the general version of one way to get the value of an element of an array when you only have a reference to the array (more commonly, of course, you'd use ARRAYREF->[ INDEX ]).

As the expression within ${ ... } is expected to evaluate to an array reference and as array references are always scalar values, Perl evaluates the expression in scalar context. And as we see from the documentation extract above, in scalar context, split() returns the number of elements in the list - which will be 2. And "2" isn't an array reference, so you get the error that you've seen.


来源: stackexchange

问:
How to get client IP address in Azure Functions C#?
I'm writing a function in C# using Azure Functions and need to get the ip address of the client that called the function, is this possible?</p>

答:
Now that Azure functions get an HttpRequest parameter, and they're behind a load balancer, this function to get the IP address works for me:

```<code>private static string GetIpFromRequestHeaders(HttpRequest request)
{
      return (request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "").Split(new char[] { ':' }).FirstOrDefault();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Now that Azure functions get an HttpRequest parameter, and they're behind a load balancer, this function to get the IP address works for me:

private static string GetIpFromRequestHeaders(HttpRequest request)
{
      return (request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "").Split(new char[] { ':' }).FirstOrDefault();
}

ContentLicense: CC BY-SA 4.0


问:
Set permissions for different namespaces in Azure DevOps using Rest API
How can I use RestAPI to set permissions for Build definitions, Release definitions, git repo and team securities? When I was using TFS, I was able to do this using Tfsssecurity.exe tool.

Edited.
For example, I am trying to modify the project permissions of Contributors group. like Allow Contributors to rename team project etc.

enter image description here

答:
Are you looking for the Security API page?
You probably need to manage group membership using Graph API.

The Get started page lists the libraries you can use and how to authenticate.


问:
How to iterate on results inside then() and call other chained then() inside the loop
I cannot find any documentation or example in typescript  that illustrates how to nest then() inside a loop which is inside a then().

I have the following chained then() functions that work perfectly.

but i need to make the functions 1 to 3 run n number of times based on an array property of the process object after it has been returned from the _promptUploadDialog

```<code>    .then(process => this._promptUploadDialog(process))
        .then(process => this._function1(process))
        .then(process => this._function2(process))
        .then(process => this._function3(process))
</code>```

needs to become something like this:

```<code> .then(process => this._promptUploadDialog(process)
     process.array1.forEach(function (value) {
        process.currentobject = value;
        this._function1(process))
            .then(process => this._function2(process))
            .then(process => this._function3(process))
     });
)
</code>```

Tried

```<code>return Promise.resolve<UploadDataProcess>({
            uploadResponse: undefined,
            arrayProp: [1,2,3]
        })
            .then(process => this._promptUploadDialog(process))
            .then(process =>
                process.arrayProp.forEach((value) => {
                    this._function1(process)
                        .then(process => this._function2(process))
                        .then(process => this._function3(process));
                    })
            );
</code>```

But I am getting a compile error:

TS2322    Type 'Promise' is not assignable to type 'Promise'.

答:
When you use the { ... } syntax for a lambda function definition, it does not return the last instruction (as opposed to the (arg) => statement which returns the value of statement).

So, here you see you have a problem with void being returned by the last Promise instead of your data type UploadDataProcess. That's because you miss the return keyword. Just add it and it will be ok:

```<code>return Promise.resolve<UploadDataProcess>({
        uploadResponse: undefined,
        arrayProp: [1,2,3]
    })
        .then(process => this._promptUploadDialog(process))
        .then(process =>
            process.arrayProp.forEach((value) => {
                return /* <-- HERE */ this._function1(process)
                    .then(process => this._function2(process))
                    .then(process => { this._function3(process));
                                       return process; /* <-- and return process at the end if it's your object */ }
                })
        );
</code>```

Body:
I cannot find any documentation or example in typescript  that illustrates how to nest then() inside a loop which is inside a then().

I have the following chained then() functions that work perfectly.

but i need to make the functions 1 to 3 run n number of times based on an array property of the process object after it has been returned from the _promptUploadDialog

    .then(process => this._promptUploadDialog(process))
        .then(process => this._function1(process))
        .then(process => this._function2(process))
        .then(process => this._function3(process))

needs to become something like this:

 .then(process => this._promptUploadDialog(process)
     process.array1.forEach(function (value) {
        process.currentobject = value;
        this._function1(process))
            .then(process => this._function2(process))
            .then(process => this._function3(process))
     });
)

Tried

return Promise.resolve<UploadDataProcess>({
            uploadResponse: undefined,
            arrayProp: [1,2,3]
        })
            .then(process => this._promptUploadDialog(process))
            .then(process =>
                process.arrayProp.forEach((value) => {
                    this._function1(process)
                        .then(process => this._function2(process))
                        .then(process => this._function3(process));
                    })
            );

But I am getting a compile error:

TS2322    Type 'Promise' is not assignable to type 'Promise'.

Body:
When you use the { ... } syntax for a lambda function definition, it does not return the last instruction (as opposed to the (arg) => statement which returns the value of statement).

So, here you see you have a problem with void being returned by the last Promise instead of your data type UploadDataProcess. That's because you miss the return keyword. Just add it and it will be ok:

return Promise.resolve<UploadDataProcess>({
        uploadResponse: undefined,
        arrayProp: [1,2,3]
    })
        .then(process => this._promptUploadDialog(process))
        .then(process =>
            process.arrayProp.forEach((value) => {
                return /* <-- HERE */ this._function1(process)
                    .then(process => this._function2(process))
                    .then(process => { this._function3(process));
                                       return process; /* <-- and return process at the end if it's your object */ }
                })
        );


问:
How to get Rails and all requirements running to use React?
Iam a novice in rails and trying to write my first React frontend. I have read enough to know that there are different methods to use React with rails. I decided to split frontend and backend, and use rails in API mode. I cannot find good sources explaining what I need on my server to get rails and react going, and why. I read so far about npm, node.js, Heroku and so on, but i lack the knowledge to decide what to pick and i dont understand the interactions yet.
Does someone know a good tutorial, some sources or keywords to point me to a direction?</p>

答:
If you want to use Rails just in API mode with React on frontend then you can separate those apps completely.

I.e. use Rails/Puma server for API and have a separate server (Nginx/Apache/Node.js) to serve the frontend React app and other static assets.


问:
Python module has no attribute while the attribute exists
Taking help from here, I was writing my own package. I have a folder filter which contains __init__.py (completely empty) and pca.py. pca.py has a class pca and that class has a method performPCA which takes two arguments. Then, I have this code:

```<code>from filter import pca
....
pca.performPCA(x,2)
</code>```

When I run this, I'm getting an error

```<code>AttributeError: module 'filter.pca' has no attribute 'performPCA'
</code>```

I know this question has an answer here, but I have everything that answer asks (the only difference is that my __init__.py is empty, which I think is totally fine). Please tell me where am I wrong. Thanks!

test.py goes as:

```<code>from filter import pca
print(pca)
import pandas as pd

x=pd.read_csv('Assignment-DS_gene_data.csv')
meta=pd.read_csv('Assignment-DS_Meta_data_sheet_.csv')
x.rename(columns={'Unnamed: 0':'col1'}, inplace=True )
del x['symbol']
del x['col1']
p=pca.pca2
#print(p)
xNew=p.performPCA(x,2)
</code>```

pca.py goes as:

```<code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D

class pca2:
    #Choose this method if only projected data is required
    def perfromPCA(self,data,nComp):
        pcaModel = PCA(n_components=nComp)
        principalComponents = pcaModel.fit_transform(data)
        colNames = []
        for i in range(1,nComp+1):
            colNames.append('PC '+str(i))
        principalDf = pd.DataFrame(data = principalComponents
             , columns = colNames)
        return principalDf

    #Choose this method if plot and projected data both are required
    #For this, nComp can either be 2 or 3
    def performPCAPlot(self,data,nComp,metaData,column):
        principalDf = performPCA(data,nComp)
        if nComp == 2:
            plt.scatter(principalDf,data=metaData['column'])
            #plt.xlabel('PC1')
            #plt.ylabel('PC2')
            plt.show()
        else:
            fig = plt.figure()
            #to do
        return principalDf
</code>```

答:
Since you have another class inside pca.py, you should try creating an object first and then accessing it.

from filter import pca
....
p = pca()
p.performPCA(x,2)
```

Body:
Taking help from here, I was writing my own package. I have a folder filter which contains __init__.py (completely empty) and pca.py. pca.py has a class pca and that class has a method performPCA which takes two arguments. Then, I have this code:

from filter import pca
....
pca.performPCA(x,2)

When I run this, I'm getting an error

AttributeError: module 'filter.pca' has no attribute 'performPCA'

I know this question has an answer here, but I have everything that answer asks (the only difference is that my __init__.py is empty, which I think is totally fine). Please tell me where am I wrong. Thanks!

test.py goes as:

from filter import pca
print(pca)
import pandas as pd

x=pd.read_csv('Assignment-DS_gene_data.csv')
meta=pd.read_csv('Assignment-DS_Meta_data_sheet_.csv')
x.rename(columns={'Unnamed: 0':'col1'}, inplace=True )
del x['symbol']
del x['col1']
p=pca.pca2
#print(p)
xNew=p.performPCA(x,2)

pca.py goes as:

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D

class pca2:
    #Choose this method if only projected data is required
    def perfromPCA(self,data,nComp):
        pcaModel = PCA(n_components=nComp)
        principalComponents = pcaModel.fit_transform(data)
        colNames = []
        for i in range(1,nComp+1):
            colNames.append('PC '+str(i))
        principalDf = pd.DataFrame(data = principalComponents
             , columns = colNames)
        return principalDf

    #Choose this method if plot and projected data both are required
    #For this, nComp can either be 2 or 3
    def performPCAPlot(self,data,nComp,metaData,column):
        principalDf = performPCA(data,nComp)
        if nComp == 2:
            plt.scatter(principalDf,data=metaData['column'])
            #plt.xlabel('PC1')
            #plt.ylabel('PC2')
            plt.show()
        else:
            fig = plt.figure()
            #to do
        return principalDf


问:
Downloading large files from artifactory remote repo giving error - unexpected EOF
I have an artifactory in Jfrog, where the vendor keeps the updated binaries. I am supposed to download the binaries using a build task (i.e. Artifactory Generic Download) from Azure Pipelines. While downloading the binaries from that artifactory remote repo some large files(i.e. more that 800 MB in size) are not getting downloaded and throwing an error "unexpected EoF"

I thought the issue was because of slow internet, so I had tried to download those artifacts with fastest internet connection available, but it did not help.

The output I got was this

```<code>##[debug]fileSpec={
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\Abhijit\VSTS_Agent\_work\2\s\\"
        }
    ]
}
Using file spec:
{
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\\Abhijit\\VSTS_Agent\\_work\\2\\s\\"
        }
    ]
}
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param username = ***
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param password = ***
##[debug]failNoOp=true
##[debug]buildName=Test_Project_KT-CI (1)
##[debug]buildNumber=309
[Info] Searching items to download...
[Info] [Thread 2] Downloading Dependencies/SQLEXPRADV_x64_ENU.exe
[Info] [Thread 2] [0]: 206 Partial content...
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [1]: Attempt 0 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [2]: Attempt 0 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Warn] [Thread 2] [1]: Attempt 1 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [2]: Attempt 1 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [1]: Attempt 2 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [2]: Attempt 2 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [1]: Attempt 3 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x799657]
</code>```

expected Output

```<code>##[debug]fileSpec={
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\Abhijit\VSTS_Agent\_work\2\s\\"
        }
    ]
}
Using file spec:
{
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\\Abhijit\\VSTS_Agent\\_work\\2\\s\\"
        }
    ]
}
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param username = ***
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param password = ***
##[debug]failNoOp=true
##[debug]buildName=Test_Project_KT-CI (1)
##[debug]buildNumber=309
[Info] Searching items to download...
[Info] [Thread 2] Downloading Dependencies/SQLEXPRADV_x64_ENU.exe
[Info] [Thread 2] [0]: 206 Partial content...
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Info] download done...
```
```

答:
According to your output file, not only unexpected EOF, you also got another error message:

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x799657]
</code>```

This is the error which about Go, and the task you used is written with this Go language.  According to their github repos, you can check what the task code is. So this error message should caused by their task code, not you.

In addition, There also have similar error under their github issue report. You can check it. Their team are updating to change the code which cause this error and their latest release will include this change.

Body:
I have an artifactory in Jfrog, where the vendor keeps the updated binaries. I am supposed to download the binaries using a build task (i.e. Artifactory Generic Download) from Azure Pipelines. While downloading the binaries from that artifactory remote repo some large files(i.e. more that 800 MB in size) are not getting downloaded and throwing an error "unexpected EoF"

I thought the issue was because of slow internet, so I had tried to download those artifacts with fastest internet connection available, but it did not help.

The output I got was this

##[debug]fileSpec={
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\Abhijit\VSTS_Agent\_work\2\s\\"
        }
    ]
}
Using file spec:
{
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\\Abhijit\\VSTS_Agent\\_work\\2\\s\\"
        }
    ]
}
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param username = ***
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param password = ***
##[debug]failNoOp=true
##[debug]buildName=Test_Project_KT-CI (1)
##[debug]buildNumber=309
[Info] Searching items to download...
[Info] [Thread 2] Downloading Dependencies/SQLEXPRADV_x64_ENU.exe
[Info] [Thread 2] [0]: 206 Partial content...
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [1]: Attempt 0 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [2]: Attempt 0 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Warn] [Thread 2] [1]: Attempt 1 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [2]: Attempt 1 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [1]: Attempt 2 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Warn] [Thread 2] [2]: Attempt 2 - Failure occurred while downloading part 2 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
[Warn] [Thread 2] [1]: Attempt 3 - Failure occurred while downloading part 1 of https://artifacts.test.com/artifactory/Dependencies/SQLEXPRADV_x64_ENU.exe - unexpected EOF
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x799657]

expected Output

##[debug]fileSpec={
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\Abhijit\VSTS_Agent\_work\2\s\\"
        }
    ]
}
Using file spec:
{
    "files": [
        {
            "pattern": "Dependencies/SQLEXPRADV_x64_ENU.exe",
            "target": "D:\\Abhijit\\VSTS_Agent\\_work\\2\\s\\"
        }
    ]
}
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param username = ***
##[debug]0a364c9c-b6a0-43eb-8b47-d6a58c68b016 auth param password = ***
##[debug]failNoOp=true
##[debug]buildName=Test_Project_KT-CI (1)
##[debug]buildNumber=309
[Info] Searching items to download...
[Info] [Thread 2] Downloading Dependencies/SQLEXPRADV_x64_ENU.exe
[Info] [Thread 2] [0]: 206 Partial content...
[Info] [Thread 2] [1]: 206 Partial Content...
[Info] [Thread 2] [2]: 206 Partial Content...
[Info] download done...
```

Body:
According to your output file, not only unexpected EOF, you also got another error message:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x799657]

This is the error which about Go, and the task you used is written with this Go language.  According to their github repos, you can check what the task code is. So this error message should caused by their task code, not you.

In addition, There also have similar error under their github issue report. You can check it. Their team are updating to change the code which cause this error and their latest release will include this change.


问:
How to fix css font style to show properly in all browsers?
I currently use this code in style.css file:

```<code>@font-face {
    font-family: Frutiger;
    src: url('fonts/frutiger.ttf');
}
</code>```

It works fine in

Chrome

Firefox

but it doesn't work in

Internet Explorer

I tried to add font in oet open embedded type with this line: line src: url('fonts/frutiger.oet'); to my code but  then it doesnt want to work in chrome either.

I don't know how to properly set fonts to be displayed in all browsers without any problems. Kindly let me know, my site url is www.virmodrosti.com

答:
The newer bulletprof font syntax is:

```<code>@font-face {
    font-family: 'my-font';
    font-display: swap;
    src: url('/fonts/my-font.woff2') format('woff2'), /* Super Modern Browsers */
         url('/fonts/my-font.woff') format('woff'); /* Pretty Modern Browsers */
}
</code>```

The older bulletproof font syntax was:

```<code>@font-face {
  font-family: 'my-font';
  src: url('/fonts/my-font.eot'); /* IE9 Compat Modes */
  src: url('/fonts/my-font.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('/fonts/my-font.woff2') format('woff2'), /* Super Modern Browsers */
       url('/fonts/my-font.woff') format('woff'), /* Pretty Modern Browsers */
       url('/fonts/my-font.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('/fonts/my-font.svg#svgMyFont') format('svg'); /* Legacy iOS */
}
</code>```

Body:
I currently use this code in style.css file:

@font-face {
    font-family: Frutiger;
    src: url('fonts/frutiger.ttf');
}

It works fine in

Chrome

Firefox

but it doesn't work in

Internet Explorer

I tried to add font in oet open embedded type with this line: line src: url('fonts/frutiger.oet'); to my code but  then it doesnt want to work in chrome either.

I don't know how to properly set fonts to be displayed in all browsers without any problems. Kindly let me know, my site url is www.virmodrosti.com

Body:
The newer bulletprof font syntax is:

@font-face {
    font-family: 'my-font';
    font-display: swap;
    src: url('/fonts/my-font.woff2') format('woff2'), /* Super Modern Browsers */
         url('/fonts/my-font.woff') format('woff'); /* Pretty Modern Browsers */
}

The older bulletproof font syntax was:

@font-face {
  font-family: 'my-font';
  src: url('/fonts/my-font.eot'); /* IE9 Compat Modes */
  src: url('/fonts/my-font.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('/fonts/my-font.woff2') format('woff2'), /* Super Modern Browsers */
       url('/fonts/my-font.woff') format('woff'), /* Pretty Modern Browsers */
       url('/fonts/my-font.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('/fonts/my-font.svg#svgMyFont') format('svg'); /* Legacy iOS */
}


问:
Getting Error while trying to access nextcloud through sso
I have problems with SAMLRequest not being authenticated by nextcloud

```<code><samlp:Response ID="_7b0ef094-ae04-4d2c-a7d1-e9d5e698c278"
                Version="2.0"
                IssueInstant="2019-05-28T12:19:07.704Z"
                Destination="https://192.168.1.136/index.php/apps/user_saml/saml/acs"
                Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
                xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://WindowsServer19.server.net/adfs/services/trust</Issuer>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status>
  <Assertion ID="_3acf9e24-2f34-47bf-82fb-97f6d11ab652"
             IssueInstant="2019-05-28T12:19:07.703Z"
             Version="2.0"
             xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <Issuer>http://WindowsServer19.server.net/adfs/services/trust</Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <ds:Reference URI="#_3acf9e24-2f34-47bf-82fb-97f6d11ab652">
          <ds:Transforms>
            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></ds:Transforms>
          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
          <ds:DigestValue>0frZvK2y9o8WTDfpB3rBlK+82W4=</ds:DigestValue>
        </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>
s4NAgv4ucV5xM6Ig+GsNunpNo5whkJljUec9KtNh00UbRZJ3q2KdzNQ3ZxhpvYudTDqlgzwnenaPmZIcpmgzuqaIiHTStBWUgafZDljZ4/WnQ8SRslMBgRNtuh3NU8qh+0Hgr3k+ngZc1YvlACy+sPeoBxZoFKTC+cwXVeezdlTnPW+IbZ2T1xeLmjz42oelqrnGbsnu6btNgTHzij302YCsbnlKe6wAEw9CvjFCtWPW1dV9iL6FLYkJfPporG9D7FkW+nZoYa8SHns8VRFM97sBKSBcX/csneJiX+7b+hZttw+MPsXmXBgXiU8D0boRjqKByv51fhlhLpKl3HRZZg==
</ds:SignatureValue>
      <KeyInfo
      xmlns="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
          <ds:X509Certificate>
MIIC8DCCAdigAwIBAgIQMCGuwW//8oZPRuZYDplwVTANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylBREZTIFNpZ25pbmcgLSBXaW5kb3dzU2VydmVyMTkuc2VydmVyLm5ldDAeFw0xOTA1MjMwMTM1MjJaFw0yMDA1MjIwMTM1MjJaMDQxMjAwBgNVBAMTKUFERlMgU2lnbmluZyAtIFdpbmRvd3NTZXJ2ZXIxOS5zZXJ2ZXIubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7VQR25k7qgmSYMhh40HYEdaki0Itff0QfjpABaNLJJYLB51ikpK/PctqXDy2StJqo4ai3wcrM2xjcLKm7pOGpNYYF2Brdf8ae3i+gjh3Ej6vDYWs/YWve2yZarBkUxTSFlCLsUACIu5nuo7JmVU9ptPcmcKqEZamU1U04qt6RJzxKvLOdFa4nT2Nx1jM8lGyo+x4oJ0agaSORURdQQVSfIJMUuEXWufp0qeCRt3KrQHf6NzJYGvDCdF6bu5lsrXma+nEIxvs88qg7P15ntA+HTdxut3M9vLm+P2nvZMfxU+BKScBWpBfKDAkABF3PibCjnlr0pJ0ZUwPGsya180NAQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAl1f4+rQ3jG+8TfTNtnT/VX8DgXLCop8yrypU/i5AHeS9Xwmi2vqPwEkJQLd84ictIVU43NxtQPvj9RT6IjrwSaDqQcwVOcL0ectlp4cy9DsJsGfMPc3LczX6n07dRweCibRT7+aOGUNuBAi5Qwa63e68DEaHbg+hZkAd0G5gfVLvuKLWcGNUhdGAyHSUCZEXKNeWAVcpeL0JQeEAdPoTR1LA78RUW5PH/VMiEwXrB22T535m3z6YoPyrrWQnDBcXWJ5rIHtJPT58sB3VVHnV2VjNSBH+hS5fFOQ8pABmW+Z5ajpfy2DxdhtTaLt0hXuLpFon7b7/5XJI8ut57yG0E
</ds:X509Certificate>
        </ds:X509Data>
        </KeyInfo>
    </ds:Signature>
    <Subject>
      <NameID>Administrator</NameID>
      <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <SubjectConfirmationData NotOnOrAfter="2019-05-28T12:24:07.704Z"
                                 Recipient="https://192.168.1.136/index.php/apps/user_saml/saml/acs" />
      </SubjectConfirmation>
    </Subject>
    <Conditions NotBefore="2019-05-28T12:19:07.702Z"
                NotOnOrAfter="2019-05-28T13:19:07.702Z">
      <AudienceRestriction>
        <Audience>https://192.168.1.136/index.php/apps/user_saml/saml/metadata</Audience>
      </AudienceRestriction>
    </Conditions>
    <AttributeStatement>
      <Attribute Name="http://schemas.microsoft.com/2012/12/certificatecontext/field/issuername">
        <AttributeValue>Aleksandar</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname">
        <AttributeValue>Andric</AttributeValue>
      </Attribute>
      <Attribute Name="sAMAccountName">
        <AttributeValue>Administrator</AttributeValue>
      </Attribute>
    </AttributeStatement>
    <AuthnStatement AuthnInstant="2019-05-28T12:19:07.675Z"
                    SessionIndex="_3acf9e24-2f34-47bf-82fb-97f6d11ab652">
      <AuthnContext>
        <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
      </AuthnContext>
    </AuthnStatement>
  </Assertion>
</samlp:Response>
</code>```

I am using ADFS as Identity provider and nextcloud as Service Provider, and I can't make them work for 2 weeks. When i click on the sso & saml button on nextcloud http://prntscr.com/nuevag this error occurs and after deleting SAMLRequest and RelayState query parameters and deleting cookies login page is shown http://prntscr.com/nuez9s and after signing in 'Account not provisioned' error appears http://prntscr.com/nuf01w. Log files show http://prntscr.com/nuf0qj but in ADFS, URL is set with https:// http://prntscr.com/nuf11w. Do you have any idea how to make this work. Thank you very much!

答:
You need to trace the SAML request. Either ADFS does not know the Issuer of the SAML AuthnRequest or it may not be able to verify the signature of SAML AuthnRequest (if it was digitally signed).

IdP initiated SSO as shown in https://prnt.sc/nuez9s is a totally different flow, where the IdP only sends a SAML response, there is no SAML AuthnRequest.

ADFS event log would actually show (also sometimes in a somewhat cryptic way) why the SAML AuthnRequest could not be handled.

Body:
I have problems with SAMLRequest not being authenticated by nextcloud

<samlp:Response ID="_7b0ef094-ae04-4d2c-a7d1-e9d5e698c278"
                Version="2.0"
                IssueInstant="2019-05-28T12:19:07.704Z"
                Destination="https://192.168.1.136/index.php/apps/user_saml/saml/acs"
                Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
                xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://WindowsServer19.server.net/adfs/services/trust</Issuer>
  <samlp:Status>
    <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" /></samlp:Status>
  <Assertion ID="_3acf9e24-2f34-47bf-82fb-97f6d11ab652"
             IssueInstant="2019-05-28T12:19:07.703Z"
             Version="2.0"
             xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <Issuer>http://WindowsServer19.server.net/adfs/services/trust</Issuer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <ds:Reference URI="#_3acf9e24-2f34-47bf-82fb-97f6d11ab652">
          <ds:Transforms>
            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></ds:Transforms>
          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
          <ds:DigestValue>0frZvK2y9o8WTDfpB3rBlK+82W4=</ds:DigestValue>
        </ds:Reference>
      </ds:SignedInfo>
      <ds:SignatureValue>
s4NAgv4ucV5xM6Ig+GsNunpNo5whkJljUec9KtNh00UbRZJ3q2KdzNQ3ZxhpvYudTDqlgzwnenaPmZIcpmgzuqaIiHTStBWUgafZDljZ4/WnQ8SRslMBgRNtuh3NU8qh+0Hgr3k+ngZc1YvlACy+sPeoBxZoFKTC+cwXVeezdlTnPW+IbZ2T1xeLmjz42oelqrnGbsnu6btNgTHzij302YCsbnlKe6wAEw9CvjFCtWPW1dV9iL6FLYkJfPporG9D7FkW+nZoYa8SHns8VRFM97sBKSBcX/csneJiX+7b+hZttw+MPsXmXBgXiU8D0boRjqKByv51fhlhLpKl3HRZZg==
</ds:SignatureValue>
      <KeyInfo
      xmlns="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
          <ds:X509Certificate>
MIIC8DCCAdigAwIBAgIQMCGuwW//8oZPRuZYDplwVTANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylBREZTIFNpZ25pbmcgLSBXaW5kb3dzU2VydmVyMTkuc2VydmVyLm5ldDAeFw0xOTA1MjMwMTM1MjJaFw0yMDA1MjIwMTM1MjJaMDQxMjAwBgNVBAMTKUFERlMgU2lnbmluZyAtIFdpbmRvd3NTZXJ2ZXIxOS5zZXJ2ZXIubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7VQR25k7qgmSYMhh40HYEdaki0Itff0QfjpABaNLJJYLB51ikpK/PctqXDy2StJqo4ai3wcrM2xjcLKm7pOGpNYYF2Brdf8ae3i+gjh3Ej6vDYWs/YWve2yZarBkUxTSFlCLsUACIu5nuo7JmVU9ptPcmcKqEZamU1U04qt6RJzxKvLOdFa4nT2Nx1jM8lGyo+x4oJ0agaSORURdQQVSfIJMUuEXWufp0qeCRt3KrQHf6NzJYGvDCdF6bu5lsrXma+nEIxvs88qg7P15ntA+HTdxut3M9vLm+P2nvZMfxU+BKScBWpBfKDAkABF3PibCjnlr0pJ0ZUwPGsya180NAQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAl1f4+rQ3jG+8TfTNtnT/VX8DgXLCop8yrypU/i5AHeS9Xwmi2vqPwEkJQLd84ictIVU43NxtQPvj9RT6IjrwSaDqQcwVOcL0ectlp4cy9DsJsGfMPc3LczX6n07dRweCibRT7+aOGUNuBAi5Qwa63e68DEaHbg+hZkAd0G5gfVLvuKLWcGNUhdGAyHSUCZEXKNeWAVcpeL0JQeEAdPoTR1LA78RUW5PH/VMiEwXrB22T535m3z6YoPyrrWQnDBcXWJ5rIHtJPT58sB3VVHnV2VjNSBH+hS5fFOQ8pABmW+Z5ajpfy2DxdhtTaLt0hXuLpFon7b7/5XJI8ut57yG0E
</ds:X509Certificate>
        </ds:X509Data>
        </KeyInfo>
    </ds:Signature>
    <Subject>
      <NameID>Administrator</NameID>
      <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <SubjectConfirmationData NotOnOrAfter="2019-05-28T12:24:07.704Z"
                                 Recipient="https://192.168.1.136/index.php/apps/user_saml/saml/acs" />
      </SubjectConfirmation>
    </Subject>
    <Conditions NotBefore="2019-05-28T12:19:07.702Z"
                NotOnOrAfter="2019-05-28T13:19:07.702Z">
      <AudienceRestriction>
        <Audience>https://192.168.1.136/index.php/apps/user_saml/saml/metadata</Audience>
      </AudienceRestriction>
    </Conditions>
    <AttributeStatement>
      <Attribute Name="http://schemas.microsoft.com/2012/12/certificatecontext/field/issuername">
        <AttributeValue>Aleksandar</AttributeValue>
      </Attribute>
      <Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname">
        <AttributeValue>Andric</AttributeValue>
      </Attribute>
      <Attribute Name="sAMAccountName">
        <AttributeValue>Administrator</AttributeValue>
      </Attribute>
    </AttributeStatement>
    <AuthnStatement AuthnInstant="2019-05-28T12:19:07.675Z"
                    SessionIndex="_3acf9e24-2f34-47bf-82fb-97f6d11ab652">
      <AuthnContext>
        <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
      </AuthnContext>
    </AuthnStatement>
  </Assertion>
</samlp:Response>

I am using ADFS as Identity provider and nextcloud as Service Provider, and I can't make them work for 2 weeks. When i click on the sso & saml button on nextcloud http://prntscr.com/nuevag this error occurs and after deleting SAMLRequest and RelayState query parameters and deleting cookies login page is shown http://prntscr.com/nuez9s and after signing in 'Account not provisioned' error appears http://prntscr.com/nuf01w. Log files show http://prntscr.com/nuf0qj but in ADFS, URL is set with https:// http://prntscr.com/nuf11w. Do you have any idea how to make this work. Thank you very much!


问:
Unable to find gif image by Xpath/classname/cssSelector using selenium webdriver java
I am trying to locate image using Selenium webdriver but unable to locate it by Xpath/cssSelector

I have tried cssSelector and xpath but not working.

```<code><img alt="" class="i-amphtml-fill-content i-amphtml-replaced-content" decoding="async" src="https://tpc.googlesyndication.com/simgad/303052068860032968">
</code>```

By cssSelector -->

```<code>WebElement elementOut = driver.findElement(By.cssSelector(".i-amphtml-fill-content.i-amphtml-replaced-content"));
</code>```

By Xpath -->

```<code>WebElement elementOut = driver.findElement(By.xpath("//*[@id='aw0']/amp-img/img"));
</code>```

I need to locate the image.

Snapshot of the page source:

答:
To click() on the image, as the the desired element is within an  so you have to:

Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.

Induce WebDriverWait for the desired elementToBeClickable.

You can use either of the following Locator Strategies:

cssSelector:

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id$='com/Web/News24/Homepage_20'][name^='google_ads_iframe_'][title='3rd party ad content']")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("img.i-amphtml-fill-content.i-amphtml-replaced-content[src^='https://tpc.googlesyndication.com/simgad']"))).click()
</code>```

xpath:

```<code>new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[contains(@id, 'com/Web/News24/Homepage_20') and starts-with(@name, 'google_ads_iframe_')][@title='3rd party ad content']")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@class='i-amphtml-fill-content i-amphtml-replaced-content' and starts-with(@src, 'https://tpc.googlesyndication.com/simgad')]"))).click();
</code>```

Body:
I am trying to locate image using Selenium webdriver but unable to locate it by Xpath/cssSelector

I have tried cssSelector and xpath but not working.

By cssSelector -->

WebElement elementOut = driver.findElement(By.cssSelector(".i-amphtml-fill-content.i-amphtml-replaced-content"));

By Xpath -->

WebElement elementOut = driver.findElement(By.xpath("//*[@id='aw0']/amp-img/img"));

I need to locate the image.

Snapshot of the page source:

Body:
To click() on the image, as the the desired element is within an <iframe> so you have to:

Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.

Induce WebDriverWait for the desired elementToBeClickable.

You can use either of the following Locator Strategies:

cssSelector:

new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id$='com/Web/News24/Homepage_20'][name^='google_ads_iframe_'][title='3rd party ad content']")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("img.i-amphtml-fill-content.i-amphtml-replaced-content[src^='https://tpc.googlesyndication.com/simgad']"))).click()

xpath:

new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[contains(@id, 'com/Web/News24/Homepage_20') and starts-with(@name, 'google_ads_iframe_')][@title='3rd party ad content']")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@class='i-amphtml-fill-content i-amphtml-replaced-content' and starts-with(@src, 'https://tpc.googlesyndication.com/simgad')]"))).click();


问:
How can I fix the position of buttons in a RecylerView layout? I don't want the buttons to scroll along with the image in RecyclerView
I am using a recyclerview and I want to stop scrolling of the complete layout on scrolling left or right.

If it is not possible, is there a way to get the itemposition without a click Interface so that I can put the buttons outside recylerview?
The buttons are placed in a cardview.

答: Copy the button layout below to recycler view in xml of activity from item layout. </p>


问:
Passing an object's string value to component using a button Angular
In my html template of my component 'a', I have a button which is used to navigate to an other component :

```<code><button nbButton status="info" class="left" [routerLink]="['/centers', center.id, 'prices']">PRICES</button>
</code>```

So clicking on this button made me move to an other component 'b'.

In the component 'a' I have a private object variable, which contains a string value currenciesAccepted, basically :myObject.currenciesAccepted.

In the component 'b', I need this string value, so I need to pass it when I click on the button, to navigate from the component 'a' to the component 'b'.

答:
try this

```<code><button nbButton status="info" class="left"
[routerLink]="['/centers', center.id, 'prices']"
[queryParams]='{currenciesAccepted: myObject.currenciesAccepted}' >PRICES</button>
</code>```

in centers component

```<code>import { ActivatedRoute } from '@angular/router';

currenciesAccepted: any = {};
constructor( private route: ActivatedRoute) { }

ngOnInit() {
    this.route.queryParamMap.subscribe( params => {
     this.currenciesAccepted  = params.get('currenciesAccepted') ;
     })
</code>```

}

Body:
In my html template of my component 'a', I have a button which is used to navigate to an other component :

<button nbButton status="info" class="left" [routerLink]="['/centers', center.id, 'prices']">PRICES</button>

So clicking on this button made me move to an other component 'b'.

In the component 'a' I have a private object variable, which contains a string value currenciesAccepted, basically :myObject.currenciesAccepted.

In the component 'b', I need this string value, so I need to pass it when I click on the button, to navigate from the component 'a' to the component 'b'.

Body:
try this

<button nbButton status="info" class="left"
[routerLink]="['/centers', center.id, 'prices']"
[queryParams]='{currenciesAccepted: myObject.currenciesAccepted}' >PRICES</button>

in centers component

import { ActivatedRoute } from '@angular/router';

currenciesAccepted: any = {};
constructor( private route: ActivatedRoute) { }

ngOnInit() {
    this.route.queryParamMap.subscribe( params => {
     this.currenciesAccepted  = params.get('currenciesAccepted') ;
     })

}


问:
Shell Script To Write PostgreSQL SQL Query Results In To CSV Format
I need to create a Linux shell script to run a PostgreSQL SQL query and  export the results in CSV Format. By doing some research I came to know there are two ways I can do it such as below:

using an SQL query

```<code>COPY table_name TO ‘file_name.csv' DELIMITER ',' CSV HEADER;
</code>```

using psql

```<code>\copy table_name to 'filename.csv’ csv header
</code>```

I have tried both from SQL server out of which I found the first method needs administrative permission, which I don't want.

I have tried the second method and am able to write the PostgreSQL query output to a CSV file as well, but now I need to do that from a shell script, where I am facing the below issue. I am writing inside the script as follows:

```<code>psql -U username -d database -c $'
\copy(WITH var(collectionMonth) as (values(\'$collectionMonth\'))
SELECT CONCAT(var.collectionMonth, LPAD(mfv2.integer_value::text,2,\'0\')) as "collection_date" FROM var,
meta_field_value mfv2 WHERE mfv2.meta_field_name_id=8 TO \'/home/my.csv\' csv HEADER;'
</code>```

It shows “syntax error near \copy”. How to fix this? I know the error is because of the \ in front of the copy command.

答:
Your quoting is off.

Best is to use a “here document”:

```<code>psql -U username -d database <<EOF
\copy (WITH var(collectionMonth) as (values('$collectionMonth')) SELECT CONCAT(var.collectionMonth, LPAD(mfv2.integer_value::text,2,'0')) as "collection_date" FROM var, meta_field_value mfv2 WHERE mfv2.meta_field_name_id=8) TO '/home/my.csv' (FORMAT 'csv', HEADER)
EOF
</code>```

Body:
I need to create a Linux shell script to run a PostgreSQL SQL query and  export the results in CSV Format. By doing some research I came to know there are two ways I can do it such as below:

using an SQL query

COPY table_name TO ‘file_name.csv' DELIMITER ',' CSV HEADER;

using psql

\copy table_name to 'filename.csv’ csv header

I have tried both from SQL server out of which I found the first method needs administrative permission, which I don't want.

I have tried the second method and am able to write the PostgreSQL query output to a CSV file as well, but now I need to do that from a shell script, where I am facing the below issue. I am writing inside the script as follows:

psql -U username -d database -c $'
\copy(WITH var(collectionMonth) as (values(\'$collectionMonth\'))
SELECT CONCAT(var.collectionMonth, LPAD(mfv2.integer_value::text,2,\'0\')) as "collection_date" FROM var,
meta_field_value mfv2 WHERE mfv2.meta_field_name_id=8 TO \'/home/my.csv\' csv HEADER;'

It shows “syntax error near \copy”. How to fix this? I know the error is because of the \ in front of the copy command.

Body:
Your quoting is off.

Best is to use a “here document”:

psql -U username -d database <<EOF
\copy (WITH var(collectionMonth) as (values('$collectionMonth')) SELECT CONCAT(var.collectionMonth, LPAD(mfv2.integer_value::text,2,'0')) as "collection_date" FROM var, meta_field_value mfv2 WHERE mfv2.meta_field_name_id=8) TO '/home/my.csv' (FORMAT 'csv', HEADER)
EOF


问:
PHPExcel - dynamically check columns in a row
I have a xlsx file where the first row has:

image :

I need to dynamically check how much locales are there (by column name), as it can happen that it can be only one or 5/6 columns.

How to set it?

```<code>$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filePath);
$activeSheet = $phpExcelObject->getActiveSheet()->rangeToArray('B1:G1');

dump($activeSheet);die;
</code>```

答:
at first, you can use PhpSpreadsheet for loading Excel files.

there is example code for counting first row keys :

```<code>    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\IOFactory;
    $reader = new \PhpOffice\PhpSpreadsheet\Reader\xlsx();

    $spreadsheet = $reader->load($filePath);
    $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

    $firstRow = $sheetData[0];

    $cnt = 0;

    foreach ($firstRow as $value) {
        if($value)
            $cnt++;
    }
    //because of first column
    $cnt--;
</code>```

the last line, mines one is because of your first column "key"

Body:
I have a xlsx file where the first row has:

image :

I need to dynamically check how much locales are there (by column name), as it can happen that it can be only one or 5/6 columns.

How to set it?

$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filePath);
$activeSheet = $phpExcelObject->getActiveSheet()->rangeToArray('B1:G1');

dump($activeSheet);die;

Body:
at first, you can use PhpSpreadsheet for loading Excel files.

there is example code for counting first row keys :

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\IOFactory;
    $reader = new \PhpOffice\PhpSpreadsheet\Reader\xlsx();

    $spreadsheet = $reader->load($filePath);
    $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

    $firstRow = $sheetData[0];

    $cnt = 0;

    foreach ($firstRow as $value) {
        if($value)
            $cnt++;
    }
    //because of first column
    $cnt--;

the last line, mines one is because of your first column "key"


问:
Need some help positioning a header and sub heading
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div></code>```

答:
Try below Code...</p>

```<code><div class="myDiv">
  <h3>helpthistext</h3>
  <h1>title one & another one</h1>
</div>
</code>```

```<code>.myDiv {
  margin: 20px auto;
  width: 50%;
}

.myDiv h3 {
  margin: 0px;
}

.myDiv h1 {
  margin: 0;
}
</code>```

Body:
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}

  helpthistext

title one & another one

Body:
Try below Code...

<div class="myDiv">
  <h3>helpthistext</h3>
  <h1>title one & another one</h1>
</div>

.myDiv {
  margin: 20px auto;
  width: 50%;
}

.myDiv h3 {
  margin: 0px;
}

.myDiv h1 {
  margin: 0;
}


问:
Having a firewall issues when using FOSUserBundle
I am trying to incorporate FOSUserBundle in existing project that has an authentication system for admin and I am using FOSUserBundle for users but I have a firwall error!

I am using this url: http://localhost/myproject/web/app_dev.php/fr/user/login

and the error :

```<code>InvalidConfigurationException in BaseNode.php line 313:
Invalid configuration for path "security.firewalls.Fos_secured_area": The check_path "/login_check" for login method "form_login" is not matched by the firewall pattern "^/(fr|en)/user/.*".
</code>```

this is my security.yml

```<code> admin:
            entity: { class: AppBundle:Admin}

        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:

        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        Fos_secured_area:
            pattern:  ^/(%app_locales%)/User/.*
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout:       true
            anonymous:    true

        admin_secured_area:
            pattern: ^/(%app_locales%)/admin/.*
            anonymous: true
            provider: admin
            form_login:
                check_path: security_admin_login
                login_path: security_admin_login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: admin_page
            logout:
                path: admin_logout
                target: homepage
  access_control:

     - { path: ^/(%app_locales%)/User/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
     - { path: ^/(%app_locales%)/User/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
     - { path: ^/(%app_locales%)/User/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
</code>```

my routing.yml

```<code>fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

app:
    resource: '@AppBundle/Controller/'
    type:     annotation
    prefix:   /{_locale}
    requirements:
        _locale: '%app_locales%'
    defaults:
        _locale: '%locale%'
</code>```

答:
try changing

```<code>pattern: ^/(%app_locales%)/User/.*
</code>```

to

```<code>pattern: ^/
</code>```

I think there is no need for that pattern in your case

Short explanation:
The pattern is a regex that determens what firewall rule will apply for what route.

Fosuserbundle uses a route that looks like  /login_check for the callback of the login action. And since it doesn't match your pattern the Fos_secured_area rull won't apply for that route.

Body:
I am trying to incorporate FOSUserBundle in existing project that has an authentication system for admin and I am using FOSUserBundle for users but I have a firwall error!

I am using this url: http://localhost/myproject/web/app_dev.php/fr/user/login

and the error :

InvalidConfigurationException in BaseNode.php line 313:
Invalid configuration for path "security.firewalls.Fos_secured_area": The check_path "/login_check" for login method "form_login" is not matched by the firewall pattern "^/(fr|en)/user/.*".

this is my security.yml

 admin:
            entity: { class: AppBundle:Admin}

        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:

        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        Fos_secured_area:
            pattern:  ^/(%app_locales%)/User/.*
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout:       true
            anonymous:    true

        admin_secured_area:
            pattern: ^/(%app_locales%)/admin/.*
            anonymous: true
            provider: admin
            form_login:
                check_path: security_admin_login
                login_path: security_admin_login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: admin_page
            logout:
                path: admin_logout
                target: homepage
  access_control:

     - { path: ^/(%app_locales%)/User/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
     - { path: ^/(%app_locales%)/User/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
     - { path: ^/(%app_locales%)/User/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }

my routing.yml

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

app:
    resource: '@AppBundle/Controller/'
    type:     annotation
    prefix:   /{_locale}
    requirements:
        _locale: '%app_locales%'
    defaults:
        _locale: '%locale%'

Body:
try changing

pattern: ^/(%app_locales%)/User/.*

to

pattern: ^/

I think there is no need for that pattern in your case

Short explanation:
The pattern is a regex that determens what firewall rule will apply for what route.

Fosuserbundle uses a route that looks like  /login_check for the callback of the login action. And since it doesn't match your pattern the Fos_secured_area rull won't apply for that route.


问:
Firebase target Inactive user audience
I want to create an Audience in Firebase that consists of users who have not used the app in one day. By doing this, I could target notifications to be sent via the Notifications Console.

I am aware that I can send data to Firebase as a User Property, for example I can define a value like last_opened_app to equal current time in ms. But there is no way to compare it to current time to see if its been a day etc. Any ideas? thanks

答:
You can do this using including and excluding conditions.

Audiences are now dynamic by default, meaning Analytics will automatically include users as soon as they meet your criteria, and automatically exclude users when they no longer do. This allows you to “set and forget” your audiences while they populate, without the hassle of constantly re-evaluating them.

Audiences can be more precisely defined by adding exclusion criteria. For example, you can create a list of users that added an item to a shopping cart and of those users, exclude those who have also made a purchase.

Dynamic audiences in Google Analytics for Firebase

Title: Firebase target Inactive user audience


问:
Django going to external website with my variables in url
I have a model and i want to go to a external website with my variables in the url . For example: "www.example.com\ {% object.field %} .com

My model

class Avaria(models.Model):
    freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia")
    rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua")
```

<p>I'm changing my <code>change_form_object_tools.html</code> and add a extra <code>li</code> to do something like this: </p>

<pre class="lang-html prettyprint-override"><code><li>
    {% trans "Example" %
</li>
</code>```

If i use the original.pk it is working but i want to use another field that is not the primary key

答:
If you're getting correct object in variable obj then

instead of

```<code><a href="https://example.com\{% obj.freguesia%}\{% obj.rua%}">{% trans "Example" %</a>
</code>```

you need to do

```<code><a href="https://example.com\{{ obj.freguesia }}\{{ obj.rua }}">{% trans "Example" %</a>
</code>```

I know in django admin model object comes in variable original, you can use original in place of obj.

Also if you want to understand django template language

{{ }} for rendering variables and using filters, read more

{% %} for sentences such as if and for or to call tags such as load, static, etc. is for tags, read more

Similarly there is {#  #} for comments.

Read the documentation please

Body:
I have a model and i want to go to a external website with my variables in the url . For example: "www.example.com\ {% object.field %} .com

My model

class Avaria(models.Model):
    freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia")
    rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua")

I'm changing my change_form_object_tools.html and add a extra li to do something like this:

    {% trans "Example" %

If i use the original.pk it is working but i want to use another field that is not the primary key

Body:
If you're getting correct object in variable obj then

instead of

<a href="https://example.com\{% obj.freguesia%}\{% obj.rua%}">{% trans "Example" %</a>

you need to do

<a href="https://example.com\{{ obj.freguesia }}\{{ obj.rua }}">{% trans "Example" %</a>

I know in django admin model object comes in variable original, you can use original in place of obj.

Also if you want to understand django template language

{{ }} for rendering variables and using filters, read more

{% %} for sentences such as if and for or to call tags such as load, static, etc. is for tags, read more

Similarly there is {#  #} for comments.

Read the documentation please


问:
How to focus on label(s) that is(are) difficult to predict?
I am facing with binary classification problem. I am using some machine learning models and Python 3. I have noticed that some models perform better on a given class than the others. I would like to combine them to improve my accuracy and precision. I know a way to do so in regression problems, something like a weighted average of predictions. But I am not sure that it makes sense in classification problem. And, you must know a better way to do so.

Here is my algorithm that helps me to identify labels which are particularly difficult to predict :

```<code>"""
each value is in {0, 1}
ytrue : real values
ypred : predicted values
"""
def errorIdentifier(ytrue, ypred):
    n = len(ytrue)
    ytrue = list(ytrue)
    ypred = list(ypred)
    error = [0,0]
    for i in range(n):
        if ytrue[i] != ypred[i] :
            error[ytrue[i]] += 1
    return error
</code>```

As you can guess, I need to call it for each model I am using.

答:
The issue that different models are better are predicting different class is a classical machine learning problem. It arises due to the fact the various algorithms are better at modelling different features, hence the inclination towards better accuracy on a certain class.

To overcome this issue, we can make use of a number of models and ensemble the results to get an improved accuracy. This approach is known as ensemble learning.

There are a number of methods such as bagging, boosting etc. and some well known ensemble learning algorithms such as RandomForest. You'll have to research the various techniques to find the one that best suits your needs.

Body:
I am facing with binary classification problem. I am using some machine learning models and Python 3. I have noticed that some models perform better on a given class than the others. I would like to combine them to improve my accuracy and precision. I know a way to do so in regression problems, something like a weighted average of predictions. But I am not sure that it makes sense in classification problem. And, you must know a better way to do so.

Here is my algorithm that helps me to identify labels which are particularly difficult to predict :

"""
each value is in {0, 1}
ytrue : real values
ypred : predicted values
"""
def errorIdentifier(ytrue, ypred):
    n = len(ytrue)
    ytrue = list(ytrue)
    ypred = list(ypred)
    error = [0,0]
    for i in range(n):
        if ytrue[i] != ypred[i] :
            error[ytrue[i]] += 1
    return error

As you can guess, I need to call it for each model I am using.


问:
Installing pandas in docker Alpine
I am having a really hard time trying to install a stable data science package configuration in docker. This should be easier with such mainstream, relevant tools.

The following is the Dockerfile that used to work, with a bit of a hack, removing pandas from the package core and installing it separately, specifying pandas<0.21.0, because, allegedly, higher versions conflict with numpy.

```<code>    FROM alpine:3.6

    ENV PACKAGES="\
    dumb-init \
    musl \
    libc6-compat \
    linux-headers \
    build-base \
    bash \
    git \
    ca-certificates \
    freetype \
    libgfortran \
    libgcc \
    libstdc++ \
    openblas \
    tcl \
    tk \
    libssl1.0 \
    "

ENV PYTHON_PACKAGES="\
    numpy \
    matplotlib \
    scipy \
    scikit-learn \
    nltk \
    "

RUN apk add --no-cache --virtual build-dependencies python3 \
    && apk add --virtual build-runtime \
    build-base python3-dev openblas-dev freetype-dev pkgconfig gfortran \
    && ln -s /usr/include/locale.h /usr/include/xlocale.h \
    && python3 -m ensurepip \
    && rm -r /usr/lib/python*/ensurepip \
    && pip3 install --upgrade pip setuptools \
    && ln -sf /usr/bin/python3 /usr/bin/python \
    && ln -sf pip3 /usr/bin/pip \
    && rm -r /root/.cache \
    && pip install --no-cache-dir $PYTHON_PACKAGES \
    && pip3 install 'pandas<0.21.0' \    #<---------- PANDAS
    && apk del build-runtime \
    && apk add --no-cache --virtual build-dependencies $PACKAGES \
    && rm -rf /var/cache/apk/*

# set working directory
WORKDIR /usr/src/app

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt # other than data science packages go here
RUN pip install -r requirements.txt

# add entrypoint.sh
COPY ./entrypoint.sh /usr/src/app/entrypoint.sh

RUN chmod +x /usr/src/app/entrypoint.sh

# add app
COPY . /usr/src/app

# run server
CMD ["/usr/src/app/entrypoint.sh"]
</code>```

The configuration above used to work. What happens now is that build does go through, but pandas fails at import with the following error:

```<code>ImportError: Missing required dependencies ['numpy']
</code>```

Since numpy 1.16.1 was installed, I don't know which numpy pandas is trying to find anymore...

Does anyone know how to obtain a stable solution for this?

NOTE: A solution consisting of a pull from a turnkey docker image for data science with at least the packages mentioned above, into Dockerfile above, would be also very welcomed.

EDIT 1:

If I move install of data packages into requirements.txt, as suggested in the comments, like so:

requirements.txt

```<code>(...)
numpy==1.16.1 # or numpy==1.16.0
scikit-learn==0.20.2
scipy==1.2.1
nltk==3.4
pandas==0.24.1 # or pandas== 0.23.4
matplotlib==3.0.2
(...)
</code>```

and Dockerfile:

```<code># add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt
</code>```

It breaks again at pandas, complaining about numpy.

```<code>Collecting numpy==1.16.1 (from -r requirements.txt (line 61))
  Downloading https://files.pythonhosted.org/packages/2b/26/07472b0de91851b6656cbc86e2f0d5d3a3128e7580f23295ef58b6862d6c/numpy-1.16.1.zip (5.1MB)
Collecting scikit-learn==0.20.2 (from -r requirements.txt (line 62))
  Downloading https://files.pythonhosted.org/packages/49/0e/8312ac2d7f38537361b943c8cde4b16dadcc9389760bb855323b67bac091/scikit-learn-0.20.2.tar.gz (10.3MB)
Collecting scipy==1.2.1 (from -r requirements.txt (line 63))
  Downloading https://files.pythonhosted.org/packages/a9/b4/5598a706697d1e2929eaf7fe68898ef4bea76e4950b9efbe1ef396b8813a/scipy-1.2.1.tar.gz (23.1MB)
Collecting nltk==3.4 (from -r requirements.txt (line 64))
  Downloading https://files.pythonhosted.org/packages/6f/ed/9c755d357d33bc1931e157f537721efb5b88d2c583fe593cc09603076cc3/nltk-3.4.zip (1.4MB)
Collecting pandas==0.24.1 (from -r requirements.txt (line 65))
  Downloading https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz (11.8MB)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 359, in get_provider
        module = sys.modules[moduleOrReq]
    KeyError: 'numpy'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 732, in <module>
        ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 475, in maybe_cythonize
        numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1144, in resource_filename
        return get_provider(package_or_requirement).get_resource_filename(
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 361, in get_provider
        __import__(moduleOrReq)
    ModuleNotFoundError: No module named 'numpy'

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-_e5z6o6_/pandas/
</code>```

EDIT 2:

This seems like an open pandas issue. For more details please refer to:

pandas-dev github

"Unfortunately, this means that a requirements.txt file is insufficient for setting up a new environment with pandas installed (like in a docker container)".

```<code>  **ImportError**:

  IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

  Importing the multiarray numpy extension module failed.  Most
  likely you are trying to import a failed build of numpy.
  Here is how to proceed:
  - If you're working with a numpy git repository, try `git clean -xdf`
    (removes all files not under version control) and rebuild numpy.
  - If you are simply trying to use the numpy version that you have installed:
    your installation is broken - please reinstall numpy.
  - If you have already reinstalled and that did not fix the problem, then:
    1. Check that you are using the Python you expect (you're using /usr/local/bin/python),
       and that you have no directories in your PATH or PYTHONPATH that can
       interfere with the Python and numpy versions you're trying to use.
    2. If (1) looks fine, you can open a new issue at
       https://github.com/numpy/numpy/issues.  Please include details on:
       - how you installed Python
       - how you installed numpy
       - your operating system
       - whether or not you have multiple versions of Python installed
       - if you built from source, your compiler versions and ideally a build log
</code>```

EDIT 3

requirements.txt ---> https://pastebin.com/0icnx0iu

EDIT 4

As of 01/12/20, the accepted solution started not to work anymore.
Now, build breaks not at pandas, but at scipy but after numpy, while building scipy's wheel. This is the log:

```<code>  ----------------------------------------
  ERROR: Failed building wheel for scipy
  Running setup.py clean for scipy
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: /tmp/pip-install-s6nahssd/scipy
  Complete output (9 lines):

  `setup.py clean` is not supported, use one of the following instead:

    - `git clean -xdf` (cleans all files)
    - `git clean -Xdf` (cleans all versioned files, doesn't touch
                        files that aren't checked into the git repo)

  Add `--force` to your command to use it anyway if you must (unsupported).

  ----------------------------------------
  ERROR: Failed cleaning build dir for scipy
Successfully built numpy
Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly
</code>```

From the error it seems that building process is using python3.6, while I use FROM alpine:3.7.

Full log here -> https://pastebin.com/Tw4ubxSA

And this is the current Dockerfile:

https://pastebin.com/3SftEufx

答:
This may not be completely relevant, since this the first answer that pops up when searching for numpy/pandas installation failed in Alpine, I am adding this answer.

The following fix worked for me(But it takes longer to install pandas/numpy)

```<code>apk update
apk --no-cache add curl gcc g++
ln -s /usr/include/locale.h /usr/include/xlocale.h
</code>```

Now try installing pandas/numpy

Title: Installing pandas in docker Alpine

Body:
I am having a really hard time trying to install a stable data science package configuration in docker. This should be easier with such mainstream, relevant tools.

The following is the Dockerfile that used to work, with a bit of a hack, removing pandas from the package core and installing it separately, specifying pandas<0.21.0, because, allegedly, higher versions conflict with numpy.

    FROM alpine:3.6

    ENV PACKAGES="\
    dumb-init \
    musl \
    libc6-compat \
    linux-headers \
    build-base \
    bash \
    git \
    ca-certificates \
    freetype \
    libgfortran \
    libgcc \
    libstdc++ \
    openblas \
    tcl \
    tk \
    libssl1.0 \
    "

ENV PYTHON_PACKAGES="\
    numpy \
    matplotlib \
    scipy \
    scikit-learn \
    nltk \
    "

RUN apk add --no-cache --virtual build-dependencies python3 \
    && apk add --virtual build-runtime \
    build-base python3-dev openblas-dev freetype-dev pkgconfig gfortran \
    && ln -s /usr/include/locale.h /usr/include/xlocale.h \
    && python3 -m ensurepip \
    && rm -r /usr/lib/python*/ensurepip \
    && pip3 install --upgrade pip setuptools \
    && ln -sf /usr/bin/python3 /usr/bin/python \
    && ln -sf pip3 /usr/bin/pip \
    && rm -r /root/.cache \
    && pip install --no-cache-dir $PYTHON_PACKAGES \
    && pip3 install 'pandas<0.21.0' \    #<---------- PANDAS
    && apk del build-runtime \
    && apk add --no-cache --virtual build-dependencies $PACKAGES \
    && rm -rf /var/cache/apk/*

# set working directory
WORKDIR /usr/src/app

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt # other than data science packages go here
RUN pip install -r requirements.txt

# add entrypoint.sh
COPY ./entrypoint.sh /usr/src/app/entrypoint.sh

RUN chmod +x /usr/src/app/entrypoint.sh

# add app
COPY . /usr/src/app

# run server
CMD ["/usr/src/app/entrypoint.sh"]

The configuration above used to work. What happens now is that build does go through, but pandas fails at import with the following error:

ImportError: Missing required dependencies ['numpy']

Since numpy 1.16.1 was installed, I don't know which numpy pandas is trying to find anymore...

Does anyone know how to obtain a stable solution for this?

NOTE: A solution consisting of a pull from a turnkey docker image for data science with at least the packages mentioned above, into Dockerfile above, would be also very welcomed.

EDIT 1:

If I move install of data packages into requirements.txt, as suggested in the comments, like so:

requirements.txt

(...)
numpy==1.16.1 # or numpy==1.16.0
scikit-learn==0.20.2
scipy==1.2.1
nltk==3.4
pandas==0.24.1 # or pandas== 0.23.4
matplotlib==3.0.2
(...)

and Dockerfile:

# add and install requirements
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt

It breaks again at pandas, complaining about numpy.

Collecting numpy==1.16.1 (from -r requirements.txt (line 61))
  Downloading https://files.pythonhosted.org/packages/2b/26/07472b0de91851b6656cbc86e2f0d5d3a3128e7580f23295ef58b6862d6c/numpy-1.16.1.zip (5.1MB)
Collecting scikit-learn==0.20.2 (from -r requirements.txt (line 62))
  Downloading https://files.pythonhosted.org/packages/49/0e/8312ac2d7f38537361b943c8cde4b16dadcc9389760bb855323b67bac091/scikit-learn-0.20.2.tar.gz (10.3MB)
Collecting scipy==1.2.1 (from -r requirements.txt (line 63))
  Downloading https://files.pythonhosted.org/packages/a9/b4/5598a706697d1e2929eaf7fe68898ef4bea76e4950b9efbe1ef396b8813a/scipy-1.2.1.tar.gz (23.1MB)
Collecting nltk==3.4 (from -r requirements.txt (line 64))
  Downloading https://files.pythonhosted.org/packages/6f/ed/9c755d357d33bc1931e157f537721efb5b88d2c583fe593cc09603076cc3/nltk-3.4.zip (1.4MB)
Collecting pandas==0.24.1 (from -r requirements.txt (line 65))
  Downloading https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz (11.8MB)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 359, in get_provider
        module = sys.modules[moduleOrReq]
    KeyError: 'numpy'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 732, in <module>
        ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
      File "/tmp/pip-install-_e5z6o6_/pandas/setup.py", line 475, in maybe_cythonize
        numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1144, in resource_filename
        return get_provider(package_or_requirement).get_resource_filename(
      File "/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py", line 361, in get_provider
        __import__(moduleOrReq)
    ModuleNotFoundError: No module named 'numpy'

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-_e5z6o6_/pandas/

EDIT 2:

This seems like an open pandas issue. For more details please refer to:

pandas-dev github

"Unfortunately, this means that a requirements.txt file is insufficient for setting up a new environment with pandas installed (like in a docker container)".

  **ImportError**:

  IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

  Importing the multiarray numpy extension module failed.  Most
  likely you are trying to import a failed build of numpy.
  Here is how to proceed:
  - If you're working with a numpy git repository, try `git clean -xdf`
    (removes all files not under version control) and rebuild numpy.
  - If you are simply trying to use the numpy version that you have installed:
    your installation is broken - please reinstall numpy.
  - If you have already reinstalled and that did not fix the problem, then:
    1. Check that you are using the Python you expect (you're using /usr/local/bin/python),
       and that you have no directories in your PATH or PYTHONPATH that can
       interfere with the Python and numpy versions you're trying to use.
    2. If (1) looks fine, you can open a new issue at
       https://github.com/numpy/numpy/issues.  Please include details on:
       - how you installed Python
       - how you installed numpy
       - your operating system
       - whether or not you have multiple versions of Python installed
       - if you built from source, your compiler versions and ideally a build log

EDIT 3

requirements.txt ---> https://pastebin.com/0icnx0iu

EDIT 4

As of 01/12/20, the accepted solution started not to work anymore.
Now, build breaks not at pandas, but at scipy but after numpy, while building scipy's wheel. This is the log:

  ----------------------------------------
  ERROR: Failed building wheel for scipy
  Running setup.py clean for scipy
  ERROR: Command errored out with exit status 1:
   command: /usr/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s6nahssd/scipy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: /tmp/pip-install-s6nahssd/scipy
  Complete output (9 lines):

  `setup.py clean` is not supported, use one of the following instead:

    - `git clean -xdf` (cleans all files)
    - `git clean -Xdf` (cleans all versioned files, doesn't touch
                        files that aren't checked into the git repo)

  Add `--force` to your command to use it anyway if you must (unsupported).

  ----------------------------------------
  ERROR: Failed cleaning build dir for scipy
Successfully built numpy
Failed to build scipy
ERROR: Could not build wheels for scipy which use PEP 517 and cannot be installed directly

From the error it seems that building process is using python3.6, while I use FROM alpine:3.7.

Full log here -> https://pastebin.com/Tw4ubxSA

And this is the current Dockerfile:

https://pastebin.com/3SftEufx

Body:
This may not be completely relevant, since this the first answer that pops up when searching for numpy/pandas installation failed in Alpine, I am adding this answer.

The following fix worked for me(But it takes longer to install pandas/numpy)

apk update
apk --no-cache add curl gcc g++
ln -s /usr/include/locale.h /usr/include/xlocale.h

Now try installing pandas/numpy


问:
Issue with STM32F769 PWM output when updated according to condition
I am using STM32F769 Disc board with Mbed online compiler. My task is to change the PWM frequency and duty ratio according to input.

I've created a simple algorithm according to my need, the program is working well but whenever the controller updates the PWM frequency, there is strange behavior(overlapped maybe, difficult to explain verbally for me), the frequency is changed instantly and the output is incorrect at that moment. For other controllers (like arduino) this never happens, the controller updates value after the time period of PWM is over. But not in this case.
What can be wrong?

I thought to add a small delay before value is updated but that will not work, as every time a different delay would be needed. I have attached the code and screenshots.

#include "mbed.h"

AnalogIn analog_value(A0);

PwmOut pulse(D11);

int main() {

  double meas_v = 0;
  double out_freq, out_duty, s_time;
  while (1) {

    meas_v = analog_value.read() * 3300;
    if (meas_v < 1) {
      out_freq = 50000;
      out_duty = 40;
    } else if (meas_v >= 1000) {
      out_freq = 100000;
      out_duty = 80;
    } else {
      out_freq = 50000 + (meas_v * 50);
      out_duty = 40 + (meas_v * 0.04);
    }

    pulse.period(1.0 / out_freq);
    pulse = out_duty / 100;
    s_time = 0.0001;
    wait(s_time);
  }
}
```

The output should be updated after the current period is completed, not instantly.

Error I am getting

答: You need to update the value in the update interrupt or use the timer DMA burst mode</p>

Body:
I am using STM32F769 Disc board with Mbed online compiler. My task is to change the PWM frequency and duty ratio according to input.

I've created a simple algorithm according to my need, the program is working well but whenever the controller updates the PWM frequency, there is strange behavior(overlapped maybe, difficult to explain verbally for me), the frequency is changed instantly and the output is incorrect at that moment. For other controllers (like arduino) this never happens, the controller updates value after the time period of PWM is over. But not in this case.
What can be wrong?

I thought to add a small delay before value is updated but that will not work, as every time a different delay would be needed. I have attached the code and screenshots.

#include "mbed.h"

AnalogIn analog_value(A0);

PwmOut pulse(D11);

int main() {

  double meas_v = 0;
  double out_freq, out_duty, s_time;
  while (1) {

    meas_v = analog_value.read() * 3300;
    if (meas_v < 1) {
      out_freq = 50000;
      out_duty = 40;
    } else if (meas_v >= 1000) {
      out_freq = 100000;
      out_duty = 80;
    } else {
      out_freq = 50000 + (meas_v * 50);
      out_duty = 40 + (meas_v * 0.04);
    }

    pulse.period(1.0 / out_freq);
    pulse = out_duty / 100;
    s_time = 0.0001;
    wait(s_time);
  }
}

The output should be updated after the current period is completed, not instantly.

Error I am getting


问:
Matlab sum function from index to index
I am looking for a better way to calculate the sum off all elements from index X to index Y, if I have a list of indexes.

For example:

```<code>a = {1, 40, 77} % indexes
cell_elements = {1,1,1.....,1} %100 elements, each 1
</code>```

My current idea looks something like this:

```<code>        counter = 1;
        for k=1:length(cell_elements)
            if(%Some condition) %condition is true for k=1,40 and 77
                sum = sum+cell_elements(k);
                result(counter) = sum;
                sum=0;
                counter = counter+1;
            else
                sum = sum+cell_elements(k);
            end
        end
</code>```

I would like to improve the code, since I have the feeling that the problematic is simple, but due to my lack of experience in matlab my code is too long.

Is there any function, where I could just pass a list of indexes and it will do the same job as the code above?

答:
Use array instead of cell

Also since your cell_elements are all 1s, you can use the matrix
ones(row, column)

Specify the row and the column, here row is 1 and column is 100 this is the code

```<code>cell_elements = ones(1, 100)
</code>```

Define a as an array a = [1, 40, 77]

First 40 elements are elements having indices from 1 to 40, in Matlab
this is equivalent to 1:40, in order to include the array a,
since a(1) = 1 and a(2) = 40; set 1:40 as a(1):a(2)
First 40 elements will be

```<code>First_40_elements = cell_elements(a(1):a(2));
</code>```

To sum them all together use Matlab built in function sum as follow

```<code>Sum_First_40_elements = sum(First_40_elements)
</code>```

For the second 37 elements the indices start from 41 to 77, in Matlab
written as 41:77, using array a, a(2)+1:a(3)

Following the logic above

```<code>Second_37_elements = cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = cell_elements(Second_37_elements);
</code>```

The entire code is as follow

```<code>cell_elements = ones(1,100);

a = [1,40,77];

First_40_elements =  cell_elements(a(1):a(2));

Sum_First_40_elements = sum(First_40_elements);
% 40

Second_37_elements =  cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = sum(Second_37_elements);
% 37
</code>```

The dynamic way is as follow

```<code>cell_elements = ones(1,100);
a = [1,25,40, 67, 80, 95];

element_sum = zeros(1, length(a)-1);
for i = 1:length(a)-1
    if i == 1
        element_sum(i) =  sum(cell_elements(a(i):a(i+1)));
    else
        element_sum(i) =  sum(cell_elements(a(i)+1:a(i+1)));
    end
end
</code>```

Result

```<code>>> element_sum

element_sum =

    25    15    27    13    15

>>
</code>```

Title: Matlab sum function from index to index

Body:
I am looking for a better way to calculate the sum off all elements from index X to index Y, if I have a list of indexes.

For example:

a = {1, 40, 77} % indexes
cell_elements = {1,1,1.....,1} %100 elements, each 1

My current idea looks something like this:

        counter = 1;
        for k=1:length(cell_elements)
            if(%Some condition) %condition is true for k=1,40 and 77
                sum = sum+cell_elements(k);
                result(counter) = sum;
                sum=0;
                counter = counter+1;
            else
                sum = sum+cell_elements(k);
            end
        end

I would like to improve the code, since I have the feeling that the problematic is simple, but due to my lack of experience in matlab my code is too long.

Is there any function, where I could just pass a list of indexes and it will do the same job as the code above?

Body:
Use array instead of cell

Also since your cell_elements are all 1s, you can use the matrix
ones(row, column)

Specify the row and the column, here row is 1 and column is 100 this is the code

cell_elements = ones(1, 100)

Define a as an array a = [1, 40, 77]

First 40 elements are elements having indices from 1 to 40, in Matlab
this is equivalent to 1:40, in order to include the array a,
since a(1) = 1 and a(2) = 40; set 1:40 as a(1):a(2)
First 40 elements will be

First_40_elements = cell_elements(a(1):a(2));

To sum them all together use Matlab built in function sum as follow

Sum_First_40_elements = sum(First_40_elements)

For the second 37 elements the indices start from 41 to 77, in Matlab
written as 41:77, using array a, a(2)+1:a(3)

Following the logic above

Second_37_elements = cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = cell_elements(Second_37_elements);

The entire code is as follow

cell_elements = ones(1,100);

a = [1,40,77];

First_40_elements =  cell_elements(a(1):a(2));

Sum_First_40_elements = sum(First_40_elements);
% 40

Second_37_elements =  cell_elements(a(2)+1:a(3));

Sum_Second_37_elements = sum(Second_37_elements);
% 37

The dynamic way is as follow

cell_elements = ones(1,100);
a = [1,25,40, 67, 80, 95];

element_sum = zeros(1, length(a)-1);
for i = 1:length(a)-1
    if i == 1
        element_sum(i) =  sum(cell_elements(a(i):a(i+1)));
    else
        element_sum(i) =  sum(cell_elements(a(i)+1:a(i+1)));
    end
end

Result

>> element_sum

element_sum =

    25    15    27    13    15

>>


问:
Null-aware operator when traversing a nested map
How do you check for nulls when accessing second level map elements?
E.g.

```<code>var clientName = item['client']['name'];
</code>```

will throw an exception if item does not contain client
I'd like something like

```<code>item['client']?['name']
</code>```

or

```<code>item['client']?.['name']
</code>```

But that won't compile.

Surely I can do item['client'] twice or introduce a local var for it but that feels subpar.

答:
I think that this is similar to a question I asked some time ago.

Basically, this would be the solution for your case:

(item['client'] ?? const {})['name']
```

This makes use of the null-aware ?? operator which just returns an empty map in the case that 'client' is not present in item.

Body:
How do you check for nulls when accessing second level map elements?
E.g.

var clientName = item['client']['name'];

will throw an exception if item does not contain client
I'd like something like

item['client']?['name']

or

item['client']?.['name']

But that won't compile.

Surely I can do item['client'] twice or introduce a local var for it but that feels subpar.

Body:
I think that this is similar to a question I asked some time ago.

Basically, this would be the solution for your case:

(item['client'] ?? const {})['name']

This makes use of the null-aware ?? operator which just returns an empty map in the case that 'client' is not present in item.


问:
IE8 CSS Hack - best method?
Can anyone recommend the best way to hack IE8 styling via CSS, I've recently been making IE8 render as IE7 for ease -  but wondered if it was best to add IE8 hacks?</p>

答: Use conditional comments.</p>

Title: IE8 CSS Hack - best method?

Body: Use conditional comments.


问:
Why my Group root is an abstract and how to fix it?
I am making an app with JavaFX. And this is my code:

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package line;

import java.awt.Color;
import java.security.acl.Group;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;

 /**
 *
 * @author kevin
 */

public class Line extends Application {

    @Override
    public void start(Stage stage) throws Exception{
        Group root=new Group();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Why my Group root is an abstract and how to fix it?

What is abstract? How can I fix this to work properly?

答:
You are using the wrong class, the correct class is javafx.scene.Group ,not the Java security class.
 javafx.scene.Group can be used as root node</p>

Body:
I am making an app with JavaFX. And this is my code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package line;

import java.awt.Color;
import java.security.acl.Group;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;

 /**
 *
 * @author kevin
 */

public class Line extends Application {

    @Override
    public void start(Stage stage) throws Exception{
        Group root=new Group();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        launch(args);
    }
}

Why my Group root is an abstract and how to fix it?

What is abstract? How can I fix this to work properly?


问:
Right left swipe in appium
How to do Right and left in latest version of appium beacuse as we dont have swipe(driver.swipe) method in new appium version</p>

```<code>public DailyPicksPage swipeDailyPicksCard() throws Exception {
        Dimension size = agent.getMobileDriver().manage().window().getSize();
        System.out.println("Dimensions of the screen" + size);
        int startX = (int) (size.width * 0.80);
        int endX = (int) (size.width * 0.20);
        int width = size.width;
        int duration = 2000;
        int height = size.height;
        int pressHeight = (int) (height * 0.80);
        new TouchAction(agent.getMobileDriver()).press(PointOption.point(startX, pressHeight)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(duration))).moveTo(PointOption.point(endX, pressHeight)).release().perform();
        return new DailyPicksPage(params, agent);
    }
</code>```

答:
You can create a custom swipe method using io.appium.java_client.TouchAction

```<code>public void horizontalSwipeByPercentage(double startPercentage, double endPercentage, double anchorPercentage, AppiumDriver<MobileElement> driver) {
    Dimension size = driver.manage().window().getSize();
    int anchor = (int) (size.height * anchorPercentage);
    int startPoint = (int) (size.width * startPercentage);
    int endPoint = (int) (size.width * endPercentage);

    new TouchAction(driver)
            .press(PointOption.point(startPoint, anchor))
            .waitAction(WaitOptions.waitOptions(ofSeconds(1)))
            .moveTo(PointOption.point(endPoint, anchor))
            .release().perform();
}
</code>```

Title: Right left swipe in appium

Body:
How to do Right and left in latest version of appium beacuse as we dont have swipe(driver.swipe) method in new appium version

public DailyPicksPage swipeDailyPicksCard() throws Exception {
        Dimension size = agent.getMobileDriver().manage().window().getSize();
        System.out.println("Dimensions of the screen" + size);
        int startX = (int) (size.width * 0.80);
        int endX = (int) (size.width * 0.20);
        int width = size.width;
        int duration = 2000;
        int height = size.height;
        int pressHeight = (int) (height * 0.80);
        new TouchAction(agent.getMobileDriver()).press(PointOption.point(startX, pressHeight)).waitAction(WaitOptions.waitOptions(Duration.ofMillis(duration))).moveTo(PointOption.point(endX, pressHeight)).release().perform();
        return new DailyPicksPage(params, agent);
    }

Body:
You can create a custom swipe method using io.appium.java_client.TouchAction

public void horizontalSwipeByPercentage(double startPercentage, double endPercentage, double anchorPercentage, AppiumDriver<MobileElement> driver) {
    Dimension size = driver.manage().window().getSize();
    int anchor = (int) (size.height * anchorPercentage);
    int startPoint = (int) (size.width * startPercentage);
    int endPoint = (int) (size.width * endPercentage);

    new TouchAction(driver)
            .press(PointOption.point(startPoint, anchor))
            .waitAction(WaitOptions.waitOptions(ofSeconds(1)))
            .moveTo(PointOption.point(endPoint, anchor))
            .release().perform();
}