问:
Integrating Windows Authentication in Docker Container ASP.NET App
I've created a container from the microsoft/aspnet repository.  I want to containerize an ASP.NET 4.x web app within IIS in which I'm able to obtain the logged in user accessing the site. I want to be able to leverage the integrated Windows authentication since this is an internal application.

I've created a transparent network to the container host.

In addition, I've setup Windows authentication on the IIS within the container.  I've read about creating a Group Managed Service Account on the container host but I've not done this yet and not sure if this is enough or I'd have to take further steps.

答:
Creating a Group Managed Service Account (gMSA) is only one of the steps you need to take in order to get Windows Authentication to work with the container. You'll also need a Credential Spec, which contains information about the gMSA you create, and will be used by the container to swap the gMSA account for the built-in accounts (LocalSystem, NetworkService, ApplicationPoolIdentity) used by your application's app pool.

Really, the minimum set of steps would be:

1) Create an AD Group that you can use to add the machines that will be used to host your containers.

```<code>PS> New-ADGroup "Container Hosts" -GroupScope Global
PS> $group = Get-ADGroup "Container Hosts"
PS> $host = Get-ADComputer "mydockerhostmachine"
PS> Add-ADGroupMember $group -Members $host
</code>```

2) Create your gMSA account to be used for your app:

```<code>PS> New-ADServiceAccount -name myapp -DNSHostName myapp.mydomain.local -ServicePrincipalNames http/myapp.mydomain.local -PrincipalsAllowedToRetrieveManagedPassword "Container Hosts"
</code>```

The value for PrincipalsAllowedToRetrieveManagePassword should be the name of the AD group you created in step 1.

3) Then, on each container host:

a. Install the Powershell Active Directory module and test to see that you're able to use the gMSA from the host:

```<code>PS> Add-WindowsFeature RSAT-AD-PowerShell
PS> Import-Module ActiveDirectory
PS> Install-AdServiceAccount myapp
PS> Test-AdServiceAccount myapp
</code>```

b. Install the Credential Spec Powershell module and create a credential spec:

```<code>PS> Invoke-WebRequest https://raw.githubusercontent.com/Microsoft/Virtualization-Documentation/live/windows-server-container-tools/ServiceAccounts/CredentialSpec.psm1 -OutFile CredentialSpec.psm1
PS> Import-Module .\CredentialSpec.psm1
PS> New-CredentialSpec -Name myapp -AccountName myapp
</code>```

c. Now, if everything was configured correctly, you can then run your container with this credential spec:

```<code>docker run --security-opt "credentialspec=file://myapp.json" -d -p
80:80 -h myapp.mydomain.local [my-image-name:tag]
</code>```

One thing to keep in mind with the above - make sure the Service Principal Name you use when creating the gMSA matches the hostname (-h argument) of the container. Otherwise, you'll have issues if your application uses Windows Authentication to access other domain resources or services (e.g., SQL Server). Also, if you are going to access other resources like SQL Server, make sure to also give the appropriate permissions to the gMSA account to those services.

Lastly, when creating your Dockerfile, don't try to assign the gMSA account directly to your app pool. Use one of the built-in accounts and let the engine swap out the account in the container for you. In other words, your app pool creation in your Dockerfile should look a little something like this:

```<code>RUN Import-Module WebAdministration; `
    New-Item -Path IIS:\AppPools\MyAppPool; `
    Set-ItemProperty -Path IIS:\AppPools\MyAppPool -Name managedRuntimeVersion -Value 'v4.0'; `
    Set-ItemProperty -Path IIS:\AppPools\MyAppPool -Name processModel -value @{identitytype='ApplicationPoolIdentity'}
</code>```

Body:
Creating a Group Managed Service Account (gMSA) is only one of the steps you need to take in order to get Windows Authentication to work with the container. You'll also need a Credential Spec, which contains information about the gMSA you create, and will be used by the container to swap the gMSA account for the built-in accounts (LocalSystem, NetworkService, ApplicationPoolIdentity) used by your application's app pool.

Really, the minimum set of steps would be:

1) Create an AD Group that you can use to add the machines that will be used to host your containers.

PS> New-ADGroup "Container Hosts" -GroupScope Global
PS> $group = Get-ADGroup "Container Hosts"
PS> $host = Get-ADComputer "mydockerhostmachine"
PS> Add-ADGroupMember $group -Members $host

2) Create your gMSA account to be used for your app:

PS> New-ADServiceAccount -name myapp -DNSHostName myapp.mydomain.local -ServicePrincipalNames http/myapp.mydomain.local -PrincipalsAllowedToRetrieveManagedPassword "Container Hosts"

The value for PrincipalsAllowedToRetrieveManagePassword should be the name of the AD group you created in step 1.

3) Then, on each container host:

a. Install the Powershell Active Directory module and test to see that you're able to use the gMSA from the host:

PS> Add-WindowsFeature RSAT-AD-PowerShell
PS> Import-Module ActiveDirectory
PS> Install-AdServiceAccount myapp
PS> Test-AdServiceAccount myapp

b. Install the Credential Spec Powershell module and create a credential spec:

PS> Invoke-WebRequest https://raw.githubusercontent.com/Microsoft/Virtualization-Documentation/live/windows-server-container-tools/ServiceAccounts/CredentialSpec.psm1 -OutFile CredentialSpec.psm1
PS> Import-Module .\CredentialSpec.psm1
PS> New-CredentialSpec -Name myapp -AccountName myapp

c. Now, if everything was configured correctly, you can then run your container with this credential spec:

docker run --security-opt "credentialspec=file://myapp.json" -d -p
80:80 -h myapp.mydomain.local [my-image-name:tag]

One thing to keep in mind with the above - make sure the Service Principal Name you use when creating the gMSA matches the hostname (-h argument) of the container. Otherwise, you'll have issues if your application uses Windows Authentication to access other domain resources or services (e.g., SQL Server). Also, if you are going to access other resources like SQL Server, make sure to also give the appropriate permissions to the gMSA account to those services.

Lastly, when creating your Dockerfile, don't try to assign the gMSA account directly to your app pool. Use one of the built-in accounts and let the engine swap out the account in the container for you. In other words, your app pool creation in your Dockerfile should look a little something like this:

RUN Import-Module WebAdministration; `
    New-Item -Path IIS:\AppPools\MyAppPool; `
    Set-ItemProperty -Path IIS:\AppPools\MyAppPool -Name managedRuntimeVersion -Value 'v4.0'; `
    Set-ItemProperty -Path IIS:\AppPools\MyAppPool -Name processModel -value @{identitytype='ApplicationPoolIdentity'}


来源: stackexchange

问:
Why do eig() and ishermitian() behave differently on different computers and MATLAB versions, and is there a way around it?
I'll first state my question and situation succinctly, then give a few details on the progress I've made so far in addressing the issues.

The function eig() behaves differently on different combinations of computer architecture and MATLAB version, in two ways I've noticed. First, the order of the eigenvalues and eigenvectors in the output is different, for the same exact code. Now, I've read in several places that MATLAB does NOT guarantee any specific order of those in the output, so one should always sort afterwards just to be safe, so even though I think this is part of a larger problem, I'll let that slide. The other way in which the behavior differs is that the eigenvalues are wrong in the cases where their order is not ascending. This is how I know they're wrong: I am dealing with complex Hermitian matrices of modest size, and the eigenvalues I get are complex, but they should be real for Hermitian matrices. On the architecture/version combinations where the order is ascending, the eigenvalues are also real as they should be. When they're complex, the imaginary parts are on the order of machine epsilon, so it's clear they're not supposed to be there at all. So, the hacky way around this is just to take the real part just in case it's complex when it shouldn't be, and then sort. A practical problem with this is that, when eig() is utilizing its routine that thinks the matrix is non-Hermitian, it takes twice as long and uses twice as much memory, presumably because of complex as opposed to real numbers. So, the questions are, why is this, and do we have a way around it?

Sorry for the long introduction. One thing I noticed is that, on the architecture/version combinations with the correct eigenvalues, it also consistently gives me the correct answer if I give a complex Hermitian matrix directly to ishermitian(). And when the eigenvalues are incorrect, ishermitian() is also incorrect. Some simple examples follow. So, my thought is that eig() is testing whether the matrix is Hermitian the same way ishermitian() does.

On the architecture/version combinations with incorrect eigenvalues, ishermitian() is still correct for something simple:

```<code>>> test=[1 2 3]+[4 5 6]*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     1
</code>```

The outer product of a complex vector and its conjugate transpose is a Hermitian matrix by definition. So we can try this again with a matrix which is around the same size as the ones I am dealing with. From the same computer:

```<code>>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     0
</code>```

And we can see the corresponding problem with eig():

```<code>>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex
</code>```

And now, identical code on a different computer:

```<code>>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     1

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1               512  double
</code>```

I've tested this on a variety of systems, and I am not noticing any rule about what architectures or versions are responsible for this, so I won't bore with all those details. But I'm curious how frequent one result is versus the other. In my experience so far, it seems about half and half. Strangely, on the same computer:

```<code>>> test2=test';
>> mat=test2*test;
>> ishermitian(mat)

ans =

     0

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex
</code>```

So if you assign the transpose to another variable, there is some precision problem like on the other computer, but if you don't, it works. Am I missing something about why this is happening, and/or is there a way around it?

答:
I was about to write something to round the numbers by some small amount, but I came across this random thing that actually seems to solve the problem everywhere:

```<code>>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     0

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex

>> mat=(mat+mat')/2;
>> ishermitian(mat)

ans =

     1

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1               512  double
</code>```

I'm now getting all the expected results everywhere, and it's taking half the time as expected, etc. Clearly mat=(mat+mat')/2; is somehow solving a rounding/precision problem, but it's not intuitive to me why this works. This operation in theory should be giving me back exactly what I already had because mat==mat' if it's Hermitian but we know mat~=mat' in this case for whatever reason. Any ideas as to why this operation is working like a small round-off?

ContentLicense: CC BY-SA 3.0

Body:
I'll first state my question and situation succinctly, then give a few details on the progress I've made so far in addressing the issues.

The function eig() behaves differently on different combinations of computer architecture and MATLAB version, in two ways I've noticed. First, the order of the eigenvalues and eigenvectors in the output is different, for the same exact code. Now, I've read in several places that MATLAB does NOT guarantee any specific order of those in the output, so one should always sort afterwards just to be safe, so even though I think this is part of a larger problem, I'll let that slide. The other way in which the behavior differs is that the eigenvalues are wrong in the cases where their order is not ascending. This is how I know they're wrong: I am dealing with complex Hermitian matrices of modest size, and the eigenvalues I get are complex, but they should be real for Hermitian matrices. On the architecture/version combinations where the order is ascending, the eigenvalues are also real as they should be. When they're complex, the imaginary parts are on the order of machine epsilon, so it's clear they're not supposed to be there at all. So, the hacky way around this is just to take the real part just in case it's complex when it shouldn't be, and then sort. A practical problem with this is that, when eig() is utilizing its routine that thinks the matrix is non-Hermitian, it takes twice as long and uses twice as much memory, presumably because of complex as opposed to real numbers. So, the questions are, why is this, and do we have a way around it?

Sorry for the long introduction. One thing I noticed is that, on the architecture/version combinations with the correct eigenvalues, it also consistently gives me the correct answer if I give a complex Hermitian matrix directly to ishermitian(). And when the eigenvalues are incorrect, ishermitian() is also incorrect. Some simple examples follow. So, my thought is that eig() is testing whether the matrix is Hermitian the same way ishermitian() does.

On the architecture/version combinations with incorrect eigenvalues, ishermitian() is still correct for something simple:

>> test=[1 2 3]+[4 5 6]*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     1

The outer product of a complex vector and its conjugate transpose is a Hermitian matrix by definition. So we can try this again with a matrix which is around the same size as the ones I am dealing with. From the same computer:

>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     0

And we can see the corresponding problem with eig():

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex

And now, identical code on a different computer:

>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     1

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1               512  double

I've tested this on a variety of systems, and I am not noticing any rule about what architectures or versions are responsible for this, so I won't bore with all those details. But I'm curious how frequent one result is versus the other. In my experience so far, it seems about half and half. Strangely, on the same computer:

>> test2=test';
>> mat=test2*test;
>> ishermitian(mat)

ans =

     0

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex

So if you assign the transpose to another variable, there is some precision problem like on the other computer, but if you don't, it works. Am I missing something about why this is happening, and/or is there a way around it?

Body:
I was about to write something to round the numbers by some small amount, but I came across this random thing that actually seems to solve the problem everywhere:

>> test=randn(1,64)+randn(1,64)*1i;
>> mat=test'*test;
>> ishermitian(mat)

ans =

     0

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1              1024  double    complex

>> mat=(mat+mat')/2;
>> ishermitian(mat)

ans =

     1

>> vals=eig(mat);
>> whos vals
  Name       Size            Bytes  Class     Attributes

  vals      64x1               512  double

I'm now getting all the expected results everywhere, and it's taking half the time as expected, etc. Clearly mat=(mat+mat')/2; is somehow solving a rounding/precision problem, but it's not intuitive to me why this works. This operation in theory should be giving me back exactly what I already had because mat==mat' if it's Hermitian but we know mat~=mat' in this case for whatever reason. Any ideas as to why this operation is working like a small round-off?


问:
Unable to launch EC2 with IAM role as a member of Administrators group
On AWS member of Administrators group is unable to launch EC2 instances with IAM role. The same user can create IAM roles and even manage users in IAM console. </p>

<p>User seems to have all possible permissions. What could be missing? </p>

答: Apparently rights were OK. The mistake was made when creating the role. For instance roles EC2 had to be selected on the first step (not the desired access). Permissions were available on the next step. </p>

Body:
On AWS member of Administrators group is unable to launch EC2 instances with IAM role. The same user can create IAM roles and even manage users in IAM console.

User seems to have all possible permissions. What could be missing?


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答: destructor of temporary B is called (b = B();), not of member b. this line can be removed at all because b is already default constructed in implicit initialization list

ContentLicense: CC BY-SA 2.5

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}


问:
Command prompt window opens and closes immediately while running powershell script
I'm trying to run a powershell script as follows:

```<code>Start-Process -FilePath "C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe" -Argument --help
</code>```

Any reason why this could be happening. Also, how to write a script so that the command prompt window does not close immediately?

答:
It looks like the program is ending. If the command just outputs the help text and ends, the window will close upon completion.

Your best bet will be to capture the output from the command and display it out to the user.

```<code>& "C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe" --help | Write-Host
</code>```

If you want to open a separate window and wait for the user to hit enter to close it, you could do something like this:

```<code>Start-Process
  -FilePath "powershell.exe"
  -ArgumentList "& 'C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe' --help; Read-Host"
</code>```

It just depends on what you're trying to achieve.

Body:
I'm trying to run a powershell script as follows:

Start-Process -FilePath "C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe" -Argument --help

Any reason why this could be happening. Also, how to write a script so that the command prompt window does not close immediately?

Body:
It looks like the program is ending. If the command just outputs the help text and ends, the window will close upon completion.

Your best bet will be to capture the output from the command and display it out to the user.

& "C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe" --help | Write-Host

If you want to open a separate window and wait for the user to hit enter to close it, you could do something like this:

Start-Process
  -FilePath "powershell.exe"
  -ArgumentList "& 'C:\svn\Services\trunk\Services.In4m.Agent.Host\bin\agent.exe' --help; Read-Host"

It just depends on what you're trying to achieve.


问:
Bars not showing when saving chart to png
me very new programmer, I having problem with saving bar chart to png, bars aren't showing up.

My Code:

```<code>import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)
width = 0.35

Start_means = (100, 50, 50)
Start_std = (2, 3, 4)

End_means = (80, 30, 30)
End_std = (3, 5, 2)

fig, ax = plt.subplots()
rects1 = ax.bar(ind, Start_means, width, color='xkcd:red', yerr=Start_std)
rects2 = ax.bar(ind+width, End_means, width, color='xkcd:black', yerr=End_std)

ax.legend((rects1[0], rects2[0]), ('Start', 'End'))
ax.set_ylabel('Available')
ax.set_title('Travel availability, by tour')
ax.set_xticks(ind + width/2)
countries = ['Italy', 'China', 'France']
ids = ['ID:12345', 'ID:13579', 'ID:24680']

xlabels = []
for i, j in zip(countries, ids):
    xlabels.append(i + '\n' + j)

ax.set_xticklabels(xlabels)

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)

plt.show()
plt.savefig('barchart.png')
</code>```

What it should look like: here
I'd like to save it as a png file, but it just comes up blank without the bars.

答:
You simply need to swap the order in which the plt.show() appears and the plt.savefig('barchart.png')

```<code>plt.savefig('barchart.png')
plt.show()
</code>```

The reason that plt.savefig doesn't work after calling show is that
  the current figure has been reset.

Source: https://stackoverflow.com/a/21884187/1577947

Body:
me very new programmer, I having problem with saving bar chart to png, bars aren't showing up.

My Code:

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)
width = 0.35

Start_means = (100, 50, 50)
Start_std = (2, 3, 4)

End_means = (80, 30, 30)
End_std = (3, 5, 2)

fig, ax = plt.subplots()
rects1 = ax.bar(ind, Start_means, width, color='xkcd:red', yerr=Start_std)
rects2 = ax.bar(ind+width, End_means, width, color='xkcd:black', yerr=End_std)

ax.legend((rects1[0], rects2[0]), ('Start', 'End'))
ax.set_ylabel('Available')
ax.set_title('Travel availability, by tour')
ax.set_xticks(ind + width/2)
countries = ['Italy', 'China', 'France']
ids = ['ID:12345', 'ID:13579', 'ID:24680']

xlabels = []
for i, j in zip(countries, ids):
    xlabels.append(i + '\n' + j)

ax.set_xticklabels(xlabels)

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)

plt.show()
plt.savefig('barchart.png')

What it should look like: here
I'd like to save it as a png file, but it just comes up blank without the bars.

Body:
You simply need to swap the order in which the plt.show() appears and the plt.savefig('barchart.png')

plt.savefig('barchart.png')
plt.show()

The reason that plt.savefig doesn't work after calling show is that
  the current figure has been reset.

Source: https://stackoverflow.com/a/21884187/1577947


答:
Add this at the end of your powershell script:

It asks user to press any key and waits until user presses a key.

```<code>Write-Host "Press any key to continue ...".
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
</code>```

Title: Command prompt window opens and closes immediately while running powershell script

Body:
Add this at the end of your powershell script:

It asks user to press any key and waits until user presses a key.

Write-Host "Press any key to continue ...".
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")


问:
How to pass for loop variable to shell function in makefile
Consider the makefile below :

```<code>CFG_DIR = /media/test/
all:
    for list in $(CFG_DIR); do \
      echo "list is $$list"; \
      for file in $(shell ls $${list}); do \
        echo "file is $$file"; \
      done \
    done
</code>```

When make is executed the below result is generated:

```<code>list is /media/test/
file is Makefile
</code>```

Instead of printing the directory listing of /media/test/ directory, directory listing of the current directory from where the make command is executed is printed.

It seems like within the shell function $$list is being evaluated to an empty value. It would be helpful if someone can point out the correct way to access for loop variables inside shell function.

答:
You can't use a shell variable in a make function.

Consider how make works: when it wants to run a recipe command FIRST it expands all the make variables and functions in the command, THEN it takes the resulting string and passes it to a shell to run, THEN it waits for the shell to exit.  If the shell exits with a success code (0) then make says "yay it worked!"  If the shell exits with a failure code (non-0) then make says "boo it failed."

Here's your recipe:

```<code>for list in $(CFG_DIR); do \
  echo "list is $$list"; \
  for file in $(shell ls $${list}); do \
    echo "file is $$file"; \
  done \
done
</code>```

So, FIRST make will expand this including all variables and functions.  You have a $(CFG_DIR) variable, and a $(shell...) function.  The variable is simply /media/test/.  When make expands the function, it sees the command to pass to the shell is ls ${list}.  So make runs:

```<code>/bin/sh -c 'ls ${list}'
</code>```

Well, unless you've set the shell variable list in your environment somewhere it's the empty string, so the shell executes ls and returns all the contents of your current directory.  Then, make substitutes that into your recipe, and hands the results to the shell to run:

```<code>/bin/sh -c 'for list in /media/test; do
  echo "list is $list";
  for file in <current-wd-files>; do
    echo "file is $file";
  done
done'
</code>```

So.  Moral of the story: in a recipe command you're already in a shell.  So you should never use the $(shell ...) make function.  It will only lead to confusion and sorrow.

You should use shell syntax since you already have a shell:

```<code>all:
      for list in $(CFG_DIR); do \
          echo "list is $$list"; \
          for file in `ls $${list}`; do \
            echo "file is $$file"; \
          done \
        done
</code>```

Body:
Consider the makefile below :

CFG_DIR = /media/test/
all:
    for list in $(CFG_DIR); do \
      echo "list is $$list"; \
      for file in $(shell ls $${list}); do \
        echo "file is $$file"; \
      done \
    done

When make is executed the below result is generated:

list is /media/test/
file is Makefile

Instead of printing the directory listing of /media/test/ directory, directory listing of the current directory from where the make command is executed is printed.

It seems like within the shell function $$list is being evaluated to an empty value. It would be helpful if someone can point out the correct way to access for loop variables inside shell function.

Body:
You can't use a shell variable in a make function.

Consider how make works: when it wants to run a recipe command FIRST it expands all the make variables and functions in the command, THEN it takes the resulting string and passes it to a shell to run, THEN it waits for the shell to exit.  If the shell exits with a success code (0) then make says "yay it worked!"  If the shell exits with a failure code (non-0) then make says "boo it failed."

Here's your recipe:

for list in $(CFG_DIR); do \
  echo "list is $$list"; \
  for file in $(shell ls $${list}); do \
    echo "file is $$file"; \
  done \
done

So, FIRST make will expand this including all variables and functions.  You have a $(CFG_DIR) variable, and a $(shell...) function.  The variable is simply /media/test/.  When make expands the function, it sees the command to pass to the shell is ls ${list}.  So make runs:

/bin/sh -c 'ls ${list}'

Well, unless you've set the shell variable list in your environment somewhere it's the empty string, so the shell executes ls and returns all the contents of your current directory.  Then, make substitutes that into your recipe, and hands the results to the shell to run:

/bin/sh -c 'for list in /media/test; do
  echo "list is $list";
  for file in <current-wd-files>; do
    echo "file is $file";
  done
done'

So.  Moral of the story: in a recipe command you're already in a shell.  So you should never use the $(shell ...) make function.  It will only lead to confusion and sorrow.

You should use shell syntax since you already have a shell:

all:
      for list in $(CFG_DIR); do \
          echo "list is $$list"; \
          for file in `ls $${list}`; do \
            echo "file is $$file"; \
          done \
        done


问:
Not opening IDE as Admin causes FileStream throw access to the path is denied exception
As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.</p>

```<code> try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

           //The following line causes an exception.

                using (var stream = new FileStream(path,
                    FileMode.CreateNew, FileAccess.Write).Encrypt())
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
                        jsonWriter.Formatting = Formatting.Indented;
                        protocolJObject.WriteTo(jsonWriter);
                    }
                }
                return ReturnCodes.Success;
            }
            catch (UnauthorizedAccessException ex)
            {
                SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
                returnValue = ReturnCodes.FileAccessDenied;
            }
</code>```

答:
The workaround would be to not write directly to the C: drive, or any other location that requires administrative access. Depending on the purpose of the file, there are usually three candidate locations:

The temp folder, for files that you don't need to save

The AppData folder, for files that your application will need and which may be different for different users

The install location for your application

You can get these folders like:

```<code>private static void Main()
{
    // Create your own file name
    var fileName = "MyAppData.txt";

    // Get temp path
    var tempPath = Path.GetTempPath();

    // Get AppData path and add a directory for your .exe
    // To use Assembly.GetExecutingAssembly, you need to add: using System.Reflection
    var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    var exeName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
    var appDataForThisExe = Path.Combine(appDataFolder, exeName);
    Directory.CreateDirectory(appDataForThisExe);

    // Get the path where this .exe lives
    var exePath = Path.GetDirectoryName(
        new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

    // Now you can join your file name with one of the above paths
    // to construct the full path to the file you want to write
    var tempFile = Path.Combine(tempPath, fileName);
    var appDatFile = Path.Combine(appDataForThisExe, fileName);
    var exePathFile = Path.Combine(exePath, fileName);

    Console.WriteLine($"Temp file path:\n {tempFile}\n");
    Console.WriteLine($"AppData file path:\n {appDatFile}\n");
    Console.WriteLine($"Exe location file path:\n {exePathFile}");

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Body:
As the title says, if I open Visual Studio IDE as Admin, FileStream works just fine. But if I don't run as admin, it gives Access to the path 'C:\\ABCD.ddthp' is denied. But if I select a folder inside the C directory it works fine. For example if the path is 'C:\ABCFolder\ABCD.ddthp' it works fine. Here is my code. Is there any work around for this or should the IDE be opened as Admin.

 try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

           //The following line causes an exception.

                using (var stream = new FileStream(path,
                    FileMode.CreateNew, FileAccess.Write).Encrypt())
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
                        jsonWriter.Formatting = Formatting.Indented;
                        protocolJObject.WriteTo(jsonWriter);
                    }
                }
                return ReturnCodes.Success;
            }
            catch (UnauthorizedAccessException ex)
            {
                SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
                returnValue = ReturnCodes.FileAccessDenied;
            }

Body:
The workaround would be to not write directly to the C: drive, or any other location that requires administrative access. Depending on the purpose of the file, there are usually three candidate locations:

The temp folder, for files that you don't need to save

The AppData folder, for files that your application will need and which may be different for different users

The install location for your application

You can get these folders like:

private static void Main()
{
    // Create your own file name
    var fileName = "MyAppData.txt";

    // Get temp path
    var tempPath = Path.GetTempPath();

    // Get AppData path and add a directory for your .exe
    // To use Assembly.GetExecutingAssembly, you need to add: using System.Reflection
    var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    var exeName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
    var appDataForThisExe = Path.Combine(appDataFolder, exeName);
    Directory.CreateDirectory(appDataForThisExe);

    // Get the path where this .exe lives
    var exePath = Path.GetDirectoryName(
        new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

    // Now you can join your file name with one of the above paths
    // to construct the full path to the file you want to write
    var tempFile = Path.Combine(tempPath, fileName);
    var appDatFile = Path.Combine(appDataForThisExe, fileName);
    var exePathFile = Path.Combine(exePath, fileName);

    Console.WriteLine($"Temp file path:\n {tempFile}\n");
    Console.WriteLine($"AppData file path:\n {appDatFile}\n");
    Console.WriteLine($"Exe location file path:\n {exePathFile}");

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output


问:
Prolog and Logic Puzzles
I seem to be having an issue with the unification of facts in Prolog, but can't confirm it. Everything looks like it should work, and I've looked up examples of solved logic puzzles using Prolog to no real effect, given the relative rarity of Prolog.

This is an extra credit assignment, so I'm unsure if it's valid, but I'm genuinely stumped on how to proceed from here

```<code>% Names
name(teo).
name(mira).
name(bruno).
name(igor).

%Food
food(sandwich).
food(pie).
food(hamburger).
food(pizza).

%Hobby
hobby(crosswords).
hobby(writing).
hobby(reading).
hobby(photography).

%Shirt Colour
shirt(white).
shirt(yellow).
shirt(blue).
shirt(red).

%Other
girl(mira).

student((Name, Food, Hobby, Shirt)) :-
    name(Name), food(Food), hobby(Hobby), shirt(Shirt).

solution(L):-
    length(L,4),
    L= [student(teo, sandwich,_,_),_,_,_],
    member(student(mira, pite, crosswords,_),L),
    member(student(girl(GirlName),_,_,white),L),
    member(student(bruno,_,_,yellow),L),
    member(student(_,hamburger,writing,_),
    L= [_, student(_,pie,_,_),_,_],
    next(student(_,pie,_,_), student(teo,_,_,_), L),
    next(student(bruno,_,_,_), student(_,pizza,_,_), L),
    next(student(_,_,_,white), student(_,pizza,_,_), L),
    member(student(igor,_,reading,_),L),
    next(student(_,_,_,blue), student(girl(GirlName),_,_,_), L).

next(A, B, Ls) :- append(_, [A,B|_], Ls).
next(A, B, Ls) :- append(_, [B,A|_], Ls).
</code>```

The issue is that it won't treat solution(L) as if it's a predicate or a rule, simply a block of text, so I can't even test if it's correct or not. I am most interested in why it won't even function.

答:
At first, I thought this girl/1 is the culprit as many have remarked. But even when removing all such occurrences your definition still fails (and after fixing that syntax error). Here is the responsible part that still fails for solution(L):

```
:- op(950, fy, *).
*(_).

solution(L) :-
   * <s>length(L,4)</s>,
   L= [student(_/*<s>teo</s>*/, sandwich,_,_),_,_,_],
   member(student(_/*<s>mira</s>*/, pite, _/*<s>crosswords</s>*/,_),L),
   * <s>member(student(girl(GirlName),_,_,white),L)</s>,
   * <s>member(student(bruno,_,_,yellow),L)</s>,
   member(student(_,hamburger,_/*<s>writing</s>*/,_),L),
   L= [_, student(_,pie,_,_)|_/*<s>[_,_]</s>*/],
   * <s>next(student(_,pie,_,_), student(teo,_,_,_), L)</s>,
   next(_<s>/*student(bruno,_,_,_)*/</s>, student(_,pizza,_,_), L),
   * <s>next(student(_,_,_,white), student(_,pizza,_,_), L)</s>,
   * <s>member(student(igor,_,reading,_),L)</s>,
   * <s>next(student(_,_,_,blue), student(girl(GirlName),_,_,_), L)</s>.

next(A, B, Ls) :- append(_, [A,B|_], Ls).
next(A, B, Ls) :- append(_, [B,A|_], Ls).
```

All the names are irrelevant, just as their hobbies. What really matters is the food!

You have only four places, but a total of five foods (sandwich, pie, pite, hamburger, pizza) - give me just one of them!

That's the nice thing in Prolog: You can do such generalizations to get a clean diagnosis.

Title: Prolog and Logic Puzzles

Body:
I seem to be having an issue with the unification of facts in Prolog, but can't confirm it. Everything looks like it should work, and I've looked up examples of solved logic puzzles using Prolog to no real effect, given the relative rarity of Prolog.

This is an extra credit assignment, so I'm unsure if it's valid, but I'm genuinely stumped on how to proceed from here

% Names
name(teo).
name(mira).
name(bruno).
name(igor).

%Food
food(sandwich).
food(pie).
food(hamburger).
food(pizza).

%Hobby
hobby(crosswords).
hobby(writing).
hobby(reading).
hobby(photography).

%Shirt Colour
shirt(white).
shirt(yellow).
shirt(blue).
shirt(red).

%Other
girl(mira).

student((Name, Food, Hobby, Shirt)) :-
    name(Name), food(Food), hobby(Hobby), shirt(Shirt).

solution(L):-
    length(L,4),
    L= [student(teo, sandwich,_,_),_,_,_],
    member(student(mira, pite, crosswords,_),L),
    member(student(girl(GirlName),_,_,white),L),
    member(student(bruno,_,_,yellow),L),
    member(student(_,hamburger,writing,_),
    L= [_, student(_,pie,_,_),_,_],
    next(student(_,pie,_,_), student(teo,_,_,_), L),
    next(student(bruno,_,_,_), student(_,pizza,_,_), L),
    next(student(_,_,_,white), student(_,pizza,_,_), L),
    member(student(igor,_,reading,_),L),
    next(student(_,_,_,blue), student(girl(GirlName),_,_,_), L).

next(A, B, Ls) :- append(_, [A,B|_], Ls).
next(A, B, Ls) :- append(_, [B,A|_], Ls).

The issue is that it won't treat solution(L) as if it's a predicate or a rule, simply a block of text, so I can't even test if it's correct or not. I am most interested in why it won't even function.

Body:
At first, I thought this girl/1 is the culprit as many have remarked. But even when removing all such occurrences your definition still fails (and after fixing that syntax error). Here is the responsible part that still fails for solution(L):

:- op(950, fy, *).
*(_).

solution(L) :-
   * <s>length(L,4)</s>,
   L= [student(_/*<s>teo</s>*/, sandwich,_,_),_,_,_],
   member(student(_/*<s>mira</s>*/, pite, _/*<s>crosswords</s>*/,_),L),
   * <s>member(student(girl(GirlName),_,_,white),L)</s>,
   * <s>member(student(bruno,_,_,yellow),L)</s>,
   member(student(_,hamburger,_/*<s>writing</s>*/,_),L),
   L= [_, student(_,pie,_,_)|_/*<s>[_,_]</s>*/],
   * <s>next(student(_,pie,_,_), student(teo,_,_,_), L)</s>,
   next(_<s>/*student(bruno,_,_,_)*/</s>, student(_,pizza,_,_), L),
   * <s>next(student(_,_,_,white), student(_,pizza,_,_), L)</s>,
   * <s>member(student(igor,_,reading,_),L)</s>,
   * <s>next(student(_,_,_,blue), student(girl(GirlName),_,_,_), L)</s>.

next(A, B, Ls) :- append(_, [A,B|_], Ls).
next(A, B, Ls) :- append(_, [B,A|_], Ls).

All the names are irrelevant, just as their hobbies. What really matters is the food!

You have only four places, but a total of five foods (sandwich, pie, pite, hamburger, pizza) - give me just one of them!

That's the nice thing in Prolog: You can do such generalizations to get a clean diagnosis.


问:
How do I tell programatically if I am running under Medium Trust?
In C# how do I tell if my assembly is running under medium trust in asp.net?  Is there something similar to Debugger.IsAttached for this?</p>

答:
This should do the trick:

Get current ASP.NET Trust Level programmatically


问:
How to detect ring tone in freeswitch dialplan?
After dialing to a remote callcenter and getting past the IVR, my customer's staff usually end up waiting a long time for an agent to pickup, while listening to hold music. I am considering a possibility where they can transfer the call to a dialplan on their local freeswitch, which awaits the ringtone of the remote agent. Once the dialplan detects that the agent phone ringing, it should forward the call back to the original caller.

There are not many examples for tone_detect application. Assuming it is US ring tone, how should the tone specification look like?

```<code><action application="tone_detect" data="ring 440,480 r 0 transfer '1000 XML default' 2">
</code>```

I doubt the above will work because, US ring tone plays 440+480 Hz on for 2000ms off for 4000ms. I am not sure how I can specify that.

答: That's a great idea.  A call metaqueue.  The tone detect, if it worked wouldn't be foolproof as sometimes the bridge won't get ring back.  You might consider monitoring energy level as well to wait for a period of silence short energy then again silence (a hello sequence). Your arguments for the command - Detect Tone look correct for the old syntax, but you might update to the newer preferred behavior also herein.</p>

Body:
After dialing to a remote callcenter and getting past the IVR, my customer's staff usually end up waiting a long time for an agent to pickup, while listening to hold music. I am considering a possibility where they can transfer the call to a dialplan on their local freeswitch, which awaits the ringtone of the remote agent. Once the dialplan detects that the agent phone ringing, it should forward the call back to the original caller.

There are not many examples for tone_detect application. Assuming it is US ring tone, how should the tone specification look like?

<action application="tone_detect" data="ring 440,480 r 0 transfer '1000 XML default' 2">

I doubt the above will work because, US ring tone plays 440+480 Hz on for 2000ms off for 4000ms. I am not sure how I can specify that.


问:
regex in R to distinguish male/female in strings
I have strings with descriptions of gender that I need to sort out. For instance, if I have the following,

```<code>string1 = "FEMALE AND FEMALE"
string2 = "FEMALE AND MALE"
</code>```

I need to change string1 to say "MULTIPLE FEMALES", and string2 to say "BOTH MALE AND FEMALE".

Using gsub, I am having trouble writing a substitution that recognizes string2 as different from string1, because MALE is nested in FEMALE. Using "YEP" as a confirmation string first, I have tried the following with no luck,

```<code>gsub(".*FEMALE.*MALE.*", "YEP", string1)
gsub(".*FEMALE.*[^M]ALE.*", "YEP", string1)
gsub(".*FEMALE.*[^\b]MALE.*", "YEP", string1)
gsub(".*FEMALE.*(^\bMALE).*", "YEP", string1)
gsub(".*FEMALE.*MALE.*", "YEP", string2)
gsub(".*FEMALE.*[^M]ALE.*", "YEP", string2)
gsub(".*FEMALE.*[^\b]MALE.*", "YEP", string2)
gsub(".*FEMALE.*(^\bMALE).*", "YEP", string2)
</code>```

I need to account for sequence of wildcard because not all strings will show as "FEMALE AND FEMALE" or "FEMALE AND MALE", sometimes they show up as "1 FEMALE 12 MALES" or "B FEMALE WITH 2X W FEMALE", etc.

Any ideas on how to deal with nested strings using regex?

答:
Ok, I figured this out right after I posted.

Running gsub(".*FEMALE.*\\b(M)ALE.*", "YEP", string1) results in "FEMALE AND FEMALE", whereas gsub(".*FEMALE.*\\b(M)ALE.*", "YEP", string2) results in "YEP". So this works.

Body:
I have strings with descriptions of gender that I need to sort out. For instance, if I have the following,

string1 = "FEMALE AND FEMALE"
string2 = "FEMALE AND MALE"

I need to change string1 to say "MULTIPLE FEMALES", and string2 to say "BOTH MALE AND FEMALE".

Using gsub, I am having trouble writing a substitution that recognizes string2 as different from string1, because MALE is nested in FEMALE. Using "YEP" as a confirmation string first, I have tried the following with no luck,

gsub(".*FEMALE.*MALE.*", "YEP", string1)
gsub(".*FEMALE.*[^M]ALE.*", "YEP", string1)
gsub(".*FEMALE.*[^\b]MALE.*", "YEP", string1)
gsub(".*FEMALE.*(^\bMALE).*", "YEP", string1)
gsub(".*FEMALE.*MALE.*", "YEP", string2)
gsub(".*FEMALE.*[^M]ALE.*", "YEP", string2)
gsub(".*FEMALE.*[^\b]MALE.*", "YEP", string2)
gsub(".*FEMALE.*(^\bMALE).*", "YEP", string2)

I need to account for sequence of wildcard because not all strings will show as "FEMALE AND FEMALE" or "FEMALE AND MALE", sometimes they show up as "1 FEMALE 12 MALES" or "B FEMALE WITH 2X W FEMALE", etc.

Any ideas on how to deal with nested strings using regex?


问:
What is "this" in a java method
In an example like the one bellow :

```<code> public boolean checkLocationPermission() {
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
</code>```

What does this exactly point to. I understand that it is pointing to the current context in which the method is being implemented. But i'm not sure what is the scope of that context. Is it always reffering to the class the method is in?

答: this is a reference for current instance of the object. in this piece of code it means that this references to current instance of the activity and as a result reference to the context of that activity

Title: What is "this" in a java method

Body:
In an example like the one bellow :

 public boolean checkLocationPermission() {
        if(ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){

What does this exactly point to. I understand that it is pointing to the current context in which the method is being implemented. But i'm not sure what is the scope of that context. Is it always reffering to the class the method is in?


问:
select rows in a dataframe in python based on two criteria
Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it?

```<code>    id  x  y  z
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2
</code>```

...

答:
You can do the following:

```<code>import pandas as pd

df = pd.read_csv('data.csv')
df2 = df[(df.y == 2) | (df.z == 2)]

print(df2)
</code>```

Results:

```<code>   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2
</code>```

Body:
Based on the dataframe (1) below, I wish to create a dataframe (2) where either y or z is equal to 2. Is there a way to do this conveniently?

And if I were to create a dataframe (3) that only contains rows from dataframe (1) but not dataframe (2), how should I approach it?

    id  x  y  z
    0 324  1  2
    1 213  1  1
    2 529  2  1
    3 347  3  2
    4 109  2  2

...

Body:
You can do the following:

import pandas as pd

df = pd.read_csv('data.csv')
df2 = df[(df.y == 2) | (df.z == 2)]

print(df2)

Results:

   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2


问:
XPath / XQuery: find text in a node, but ignoring content of specific descendant elements
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

```<code><document>
   <p n="1">My text starts here/</p>
   <p n="2">Then it goes on there<footnote>It's not a very long text!</footnote></p>
</document>
</code>```

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)

答:
```<code>//p[(.//text() except .//footnote//text())[contains(., 'text')]]
</code>```

Body:
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

<document>

My text starts here/

Then it goes on there<footnote>It's not a very long text!</footnote>

</document>

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)


问:
django rest framework same route, different
i'm using django rest framework to build an api, here is my problem

```<code>url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),
</code>```

```<code>    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )
</code>```

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

答:
urls.py

```<code>url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveUpdateView.as_view(), name='profiles-detail-update'),
</code>```

views.py

```<code>from rest_framework.generics import RetrieveUpdateAPIView

class ProfileRetrieveUpdateView(RetrieveUpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

    def get_permissions(self):
        if self.request.method == "GET":
            return []
        else:
            return [IsAuthenticated()]
</code>```

Body:
i'm using django rest framework to build an api, here is my problem

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),

    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

Body:
urls.py

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveUpdateView.as_view(), name='profiles-detail-update'),

views.py

from rest_framework.generics import RetrieveUpdateAPIView

class ProfileRetrieveUpdateView(RetrieveUpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

    def get_permissions(self):
        if self.request.method == "GET":
            return []
        else:
            return [IsAuthenticated()]


问:
To change the value of an empty variable
I have a loop like this:

```<code>[centers, radii]=imfindcircles() %find circles in the image
if isnan(centers)==1 %if centres is empty
    centers='NA'; % assign centres a NA
else
    centers=centers;
end
</code>```

What I want to do is:

when no circles found and centers=[], I want to assign centres a value (could be 'NA' or 0).

if some circles found, then centres remains the same array.

The goal of this loop is to assign centres some value so that I can save it into a .xls file even if there is no circles found.

But my problem is after this loop, even if centers=[], centres will not change its value. This means this loop doesn't work at all. So could somebody check for me where is wrong?

答:
```<code>[centers,radii] = imfindcircles() %find circles in the image

if (isempty(centers)) %if centres is empty
    centers(1) = NaN; % assign centres a NA
end
</code>```

A better theoretical approach would be, IMHO:

```<code>if (isempty(centers))
    % write a dummy XLS file
else
    % write your values to XLS file
end
</code>```

Body:
I have a loop like this:

[centers, radii]=imfindcircles() %find circles in the image
if isnan(centers)==1 %if centres is empty
    centers='NA'; % assign centres a NA
else
    centers=centers;
end

What I want to do is:

when no circles found and centers=[], I want to assign centres a value (could be 'NA' or 0).

if some circles found, then centres remains the same array.

The goal of this loop is to assign centres some value so that I can save it into a .xls file even if there is no circles found.

But my problem is after this loop, even if centers=[], centres will not change its value. This means this loop doesn't work at all. So could somebody check for me where is wrong?

Body:
[centers,radii] = imfindcircles() %find circles in the image

if (isempty(centers)) %if centres is empty
    centers(1) = NaN; % assign centres a NA
end

A better theoretical approach would be, IMHO:

if (isempty(centers))
    % write a dummy XLS file
else
    % write your values to XLS file
end


问:
Spark dataframe checking equality and filtering
How do I filter column with particular value?

This works fine >

```<code>scala> dataframe.filter("postalCode > 900").count()
</code>```

but == fails

```<code>scala> dataframe.filter("postalCode == 900").count()
java.lang.RuntimeException: [1.13] failure: identifier expected

postalCode == 900 ##Error line
</code>```

I know I am missing something obvious but I cant figure out. I checked API doc and SO for same. Also, tried giving ===

Body:
How do I filter column with particular value?

This works fine >

scala> dataframe.filter("postalCode > 900").count()

but == fails

scala> dataframe.filter("postalCode == 900").count()
java.lang.RuntimeException: [1.13] failure: identifier expected

postalCode == 900 ##Error line

I know I am missing something obvious but I cant figure out. I checked API doc and SO for same. Also, tried giving ===

Body:
You could use "===" operator with filter/where as below. basically where is alias of filter.

using the same example by zero323.

val df = sc.parallelize(Seq(("foo", 900), ("bar", 100))).toDF("k", "postalCode")

df.where($"postalCode" === 900).show

+---+----------+
|  k|postalCode|
+---+----------+
|foo|       900|
+---+----------+

df.filter($"postalCode" === 900).show

+---+----------+
|  k|postalCode|
+---+----------+
|foo|       900|
+---+----------+

df.filter(df("postalCode") === 900).show

+---+----------+
|  k|postalCode|
+---+----------+
|foo|       900|
+---+----------+


问:
ReactJS - Lifting state up vs keeping a local state
At my company we're migrating the front-end of a web application to ReactJS.
We are working with create-react-app (updated to v16), without Redux.
Now I'm stuck on a page which structure can be simplified by the following image:

The data displayed by the three components (SearchableList, SelectableList and Map) is retrieved with the same backend request in the componentDidMount() method of MainContainer. The result of this request is then stored in the state of MainContainer and has a structure more or less like this:

```<code>state.allData = {
  left: {
    data: [ ... ]
  },
  right: {
    data: [ ... ],
    pins: [ ... ]
  }
}
</code>```

LeftContainer receives as prop state.allData.left from MainContainer and passes props.left.data to SearchableList, once again as prop.

RightContainer receives as prop state.allData.right from MainContainer and passes props.right.data to SelectableList and props.right.pins to Map.

SelectableList displays a checkbox to allow actions on its items. Whenever an action occur on an item of SelectableList component it may have side effects on Map pins.

I've decided to store in the state of RightContainer a list that keeps all the ids of items displayed by SelectableList; this list is passed as props to both SelectableList and Map. Then I pass to SelectableList a callback, that whenever a selection is made updates the list of ids inside RightContainer; new props arrive in both SelectableList and Map, and so render() is called in both components.

It works fine and helps to keep everything that may happen to SelectableList and Map inside RightContainer, but I'm asking if this is correct for the lifting-state-up and single-source-of-truth concepts.

As feasible alternative I thought of adding a _selected property to each item in state.right.data in MainContainer and pass the select callback three levels down to SelectableList, handling all the possible actions in MainContainer. But as soon as a selection event occurs this will eventually force the loading of LeftContainer and RightContainer, introducing the need of implementing logics like shouldComponentUpdate() to avoid useless render() especially in LeftContainer.

Which is / could be the best solution to optimise this page from an architectural and performance point of view?

Below you have an extract of my components to help you understand the situation.

MainContainer.js

```<code>class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      allData: {}
    };
  }

  componentDidMount() {
    fetch( ... )
      .then((res) => {
        this.setState({
          allData: res
        });
      });
  }

  render() {
    return (
      <div className="main-container">
        <LeftContainer left={state.allData.left} />
        <RightContainer right={state.allData.right} />
      </div>
    );
  }
}

export default MainContainer;
</code>```

RightContainer.js

```<code>class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [ ... ]
    };
  }

  onDataSelection(e) {
    const itemId = e.target.id;
    // ... handle itemId and selectedItems ...
  }

  render() {
    return (
      <div className="main-container">
        <SelectableList
          data={props.right.data}
          onDataSelection={e => this.onDataSelection(e)}
          selectedItems={this.state.selectedItems}
        />
        <Map
          pins={props.right.pins}
          selectedItems={this.state.selectedItems}
        />
      </div>
    );
  }
}

export default RightContainer;
</code>```

Thanks in advance!

答:
My honest advice on this. From experience is:

Redux is simple. It's easy to understand and scale BUT you should use Redux for some specific use cases.

Since Redux encapsulates your App you can think of storing stuff like:

current app locale

current authenticated user

current token from somewhere

Stuff that you would need on a global scale. react-redux even allows for a @connect decorator on components. So like:

```<code>@connect(state => ({
   locale: state.locale,
   currentUser: state.currentUser
}))
class App extends React.Component
</code>```

Those are all passed down as props and connect can be used anywhere on the App. Although I recommend just passing down the global props with the spread operator

```<code><Navbar {...this.props} />
</code>```

All other components (or "pages") inside your app can do their own encapsulated state. For example the Users page can do it's own thing.

```<code>class Users extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loadingUsers: false,
      users: [],
    };
  }
......
</code>```

You would access locale and currentUser through props because they were passed down from the Container components.

This approach I've done it multiple times and it works.

But, since you wanted to really consolidate the knowledge of React first, before doing Redux you can just store your state on the top-level component and pass it down to the children.

Downsides:

You're gonna have to keep passing them down into inner level components

To update state from the inner level components you're gonna have to pass the function that updates the state.

These downsides are a little boring and cumbersome to manage. That's why Redux was built.

Hope I helped. good luck

Body:
At my company we're migrating the front-end of a web application to ReactJS.
We are working with create-react-app (updated to v16), without Redux.
Now I'm stuck on a page which structure can be simplified by the following image:

The data displayed by the three components (SearchableList, SelectableList and Map) is retrieved with the same backend request in the componentDidMount() method of MainContainer. The result of this request is then stored in the state of MainContainer and has a structure more or less like this:

state.allData = {
  left: {
    data: [ ... ]
  },
  right: {
    data: [ ... ],
    pins: [ ... ]
  }
}

LeftContainer receives as prop state.allData.left from MainContainer and passes props.left.data to SearchableList, once again as prop.

RightContainer receives as prop state.allData.right from MainContainer and passes props.right.data to SelectableList and props.right.pins to Map.

SelectableList displays a checkbox to allow actions on its items. Whenever an action occur on an item of SelectableList component it may have side effects on Map pins.

I've decided to store in the state of RightContainer a list that keeps all the ids of items displayed by SelectableList; this list is passed as props to both SelectableList and Map. Then I pass to SelectableList a callback, that whenever a selection is made updates the list of ids inside RightContainer; new props arrive in both SelectableList and Map, and so render() is called in both components.

It works fine and helps to keep everything that may happen to SelectableList and Map inside RightContainer, but I'm asking if this is correct for the lifting-state-up and single-source-of-truth concepts.

As feasible alternative I thought of adding a _selected property to each item in state.right.data in MainContainer and pass the select callback three levels down to SelectableList, handling all the possible actions in MainContainer. But as soon as a selection event occurs this will eventually force the loading of LeftContainer and RightContainer, introducing the need of implementing logics like shouldComponentUpdate() to avoid useless render() especially in LeftContainer.

Which is / could be the best solution to optimise this page from an architectural and performance point of view?

Below you have an extract of my components to help you understand the situation.

MainContainer.js

class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      allData: {}
    };
  }

  componentDidMount() {
    fetch( ... )
      .then((res) => {
        this.setState({
          allData: res
        });
      });
  }

  render() {
    return (

        <LeftContainer left={state.allData.left} />
        <RightContainer right={state.allData.right} />

    );
  }
}

export default MainContainer;

RightContainer.js

class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [ ... ]
    };
  }

  onDataSelection(e) {
    const itemId = e.target.id;
    // ... handle itemId and selectedItems ...
  }

  render() {
    return (

        <SelectableList
          data={props.right.data}
          onDataSelection={e => this.onDataSelection(e)}
          selectedItems={this.state.selectedItems}
        />
        <Map
          pins={props.right.pins}
          selectedItems={this.state.selectedItems}
        />

    );
  }
}

export default RightContainer;

Thanks in advance!

Body:
My honest advice on this. From experience is:

Redux is simple. It's easy to understand and scale BUT you should use Redux for some specific use cases.

Since Redux encapsulates your App you can think of storing stuff like:

current app locale

current authenticated user

current token from somewhere

Stuff that you would need on a global scale. react-redux even allows for a @connect decorator on components. So like:

@connect(state => ({
   locale: state.locale,
   currentUser: state.currentUser
}))
class App extends React.Component

Those are all passed down as props and connect can be used anywhere on the App. Although I recommend just passing down the global props with the spread operator

<Navbar {...this.props} />

All other components (or "pages") inside your app can do their own encapsulated state. For example the Users page can do it's own thing.

class Users extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loadingUsers: false,
      users: [],
    };
  }
......

You would access locale and currentUser through props because they were passed down from the Container components.

This approach I've done it multiple times and it works.

But, since you wanted to really consolidate the knowledge of React first, before doing Redux you can just store your state on the top-level component and pass it down to the children.

Downsides:

You're gonna have to keep passing them down into inner level components

To update state from the inner level components you're gonna have to pass the function that updates the state.

These downsides are a little boring and cumbersome to manage. That's why Redux was built.

Hope I helped. good luck


问:
Botan library and 'compressed' public keys
Does Botan support serialisation / deserialisation of a 'compressed' representation of an EC public key? (only X coordinate of the point on EC + sign). Any example?</p>

答:
Yes. Botan compresses ECC points by default eg when serializing a public key to X.509 format. It accepts compressed or uncompressed points. Given an ECC point, you can convert it to an octet string in compressed form with

const PointGFp& pt = my_ecc_key.public_point();
secure_vector<uint8_t> uncompressed_point = EC2OSP(pt, PointGFp::UNCOMPRESSED);
secure_vector<uint8_t> compressed_point = EC2OSP(pt, PointGFp::COMPRESSED);


问:
Android studio: changing imageview weekly
I am trying to obtain create an app on Android Studio that displays an image on the main activity.  This image will change weekly.  I understand that this cannot be done by updating the application on a weekly basis.  How can I display an image and change it on a weekly basis without having to re-release the application?</p>

答:
You can stablish a date for each image.
You try this:

Get the date with

final Calendar calendar = Calendar.getInstance();
   String dat=new SimpleDateFormat("EEE MMM dd hh:mm:ss 'GMT'Z
   yyyy").format(calendar.getTime())
   System.out.println(dat);//"Sat Jul 23 11:03:36 GMT+01:00 2017"

// or the format that you want (in your on create)
// 2. Stablish the dates for example:

`date1= //your date
 date2= //your date
 date3= //your date
 date4= //your date
  .
  .

//3. In your onCreate
  if(dat>= date1 &&
   iv.setImageResource(R.drawable.image_name);
   }
   elseif (dat >= date2 && < date3)
   {
   ImageView iv= (ImageView)findViewById(v);

   iv.setImageResource(R.drawable.image_name2);
   }`


问:
Sampling with weight for 1 number
I want to sample from a big pool of numbers e.g. -2000:5000.

I would like thought to set the weight for a certain number to 80%.

Everything other possibility should be equal for every other number.

Doing this for a small sample is easy:

sample(-2:2, 10, replace = TRUE, prob=c(0.05, 0.05, 0.80, 0.05, 0.05))

this would output:

[1]  0  0  0  0  0 -1  0  0  0  0

How can I do this for a big range of numbers?

答:
Just manipulate your probability vector pragmatically. So you have

```<code>values <- -2:2
special_value <- 0
</code>```

Then you can do

```<code>probs <- rep(1, length(values))
probs[values==special_value] <- (length(values )-1)*.8/(1-.8)
</code>```

Then use

```<code>sample(values, 10, replace = TRUE, prob=probs)
</code>```

Title: Sampling with weight for 1 number

Body:
Just manipulate your probability vector pragmatically. So you have

values <- -2:2
special_value <- 0

Then you can do

probs <- rep(1, length(values))
probs[values==special_value] <- (length(values )-1)*.8/(1-.8)

Then use

sample(values, 10, replace = TRUE, prob=probs)


Title: select rows in a dataframe in python based on two criteria

Body:
df[df[['y','z']].eq(2).any(1)]
Out[1205]:
   id    x  y  z
0   0  324  1  2
2   2  529  2  1
3   3  347  3  2
4   4  109  2  2


问:
How does EMR handle an s3 bucket for input and output?
I'm spinning up an EMR cluster and I've created the buckets specified in the EMR docs, but how should I upload data and read from it?  In my spark submit step I say the script name using s3://myclusterbucket/scripts/script.py Is output not automatically uploaded to s3?  How are dependencies handled? I've tried using the pyfiles pointing to a dependency zip inside the s3 bucket, but keep getting back 'file not found'

答:
MapReduce or Tez jobs in EMR can access S3 directly because of EMRFS (an AWS propriertary Hadoop filesystem implementation based on S3), e.g., in Apache Pig you can do
loaded_data = LOAD 's3://mybucket/myfile.txt' USING PigStorage();

Not sure about Python-based Spark jobs. But one solution is to first copy the objects from S3 to the EMR HDFS, and then process them there.

There are multiple ways of doing the copy:

Use hadoop fs commands to copy objects from S3 to the EMR HDFS (and vice versa), e.g., hadoop fs -cp s3://mybucket/myobject hdfs://mypath_on_emr_hdfs

Use s3-dist-cp to copy objects from S3 to the EMR HDFS (and vice versa) http://docs.aws.amazon.com/emr/latest/ReleaseGuide/UsingEMR_s3distcp.html

You can also use awscli (or hadoop fs -copyToLocal) to copy objects from S3 to the EMR master instance local disk (and vice versa), e.g., aws s3 cp s3://mybucket/myobject .


问:
C# - Marshall & Pass void pointer to C function calling from C#
I am implementing c#.net wrapper for C-based Library. currently, working on function with passing A void pointer, which will set value.

NOTE : void pointer can take different data type depending on Enum.

Objective: to pass void pointer and set value

I checked many solutions to implement and finally came to following state :

The C-dll function:

```<code>int function_call(enum a, void * var);
</code>```

The C function call code:

```<code>char name[255];
name = "asd";
function_call(enum a, &name);
</code>```

The C# wrapper code:

```<code>[DllImport("mylibrary.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int function_call(enum a, IntPtr var);
</code>```

The C# function call code:

```<code>IntPtr name;
string val = "asd";
name = Marshal.StringToHGolbalUni(val);
int ret = function_call(Enum_type, name);
</code>```

By this method it only sets First character a from the input asd.

I have already checked "Duplicate" questions but doesnt solve the issue:

c++ - What is void* in C#

How to declare void pointer in C#

void* in C#

答:
I would treat your void * as a char * and use

```<code>[MarshalAs(UnmanagedType.LPStr)] StringBuilder var
</code>```

instead of IntPtr

You should find it works as expected, but take care with size of the char array that your C function expects.  Perhaps an explicit size in your declaration of your StringBuilder variable before you call the C function like this:

```<code>StringBuilder newvar= new StringBuilder(512);
</code>```

Good link explaining the circumstances where StringBuilder is used instead of String or IntPtr is explained here - Thanks Amy for the link

Body:
I am implementing c#.net wrapper for C-based Library. currently, working on function with passing A void pointer, which will set value.

NOTE : void pointer can take different data type depending on Enum.

Objective: to pass void pointer and set value

I checked many solutions to implement and finally came to following state :

The C-dll function:

int function_call(enum a, void * var);

The C function call code:

char name[255];
name = "asd";
function_call(enum a, &name);

The C# wrapper code:

[DllImport("mylibrary.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int function_call(enum a, IntPtr var);

The C# function call code:

IntPtr name;
string val = "asd";
name = Marshal.StringToHGolbalUni(val);
int ret = function_call(Enum_type, name);

By this method it only sets First character a from the input asd.

I have already checked "Duplicate" questions but doesnt solve the issue:

c++ - What is void* in C#

How to declare void pointer in C#

void* in C#

Body:
I would treat your void * as a char * and use

[MarshalAs(UnmanagedType.LPStr)] StringBuilder var

instead of IntPtr

You should find it works as expected, but take care with size of the char array that your C function expects.  Perhaps an explicit size in your declaration of your StringBuilder variable before you call the C function like this:

StringBuilder newvar= new StringBuilder(512);

Good link explaining the circumstances where StringBuilder is used instead of String or IntPtr is explained here - Thanks Amy for the link


问:
Eclipse neon extra space for minimize/restore editor buttons
After upgrading my eclipse to neon from juno, I noticed that I am getting extra space for the min/restore buttons for the c/c++ editor.

looked like this in juno

looks like this in neon

it doesnt look like much in the screenshots but it adds a tabs heights to the whole window. Anyway to get rid of it, or make it smaller like in Juno ?

答:
You can add the following style in the .css file that is active for you. For example, add the following to e4-dark.css for eclipse oxygen's dark style.</p>

```<code>#org-eclipse-ui-editorss {
    swt-tab-height: 5px;
    padding: 0px 2px 2px;
}
</code>```

Body:
You can add the following style in the .css file that is active for you. For example, add the following to e4-dark.css for eclipse oxygen's dark style.

#org-eclipse-ui-editorss {
    swt-tab-height: 5px;
    padding: 0px 2px 2px;
}


问:
Magento - Customer Address Country Dropdown Issue
I'm using Magento CE 1.7.0.2, having recently upgraded from 1.4.2.0. And when editing/creating a customer address in the backend, the country dropdown field is blank - with no possible options to select. Neither does it work on the frontend address dropdown.

Any ideas what's caused this, the only code hint I could find is: "this.defaultCountries = [false,false];" in the JS on the page, whereas on a new Magento install (same version, same default country) it shows: this.defaultCountries = ['GB','GB'];

答: Search on table 'core_config_data' in field 'path' remove a row with value 'general' without anything more, if it exist. then It will works</p>


问:
Selenium Javascript Webdriver: how to setup Firefox profile to accept selfsigned certificate
I'm trying to use selenium-webdriver to test a site that uses a self-signed certificate.

To pass the tests under Firefox, it is required to use a profile that tells Firefox to accept the self-signed certificate.

I was able to use a profile created using firefox -ProfileManager. However, I'm not able to use a profile that is created programmatically.

Can anybody tell what I'm missing here?

Here is the javascript program that uses the profile created by firefox -ProfileManager:

```<code>var webdriver = require('selenium-webdriver');
var firefox   = require('selenium-webdriver/firefox');

var profile   = new firefox.Profile('/path/to/firefox/profile');
var browser   = new firefox.Driver(new firefox.Options().setProfile(profile));

browser.get('https://self-signed.badssl.com/');
browser.quit();
</code>```

And here is the javascript program that uses the profile created by code:

```<code>var webdriver = require('selenium-webdriver');
var firefox   = require('selenium-webdriver/firefox');

var profile   = new firefox.Profile();
profile.setAcceptUntrustedCerts(true);
profile.setAssumeUntrustedCertIssuer(false); // `true` didn't work too
var browser   = new firefox.Driver(new firefox.Options().setProfile(profile));

browser.get('https://self-signed.badssl.com/');
browser.quit();
</code>```

The error I'm getting with the second program is as follows:

```<code>$ node test-firefox-profile.js
/user/ws/node_modules/selenium-webdriver/lib/promise.js:654
    throw error;
    ^

WebDriverError: Error loading page
    at WebDriverError (/user/ws/node_modules/selenium-webdriver/lib/error.js:27:10)
    at Object.throwDecodedError (/user/ws/node_modules/selenium-webdriver/lib/error.js:477:11)
    at parseHttpResponse (/user/ws/node_modules/selenium-webdriver/lib/http.js:386:15)
    at /user/ws/node_modules/selenium-webdriver/lib/http.js:328:11
    at process._tickCallback (node.js:369:9)
From: Task: WebDriver.navigate().to(https://self-signed.badssl.com/)
    at Driver.schedule (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:414:17)
    at Navigation.to (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:1042:25)
    at Driver.get (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:832:28)
    at Object.<anonymous> (/user/ws/test-firefox-profile.js:9:9)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
</code>```

答:
This worked for me.
driver = new webdriver.Builder().withCapabilities({'browserName': 'firefox', acceptSslCerts: true, acceptInsecureCerts: true});

Body:
I'm trying to use selenium-webdriver to test a site that uses a self-signed certificate.

To pass the tests under Firefox, it is required to use a profile that tells Firefox to accept the self-signed certificate.

I was able to use a profile created using firefox -ProfileManager. However, I'm not able to use a profile that is created programmatically.

Can anybody tell what I'm missing here?

Here is the javascript program that uses the profile created by firefox -ProfileManager:

var webdriver = require('selenium-webdriver');
var firefox   = require('selenium-webdriver/firefox');

var profile   = new firefox.Profile('/path/to/firefox/profile');
var browser   = new firefox.Driver(new firefox.Options().setProfile(profile));

browser.get('https://self-signed.badssl.com/');
browser.quit();

And here is the javascript program that uses the profile created by code:

var webdriver = require('selenium-webdriver');
var firefox   = require('selenium-webdriver/firefox');

var profile   = new firefox.Profile();
profile.setAcceptUntrustedCerts(true);
profile.setAssumeUntrustedCertIssuer(false); // `true` didn't work too
var browser   = new firefox.Driver(new firefox.Options().setProfile(profile));

browser.get('https://self-signed.badssl.com/');
browser.quit();

The error I'm getting with the second program is as follows:

$ node test-firefox-profile.js
/user/ws/node_modules/selenium-webdriver/lib/promise.js:654
    throw error;
    ^

WebDriverError: Error loading page
    at WebDriverError (/user/ws/node_modules/selenium-webdriver/lib/error.js:27:10)
    at Object.throwDecodedError (/user/ws/node_modules/selenium-webdriver/lib/error.js:477:11)
    at parseHttpResponse (/user/ws/node_modules/selenium-webdriver/lib/http.js:386:15)
    at /user/ws/node_modules/selenium-webdriver/lib/http.js:328:11
    at process._tickCallback (node.js:369:9)
From: Task: WebDriver.navigate().to(https://self-signed.badssl.com/)
    at Driver.schedule (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:414:17)
    at Navigation.to (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:1042:25)
    at Driver.get (/user/ws/node_modules/selenium-webdriver/lib/webdriver.js:832:28)
    at Object.<anonymous> (/user/ws/test-firefox-profile.js:9:9)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)


问:
How to prevent tableview section head from sticking while scrolling?
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}
</code>```

答:
Some possible solutions :

If you have just one section then set the Tableview Header property to the UIView you want to set as the Section Header.

If you have multiple sections, change the row count for each section to (number of rows for that section + 1) and make the row at 0th index to be a header. Some hand coding will be required.

Change your tableview to grouped, will require UI redesign so that the design looks similar to a plain tableview cell.

Body:
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}


问:
LittleCMS library: which type of variable do I have to use during conversion from rgb (bgr) to cmyk colors
Please help to run conversion of colors in LittleCMS: I do find how to work with double, but I’m stacking with using an unsigned char.
 I do have BGR color in an array of unsigned char, something like this: unsigned char scanline [3] = {147, 112 220}. Values can be 0-255.
As I understand LittleCMS’s docs:  for this type I have to use TYPE_BGR_8 (and TYPE_CMYK_8 for output).
But it does not convert in a right way – only when I used TYPE_BGR_DBL, TYPE_CMYK_DBL, converted from unsigned array to double and normalized my input array to values from 0-1 I received a right conversion.
Please help to optimize my code:

1) Do I have to normalize values to 0-1?

2) Which types do I have to use in my program to exclude conversion from unsigned array to double?

My programs and outputs

1) Working in a right way:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "lcms2.h"

int main (){
    cmsHPROFILE hInProfile, hOutProfile;
    cmsHTRANSFORM hTransform;
    hInProfile = cmsCreate_sRGBProfile();
    hOutProfile = cmsOpenProfileFromFile("/home/ab/Documents/cmyk/colorProfiles/WebCoatedSWOP2006Grade5.icc", "r");
hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_DBL, hOutProfile, TYPE_CMYK_DBL, INTENT_PERCEPTUAL, 0);
cmsCloseProfile(hInProfile);
cmsCloseProfile(hOutProfile);

                unsigned char scanline0[3] = {147, 112, 220};
                double scanline [3], outputline [4];

                for(int k=0;k<3;k++){
                    scanline [k] = (double)scanline0 [k]/255;
                }

                printf("Red = %f \n",scanline  [2]);
                printf("Green = %f \n", scanline [1]);
                printf("Blue = %f \n \n", scanline [0]);

                cmsDoTransform(hTransform, scanline, outputline, 1); //transforming from one to other

                printf(" Cyan %f\n Mageta %f\n Yellow %f\n Black %f\n ", outputline[0], outputline[1], outputline[2], outputline[3]); //C M Y K

    return 0;
}
</code>```

Output:

```<code>Red = 0.862745
Green = 0.439216
Blue = 0.576471

 Cyan 15.350576
 Mageta 68.361944
 Yellow 25.549707
 Black 1.419089
</code>```

2) When I’m using an unsigned char, it works in a wrong way.
Program:

```<code>hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_8, hOutProfile, TYPE_CMYK_8, INTENT_PERCEPTUAL, 0);

...
                unsigned char scanline[3] = {147, 112, 220}, outputline [4];

                printf("Red = %d \n",scanline  [2]);
                printf("Green = %d \n", scanline [1]);
                printf("Blue = %d \n \n", scanline [0]);

                cmsDoTransform(hTransform, scanline, outputline, 1);
</code>```

Output:

```<code>Red = 220
Green = 112
Blue = 147

 Cyan 39
 Mageta 174
 Yellow 65
 Black 4
</code>```

答:
Answers are:

1) There no need of normilizing. if you are working with BYTE (unsigned char). In this case values are in range from 0 to 255. If we are working with double (DBL), than we have to normalize values:

RGB (BGR)  = 0...1, and CMYK = 0.0 ... 100.0.

2) We can use both variant.

Body:
Please help to run conversion of colors in LittleCMS: I do find how to work with double, but I’m stacking with using an unsigned char.
 I do have BGR color in an array of unsigned char, something like this: unsigned char scanline [3] = {147, 112 220}. Values can be 0-255.
As I understand LittleCMS’s docs:  for this type I have to use TYPE_BGR_8 (and TYPE_CMYK_8 for output).
But it does not convert in a right way – only when I used TYPE_BGR_DBL, TYPE_CMYK_DBL, converted from unsigned array to double and normalized my input array to values from 0-1 I received a right conversion.
Please help to optimize my code:

1) Do I have to normalize values to 0-1?

2) Which types do I have to use in my program to exclude conversion from unsigned array to double?

My programs and outputs

1) Working in a right way:

#include <stdio.h>
#include <stdlib.h>
#include "lcms2.h"

int main (){
    cmsHPROFILE hInProfile, hOutProfile;
    cmsHTRANSFORM hTransform;
    hInProfile = cmsCreate_sRGBProfile();
    hOutProfile = cmsOpenProfileFromFile("/home/ab/Documents/cmyk/colorProfiles/WebCoatedSWOP2006Grade5.icc", "r");
hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_DBL, hOutProfile, TYPE_CMYK_DBL, INTENT_PERCEPTUAL, 0);
cmsCloseProfile(hInProfile);
cmsCloseProfile(hOutProfile);

                unsigned char scanline0[3] = {147, 112, 220};
                double scanline [3], outputline [4];

                for(int k=0;k<3;k++){
                    scanline [k] = (double)scanline0 [k]/255;
                }

                printf("Red = %f \n",scanline  [2]);
                printf("Green = %f \n", scanline [1]);
                printf("Blue = %f \n \n", scanline [0]);

                cmsDoTransform(hTransform, scanline, outputline, 1); //transforming from one to other

                printf(" Cyan %f\n Mageta %f\n Yellow %f\n Black %f\n ", outputline[0], outputline[1], outputline[2], outputline[3]); //C M Y K

    return 0;
}

Output:

Red = 0.862745
Green = 0.439216
Blue = 0.576471

 Cyan 15.350576
 Mageta 68.361944
 Yellow 25.549707
 Black 1.419089

2) When I’m using an unsigned char, it works in a wrong way.
Program:

hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_8, hOutProfile, TYPE_CMYK_8, INTENT_PERCEPTUAL, 0);

...
                unsigned char scanline[3] = {147, 112, 220}, outputline [4];

                printf("Red = %d \n",scanline  [2]);
                printf("Green = %d \n", scanline [1]);
                printf("Blue = %d \n \n", scanline [0]);

                cmsDoTransform(hTransform, scanline, outputline, 1);

Output:

Red = 220
Green = 112
Blue = 147

 Cyan 39
 Mageta 174
 Yellow 65
 Black 4


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答: In b = B() you're constucting a new temporarty instance of class B, assigning a copy to b, then the temporary instance is descructed.

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}


问:
Script to copy data from one sheet to another based on criteria
I have a google spreadsheet called the master list. It contains two sheets 'Response' and 'Master Response'. The response sheet has around 3000 rows of data and the first column in the 'response' sheet is called ' responded?'. I want to copy the row from 'response' sheet to ' master response' sheet if the 'responded?' column has the value 'called' in it and every time a new entry is made in the 'response' sheet the appropriate row of data should be copied to the 'master response' sheet. I am currently using the following code but the rows get moved from the 'Response' sheet and not copied. I wanted a script where the rows are copied to the 'Master response' sheet and should also stay on the ' response' sheet.
Thank you in advance.</p>

```<code>function onEdit()
{
var sheetNameToWatch = "Response";
var columnNumberToWatch = 1;
var valueToWatch = "Called";
var sheetNameToMoveTheRowTo = "Master Response";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() ==
columnNumberToWatch && range.getValue() == valueToWatch)
{
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(2, 1, sheet.getLastRow(),
sheet.getLastColumn()).moveTo(targetRange);
}
}
</code>```

答:
You need to use copyTo instead of moveTo to copy the data from one sheet to another.

```<code>sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn()).copyTo(targetRange);
</code>```

To Copy it to different Spreadsheet.

```<code>var ss = SpreadsheetApp.openById("<<SPREADSHEET ID>>").getSheetByName("Sheet1");
var newTargetRange = ss.getRange(ss.getLastRow() + 1, 1);
sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn()).copyTo(newTargetRange);
</code>```

Body:
I have a google spreadsheet called the master list. It contains two sheets 'Response' and 'Master Response'. The response sheet has around 3000 rows of data and the first column in the 'response' sheet is called ' responded?'. I want to copy the row from 'response' sheet to ' master response' sheet if the 'responded?' column has the value 'called' in it and every time a new entry is made in the 'response' sheet the appropriate row of data should be copied to the 'master response' sheet. I am currently using the following code but the rows get moved from the 'Response' sheet and not copied. I wanted a script where the rows are copied to the 'Master response' sheet and should also stay on the ' response' sheet.
Thank you in advance.

function onEdit()
{
var sheetNameToWatch = "Response";
var columnNumberToWatch = 1;
var valueToWatch = "Called";
var sheetNameToMoveTheRowTo = "Master Response";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getActiveCell();
if (sheet.getName() == sheetNameToWatch && range.getColumn() ==
columnNumberToWatch && range.getValue() == valueToWatch)
{
var targetSheet = ss.getSheetByName(sheetNameToMoveTheRowTo);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(2, 1, sheet.getLastRow(),
sheet.getLastColumn()).moveTo(targetRange);
}
}

Body:
You need to use copyTo instead of moveTo to copy the data from one sheet to another.

sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn()).copyTo(targetRange);

To Copy it to different Spreadsheet.

var ss = SpreadsheetApp.openById("<<SPREADSHEET ID>>").getSheetByName("Sheet1");
var newTargetRange = ss.getRange(ss.getLastRow() + 1, 1);
sheet.getRange(2, 1, sheet.getLastRow(),sheet.getLastColumn()).copyTo(newTargetRange);