问:
Restrict S3 Object Access to Specific Cognito Users
I am working on an application that will manage access to purchased files that are stored in S3. I have files organized by product in S3, for example:

```<code>my-bucket
  ├── product-a
  │     ├── file-1
  │     ├── file-2
  │     └── file-3
  ├── product-b
  │     ├── file-1
  │     ├── file-2
  │     └── file-3
  └── etc...
</code>```

I am also using Cognito to manage user identities and authentication. I would like to create an IAM role that all users will assume which will grant them access only to the files of products they have purchased. What would be the proper way to do this? I have read thru Cognito's documentation and I feel I am just not quite connecting the dots.

I see from this example, that I could provide each user access to their own folder in a bucket, but then I would have to copy the files to each user's folder, which seems both inefficient and prone to error.

```<code>{
  "Version": "2012-10-17",
   "Statement": [
   {
     "Effect": "Allow",
     "Action": ["s3:ListBucket"],
     "Resource": ["arn:aws:s3:::my-bucket"],
      "Condition": {"StringLike": {"s3:prefix": ["cognito/myapp/"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}",
        "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}/*"
      ]
    }
  ]
}
</code>```

But I was hoping to create a policy that would grant a user access to the folder of product-a if and only if they had purchased that product, say using some flag that was contained in that user's Cognito Sync data.

Is this possible? Am I just not using the correct tools? I think this must be a common use-case.

答: A possible solution could be Aws Presigned URLs Read more here. The idea is you request a temporary url in order to give an access to the specific s3 objects with an expiration time.</p>

Body:
I am working on an application that will manage access to purchased files that are stored in S3. I have files organized by product in S3, for example:

my-bucket
  ├── product-a
  │     ├── file-1
  │     ├── file-2
  │     └── file-3
  ├── product-b
  │     ├── file-1
  │     ├── file-2
  │     └── file-3
  └── etc...

I am also using Cognito to manage user identities and authentication. I would like to create an IAM role that all users will assume which will grant them access only to the files of products they have purchased. What would be the proper way to do this? I have read thru Cognito's documentation and I feel I am just not quite connecting the dots.

I see from this example, that I could provide each user access to their own folder in a bucket, but then I would have to copy the files to each user's folder, which seems both inefficient and prone to error.

{
  "Version": "2012-10-17",
   "Statement": [
   {
     "Effect": "Allow",
     "Action": ["s3:ListBucket"],
     "Resource": ["arn:aws:s3:::my-bucket"],
      "Condition": {"StringLike": {"s3:prefix": ["cognito/myapp/"]}}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject"
      ],
      "Resource": [
        "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}",
        "arn:aws:s3:::my-bucket/myapp/${cognito-identity.amazonaws.com:sub}/*"
      ]
    }
  ]
}

But I was hoping to create a policy that would grant a user access to the folder of product-a if and only if they had purchased that product, say using some flag that was contained in that user's Cognito Sync data.

Is this possible? Am I just not using the correct tools? I think this must be a common use-case.


来源: stackexchange

问:
AttributeError while NameError
I am trying to write a code that checks if the username exists in xcnfg.py, and if it doesn't it will ask the user for input.

This is my code:

```<code>import xcnfg
# INITIALIZE SETUP SEQUENCE
try:
    xcnfg.Username
except NameError:
    xcnfg.Username = input("What is your Username? ")
    f = open( 'xcnfg.py', 'w' )
    f.write(xcnfg.Username)
    f.close()
# INITIALIZE MAIN PROGRAM
</code>```

This is the error I get:

```<code>  File "main.py", line 12, in <module>
    xcnfg.Username
AttributeError: module 'xcnfg' has no attribute 'Username'
</code>```

答:
Question Answered by mechanical_meat:

catch AttributeError instead of NameError.

ContentLicense: CC BY-SA 4.0

Title: AttributeError while NameError

Body:
I am trying to write a code that checks if the username exists in xcnfg.py, and if it doesn't it will ask the user for input.

This is my code:

import xcnfg
# INITIALIZE SETUP SEQUENCE
try:
    xcnfg.Username
except NameError:
    xcnfg.Username = input("What is your Username? ")
    f = open( 'xcnfg.py', 'w' )
    f.write(xcnfg.Username)
    f.close()
# INITIALIZE MAIN PROGRAM

This is the error I get:

  File "main.py", line 12, in <module>
    xcnfg.Username
AttributeError: module 'xcnfg' has no attribute 'Username'


问:
change state of button with document.getElementById("id").innerHTML
I have a button that display a certain text at first, but when i click it i would like it to display something else.

Here is the html input:

```<code><label class="button">
<input type="checkbox" id="control" onchange="changeState();">
<span class="button1" style="color: #4CAF50">Pull</span>
</label>
</code>```

and here is my function:

```<code>function changeState() {
  if (active == false) {
    active = true;
    start_timer();
    var myStop = "Stop"
    document.getElementById("control").innerHTML = myStop.fontcolor("#f00");
  } else {
    active = false;
    var myPull = "Pull"
    document.getElementById("control").innerHTML = myPull.fontcolor("#4CAF50");
  }
}
</code>```

When i used <button></button> instead of <input> it used to work but i need to use the input for something else. any idea what i would have to change to get it to work? I'm really new to HTML and JavaScript so I'm sort of clueless right now.

答:
Here is a solution without the span:

function changeState(e) {
  if (e.target.checked) {
    e.target.nextElementSibling.style.color = "#f00"
    e.target.nextElementSibling.textContent = "Stop"
  } else {
    e.target.nextElementSibling.style.color = "#4CAF50"
    e.target.nextElementSibling.textContent = "Pull"
  }
}

document.querySelector("#control").onchange = changeState;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="control" name="control">

<label for="control" class="button" style="color: #4CAF50">
Pull
</label></code>```

You may want to go further and use a class and classList.toggle() to handle the fontcolor.

Body:
I have a button that display a certain text at first, but when i click it i would like it to display something else.

Here is the html input:

<input type="checkbox" id="control" onchange="changeState();">
Pull

and here is my function:

function changeState() {
  if (active == false) {
    active = true;
    start_timer();
    var myStop = "Stop"
    document.getElementById("control").innerHTML = myStop.fontcolor("#f00");
  } else {
    active = false;
    var myPull = "Pull"
    document.getElementById("control").innerHTML = myPull.fontcolor("#4CAF50");
  }
}

When i used <button></button> instead of <input> it used to work but i need to use the input for something else. any idea what i would have to change to get it to work? I'm really new to HTML and JavaScript so I'm sort of clueless right now.

Body:
Here is a solution without the span:

function changeState(e) {
  if (e.target.checked) {
    e.target.nextElementSibling.style.color = "#f00"
    e.target.nextElementSibling.textContent = "Stop"
  } else {
    e.target.nextElementSibling.style.color = "#4CAF50"
    e.target.nextElementSibling.textContent = "Pull"
  }
}

document.querySelector("#control").onchange = changeState;

<input type="checkbox" id="control" name="control">

<label for="control" class="button" style="color: #4CAF50">
Pull
</label>

You may want to go further and use a class and classList.toggle() to handle the fontcolor.


问:
Xamarin iOS code signing key not found in keychain
I'm trying to debug my Xamarin.Forms application on a physical iPhone, from my windows machine.

I have a Mac connected, and an iPhone connected to that Mac

I have an Apple developer certificate

I have the device linked to my developer account

I set up automatic provisioning using Visual Studio (17.0.5)

I downloaded the generated certificate, and installed it:

On the Mac in the System keychain and Login keychain

On my windows machine running Visual Studio

When I try to deploy my application in Debug|iPhone, I get the following error:

iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.

More details from the build output in Visual Studio:

```<code>2>Using "DetectSigningIdentity" task from assembly "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\..\iOS\Xamarin.iOS.Tasks.dll".
2>Task "DetectSigningIdentity"
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Started
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initializing
2>  [xma]: Trying to get a Build Connection for Session '6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d': Xamarin.Messaging.Build.Client.BuildConnection.6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d, Lifetime: AppDomain
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initialized
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - There's no available inputs to copy to the Mac
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Serializing intputs
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9079268+01:00 - Executing
2>  [xma]: Starting remote task execution for 'Writeful.Mobile.iOS': Xamarin.iOS.Tasks.DetectSigningIdentity
2>  [xma]: Sending Request Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  [xma]: Received Response of Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic build6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d47080johndoe/+/xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Logging messages
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Finished
2>Done executing task "DetectSigningIdentity" -- FAILED.
2>Done building target "_DetectSigningIdentity" in project "Writeful.Mobile.iOS.csproj" -- FAILED.
2>
2>Build FAILED.
2>
2>"C:\Users\johndoe\source\repos\johndoe\writeful-app\Writeful.Mobile.iOS\Writeful.Mobile.iOS.csproj" (Build;BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;DebugSymbolsProjectOutputGroup;DebugSymbolsProjectOutputGroupDependencies;DocumentationProjectOutputGroup;DocumentationProjectOutputGroupDependencies;SatelliteDllsProjectOutputGroup;SatelliteDllsProjectOutputGroupDependencies;SGenFilesOutputGroup;SGenFilesOutputGroupDependencies target) (1) ->
2>(_DetectSigningIdentity target) ->
2>  C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>
2>    0 Warning(s)
2>    1 Error(s)
2>
2>Time Elapsed 00:00:01.23
========== Build: 1 succeeded, 1 failed, 21 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

</code>```

I'm not sure which device is missing the signing key, but I assume it is the iPhone, since I installed the certificate on the Mac.

If this is the issue, how can I transfer the certificate to the iPhone? I already tried by deploying an empty app from Xcode on the Mac to the iPhone, but that didn't work.

答:
You can workaround the issue by removing the  flag from the debug builds in the .csproj file. Try to follow this link :
Check</p>

Body:
I'm trying to debug my Xamarin.Forms application on a physical iPhone, from my windows machine.

I have a Mac connected, and an iPhone connected to that Mac

I have an Apple developer certificate

I have the device linked to my developer account

I set up automatic provisioning using Visual Studio (17.0.5)

I downloaded the generated certificate, and installed it:

On the Mac in the System keychain and Login keychain

On my windows machine running Visual Studio

When I try to deploy my application in Debug|iPhone, I get the following error:

iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.

More details from the build output in Visual Studio:

2>Using "DetectSigningIdentity" task from assembly "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\..\iOS\Xamarin.iOS.Tasks.dll".
2>Task "DetectSigningIdentity"
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Started
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initializing
2>  [xma]: Trying to get a Build Connection for Session '6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d': Xamarin.Messaging.Build.Client.BuildConnection.6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d, Lifetime: AppDomain
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Initialized
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - There's no available inputs to copy to the Mac
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9039262+01:00 - Serializing intputs
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9079268+01:00 - Executing
2>  [xma]: Starting remote task execution for 'Writeful.Mobile.iOS': Xamarin.iOS.Tasks.DetectSigningIdentity
2>  [xma]: Sending Request Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  [xma]: Received Response of Xamarin.Messaging.Build.Contracts.ExecuteTaskMessage to topic build6b535ab5f3c9b550fa521b36f236660807d516f929527c4e1cb2a3ecca9ec40d47080johndoe/+/xvs/build/execute-task/Writeful.Mobile.iOS/6b535ab002fDetectSigningIdentity
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Logging messages
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>  DetectSigningIdentity: 2022-02-06T17:49:30.9499278+01:00 - Finished
2>Done executing task "DetectSigningIdentity" -- FAILED.
2>Done building target "_DetectSigningIdentity" in project "Writeful.Mobile.iOS.csproj" -- FAILED.
2>
2>Build FAILED.
2>
2>"C:\Users\johndoe\source\repos\johndoe\writeful-app\Writeful.Mobile.iOS\Writeful.Mobile.iOS.csproj" (Build;BuiltProjectOutputGroup;BuiltProjectOutputGroupDependencies;DebugSymbolsProjectOutputGroup;DebugSymbolsProjectOutputGroupDependencies;DocumentationProjectOutputGroup;DocumentationProjectOutputGroupDependencies;SatelliteDllsProjectOutputGroup;SatelliteDllsProjectOutputGroupDependencies;SGenFilesOutputGroup;SGenFilesOutputGroupDependencies target) (1) ->
2>(_DetectSigningIdentity target) ->
2>  C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error : iOS code signing key 'Apple Development: John Doe (5L4565FZ2L)' not found in keychain.
2>C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Xamarin\iOS\Xamarin.Shared.targets(1566,3): error :
2>
2>    0 Warning(s)
2>    1 Error(s)
2>
2>Time Elapsed 00:00:01.23
========== Build: 1 succeeded, 1 failed, 21 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========

I'm not sure which device is missing the signing key, but I assume it is the iPhone, since I installed the certificate on the Mac.

If this is the issue, how can I transfer the certificate to the iPhone? I already tried by deploying an empty app from Xcode on the Mac to the iPhone, but that didn't work.


问:
error: unable to read input file as a property list: The operation couldn’t be completed. (XCBUtil.PropertyListConversionError error 1.)
I'm integrating Firebase to my Flutter app and setting up for iOS. I keep getting this error when I run the application.

```<code>Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    error: unable to read input file as a property list: The operation couldn’t be
    completed. (XCBUtil.PropertyListConversionError error 1.) (in target 'Runner' from
    project 'Runner')
    note: Using new build system
    note: Planning build
    note: Constructing build description

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.
</code>```

I'm not sure what could be causing this...

答:
This indicates a problem with a *.plist file.

Doesn't matter if it is GoogleService-Info.plist one. It could be Info.plist or Info-Debug.plist or Info-Release.plist - literally any .plist file in your iOS project dir.

I suggest opening the Xcode, clicking every .plist file and checking it if opens fine. If not, the IDE would show you error - probably malformed .plist file.

Body:
I'm integrating Firebase to my Flutter app and setting up for iOS. I keep getting this error when I run the application.

Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    error: unable to read input file as a property list: The operation couldn’t be
    completed. (XCBUtil.PropertyListConversionError error 1.) (in target 'Runner' from
    project 'Runner')
    note: Using new build system
    note: Planning build
    note: Constructing build description

Could not build the application for the simulator.
Error launching application on iPhone 11 Pro Max.

I'm not sure what could be causing this...


问:
String manipulation based on lists
Hello I need to write a function that will automatically make a specific string

For example I have a List of elements:

```<code>tab = [12, 23, 13, 4, 2]
</code>```

I want the function to take each element and add it to a string like so:

string:

12 + 23x + 13x^2 + 4x^3 + 2x^4

Basically, rewrite 1st element then add 'x' to the 2nd and every other but every element after 2nd must be raised to the power (starting with 2 on the third element and increasing by 1 for each next element)

The list can be infinitely long and it can contain floats so the function has to be universal

I tried this:

```<code>tab = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

string = ""
num = 0
for x in tab:

    if num < 1:
        string = string + str(x) + ' ' + '+' + ' '
    elif num < 2:
        string = string + str(x) + 'x' + ' ' + '+' + ' '
    else:
        string = string + str(x) + 'x' + f'^{num}' + '+' + ' '
    num = num + 1

print(string)
</code>```

output:

```<code>'1 + 2x + 3x^2+ 4x^3+ 5x^4+ 6x^5+ 7x^6+ 8x^7+ 9x^8+ 10x^9+'
</code>```

答:
in a compact way to create the list, you could use enumerate:

```<code>tab = [12, 23, 13, 4, 2]
result = []
for index,element in enumerate(tab):
    result.append(str(element)+(f"x^{index}" if index != 0 else ''))
print("list: ",result)
</code>```

output:

```<code>['12', '23x^1', '13x^2', '4x^3', '2x^4']
</code>```

and then join with the ' + ' string:

```<code>result = ' + '.join(result)
print("actual string:",result.__repr__())
</code>```

output:

```<code>list: ['12', '23x^1', '13x^2', '4x^3', '2x^4']
actual string: '12 + 23x^1 + 13x^2 + 4x^3 + 2x^4'
</code>```

Title: String manipulation based on lists

Body:
Hello I need to write a function that will automatically make a specific string

For example I have a List of elements:

tab = [12, 23, 13, 4, 2]

I want the function to take each element and add it to a string like so:

string:

12 + 23x + 13x^2 + 4x^3 + 2x^4

Basically, rewrite 1st element then add 'x' to the 2nd and every other but every element after 2nd must be raised to the power (starting with 2 on the third element and increasing by 1 for each next element)

The list can be infinitely long and it can contain floats so the function has to be universal

I tried this:

tab = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

string = ""
num = 0
for x in tab:

    if num < 1:
        string = string + str(x) + ' ' + '+' + ' '
    elif num < 2:
        string = string + str(x) + 'x' + ' ' + '+' + ' '
    else:
        string = string + str(x) + 'x' + f'^{num}' + '+' + ' '
    num = num + 1

print(string)

output:

'1 + 2x + 3x^2+ 4x^3+ 5x^4+ 6x^5+ 7x^6+ 8x^7+ 9x^8+ 10x^9+'

Body:
in a compact way to create the list, you could use enumerate:

tab = [12, 23, 13, 4, 2]
result = []
for index,element in enumerate(tab):
    result.append(str(element)+(f"x^{index}" if index != 0 else ''))
print("list: ",result)

output:

['12', '23x^1', '13x^2', '4x^3', '2x^4']

and then join with the ' + ' string:

result = ' + '.join(result)
print("actual string:",result.__repr__())

output:

list: ['12', '23x^1', '13x^2', '4x^3', '2x^4']
actual string: '12 + 23x^1 + 13x^2 + 4x^3 + 2x^4'


问:
Syntax Error: unexpected $end when using if/else if?
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

```<code>SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end
</code>```

Here is terms_controller.rb:

```<code>class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end
</code>```

My show page currently just consists of:

```<code><h1> <%= @title %> </h1>
</code>```

It's probably something small that I'm just missing - thanks for your help!

答:
Why not just do this:</p>

```<code>class TermsController < ApplicationController

  @@seasons = { 1 => "Fall", 2 => "Winter", 3 => "Spring", 4 => "Summer"}

  def show
    @term = Term.find(params[:id])
    @title = @@seasons[params[:id]] || "Invalid Season"
  end

end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting an error from one of my controller classes and I can't figure out why.  The error is:

SyntaxError in TermsController#show, syntax error, unexpected $end, expecting keyword_end

Here is terms_controller.rb:

class TermsController < ApplicationController

    def show
        @term = Term.find(params[:id])
        if @term.id == 1
            @title = "Fall"
        else if @term.id == 2
            @title = "Winter"
        else if @term.id == 3
            @title = "Spring"
        else if @term.id == 4
            @title = "Summer"
        end
    end
end

My show page currently just consists of:

 <%= @title %>

It's probably something small that I'm just missing - thanks for your help!

Body:
Why not just do this:

class TermsController < ApplicationController

  @@seasons = { 1 => "Fall", 2 => "Winter", 3 => "Spring", 4 => "Summer"}

  def show
    @term = Term.find(params[:id])
    @title = @@seasons[params[:id]] || "Invalid Season"
  end

end


问:
Get hyperlink from unhidden href element, Python Selenium
This question has been asked before numerous times but I have tried all of the solutions I can find with no success. In short, I am scraping a table of members and can successfully collect all columns but the last which includes a button with a hyperlink to the member's email address. The hyperlink does not appear to be hidden as one can see the email when the cursor hovers over the button however I cannot select the button element and print out the hyperlink.
Below is the XPATH to the first email address of the table (column 5)

```<code>/html/body/div[5]/div[1]/main/div/div[5]/div/div/div/table/tbody/tr[1]/td[5]/a
</code>```

Below is the element for this same first email address of the table

```<code><a href="mailto:mmabbott@mac.com"><span id="ember2071" class="ember-view aia-icon"><svg class="icon" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 40 40" style="enable-background:new 0 0 40 40;" xml:space="preserve">
<path class="st0" d="M5.5,8.3v23.5h30.8V8.3H5.5z M8.6,26.4V13.6l6.3,6.4L8.6,26.4z M21.5,21.1c-0.2,0.3-0.9,0.3-1.2,0l-9.6-9.7
    h20.4L21.5,21.1z M18.1,23.3c0.7,0.7,1.7,1.1,2.8,1.1c1.1,0,2.1-0.4,2.8-1.1l1-1.1l6.3,6.4H10.7l6.3-6.5L18.1,23.3z M26.9,20
    l6.2-6.3v12.7L26.9,20z"></path>
</svg>
</span></a>
</code>```

Below is the code for my script for pulling the email addresses. Finally, I would like the script to output the email addresses into a CSV in a separate column from the other columns but that is for a separate discussion.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# open chrome
# driver = Webdriver.chrome("C:\Python Tools\chromedriver.exe")
s = Service("C:\Python Tools\chromedriver.exe")
driver = webdriver.Chrome(service=s)

# navigate to site and sign-in
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
driver.implicitly_wait(10)
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
username = driver.find_element(By.ID, "mat-input-0")
password = driver.find_element(By.ID, "mat-input-1")
username.send_keys("juzek2022@gmail.com")
password.send_keys("Test1234!")
driver.find_element(By.CLASS_NAME, "mat-button-wrapper").click()
driver.implicitly_wait(10)

# close cookies box
driver.find_element(By.XPATH, '//*[@id="truste-consent-button"]').click()

# navigate go member directory
driver.implicitly_wait(10)
driver.get("https://www.aia.org/member-directory?page%5Bnumber%5D=1")
driver.implicitly_wait(10)
# extract email addresses: list of tried and failed find element queries
# v1 = driver.find_elements(By.XPATH, "//button[contains(text(),'mailto')]")
# v1 = driver.find_elements(By.XPATH,'//a[contains(@href,".com")]')
# v1 = driver.find_elements(By.PARTIAL_LINK_TEXT, ".com")
# v1 = driver.find_elements(By.XPATH, '//a[contains(@href,"href")]')
# v1 = driver.find_elements(By.XPATH, '//a[@href="'+url+'"]')
# v1 = driver.find_elements(By.XPATH, "//a[contains(text(),'Verify Email')]").getAttribute('href')
# v1 = driver.find_elements(By.CLASS_NAME, "ember-view aia-icon").get_attribute("href")
# v1 = driver.find_elements(By.TAG_NAME, "a").getAttribute("href")
# v1 = driver.find_elements(By.XPATH,("//input[contains(td[5])]")).getAttribute("href")
# v1 = driver.find_elements(By.cssSelector("mailto").getAttribute("href")
# v1 = driver.find_elements(By.CLASS_NAME, "data-table").getAttribute("href")
# v1 = driver.find_elements(By.XPATH, "//div[@id='testId']/a").getAttribute("href")
# v1 = driver.find_elements(By.cssSelector("mailto")
# v1 = driver.find_elements(By.TAG_NAME, "td[5]")
# v1 = driver.find_elements(By.XPATH,("//input[contains(td[5])]"))
# v1 = driver.find_elements(By.TAG_NAME, "a")
# v1 = driver.find_elements(By.CLASS_NAME, "ember-view aia-icon")
print(v1)
# export email addresses to CSV
import csv

with open('AIAMemberSearch.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_ALL,delimiter=';')
    writer.writerows(v1)
</code>```

Secondly, I would like to collect data from all five columns of the table and export to CSV, running a loop across all pages of the member directory. My draft code is below

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# open chrome
# driver = Webdriver.chrome("C:\Python Tools\chromedriver.exe")
s = Service("C:\Python Tools\chromedriver.exe")
driver = webdriver.Chrome(service=s)

# navigate to site
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
driver.implicitly_wait(10)

# Enter login
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
username = driver.find_element(By.ID, "mat-input-0")
password = driver.find_element(By.ID, "mat-input-1")
username.send_keys("juzek2022@gmail.com")
password.send_keys("Test1234!")
driver.find_element(By.CLASS_NAME, "mat-button-wrapper").click()
driver.implicitly_wait(10)

# close cookies box
# old way driver.find_element_by_xpath('//*[@id="truste-consent-button"]').click()
driver.find_element(By.XPATH, '//*[@id="truste-consent-button"]').click()

driver.implicitly_wait(10)

# for holding the resultant list
element_list = []
for page in range(1, 3, 1):

    page_url = "https://www.aia.org/member-directory?page%5Bnumber%5D=" + str(page)
    driver.get(page_url)
    driver.implicitly_wait(10)
    # collect name, chapter, firm and location columns (not working, needs a loop)
    v1 = driver.find_elements(By.CLASS_NAME, "data-table")
    # collect email addresses (working)
    v2 = driver.find_elements(By.XPATH, '//a [contains(@href,"mailto")][@href]')
    for i in v2:
        email = i.get_attribute("href")
# loop across pages of directory
    for i in range(len(v1)):
        element_list.append([v1[i].text, v2[i].text])
# export to csv
import csv
with open('AIAMemberSearch.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_ALL,delimiter=';')
    writer.writerows(element_list)
</code>```

答:
1st DONT SHARE YOUR CREDENTIALS AT ALL

2nd Share AS Much HTML as possible without sharing credentials

and this should work I tested that

```<code>v1 = driver.find_elements(By.XPATH, '//a [contains(@href,"mailto")][@href]')
for i in v1:
    email = i.get_attribute("href")
    print (email)

</code>```

Body:
This question has been asked before numerous times but I have tried all of the solutions I can find with no success. In short, I am scraping a table of members and can successfully collect all columns but the last which includes a button with a hyperlink to the member's email address. The hyperlink does not appear to be hidden as one can see the email when the cursor hovers over the button however I cannot select the button element and print out the hyperlink.
Below is the XPATH to the first email address of the table (column 5)

/html/body/div[5]/div[1]/main/div/div[5]/div/div/div/table/tbody/tr[1]/td[5]/a

Below is the element for this same first email address of the table

<svg class="icon" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 40 40" style="enable-background:new 0 0 40 40;" xml:space="preserve">
<path class="st0" d="M5.5,8.3v23.5h30.8V8.3H5.5z M8.6,26.4V13.6l6.3,6.4L8.6,26.4z M21.5,21.1c-0.2,0.3-0.9,0.3-1.2,0l-9.6-9.7
    h20.4L21.5,21.1z M18.1,23.3c0.7,0.7,1.7,1.1,2.8,1.1c1.1,0,2.1-0.4,2.8-1.1l1-1.1l6.3,6.4H10.7l6.3-6.5L18.1,23.3z M26.9,20
    l6.2-6.3v12.7L26.9,20z"></path>
</svg>

Below is the code for my script for pulling the email addresses. Finally, I would like the script to output the email addresses into a CSV in a separate column from the other columns but that is for a separate discussion.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# open chrome
# driver = Webdriver.chrome("C:\Python Tools\chromedriver.exe")
s = Service("C:\Python Tools\chromedriver.exe")
driver = webdriver.Chrome(service=s)

# navigate to site and sign-in
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
driver.implicitly_wait(10)
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
username = driver.find_element(By.ID, "mat-input-0")
password = driver.find_element(By.ID, "mat-input-1")
username.send_keys("juzek2022@gmail.com")
password.send_keys("Test1234!")
driver.find_element(By.CLASS_NAME, "mat-button-wrapper").click()
driver.implicitly_wait(10)

# close cookies box
driver.find_element(By.XPATH, '//*[@id="truste-consent-button"]').click()

# navigate go member directory
driver.implicitly_wait(10)
driver.get("https://www.aia.org/member-directory?page%5Bnumber%5D=1")
driver.implicitly_wait(10)
# extract email addresses: list of tried and failed find element queries
# v1 = driver.find_elements(By.XPATH, "//button[contains(text(),'mailto')]")
# v1 = driver.find_elements(By.XPATH,'//a[contains(@href,".com")]')
# v1 = driver.find_elements(By.PARTIAL_LINK_TEXT, ".com")
# v1 = driver.find_elements(By.XPATH, '//a[contains(@href,"href")]')
# v1 = driver.find_elements(By.XPATH, '//a[@href="'+url+'"]')
# v1 = driver.find_elements(By.XPATH, "//a[contains(text(),'Verify Email')]").getAttribute('href')
# v1 = driver.find_elements(By.CLASS_NAME, "ember-view aia-icon").get_attribute("href")
# v1 = driver.find_elements(By.TAG_NAME, "a").getAttribute("href")
# v1 = driver.find_elements(By.XPATH,("//input[contains(td[5])]")).getAttribute("href")
# v1 = driver.find_elements(By.cssSelector("mailto").getAttribute("href")
# v1 = driver.find_elements(By.CLASS_NAME, "data-table").getAttribute("href")
# v1 = driver.find_elements(By.XPATH, "//div[@id='testId']/a").getAttribute("href")
# v1 = driver.find_elements(By.cssSelector("mailto")
# v1 = driver.find_elements(By.TAG_NAME, "td[5]")
# v1 = driver.find_elements(By.XPATH,("//input[contains(td[5])]"))
# v1 = driver.find_elements(By.TAG_NAME, "a")
# v1 = driver.find_elements(By.CLASS_NAME, "ember-view aia-icon")
print(v1)
# export email addresses to CSV
import csv

with open('AIAMemberSearch.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_ALL,delimiter=';')
    writer.writerows(v1)

Secondly, I would like to collect data from all five columns of the table and export to CSV, running a loop across all pages of the member directory. My draft code is below

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# open chrome
# driver = Webdriver.chrome("C:\Python Tools\chromedriver.exe")
s = Service("C:\Python Tools\chromedriver.exe")
driver = webdriver.Chrome(service=s)

# navigate to site
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
driver.implicitly_wait(10)

# Enter login
driver.get("https://account.aia.org/signin?redirectUrl=https:%2F%2Fwww.aia.org%2F")
username = driver.find_element(By.ID, "mat-input-0")
password = driver.find_element(By.ID, "mat-input-1")
username.send_keys("juzek2022@gmail.com")
password.send_keys("Test1234!")
driver.find_element(By.CLASS_NAME, "mat-button-wrapper").click()
driver.implicitly_wait(10)

# close cookies box
# old way driver.find_element_by_xpath('//*[@id="truste-consent-button"]').click()
driver.find_element(By.XPATH, '//*[@id="truste-consent-button"]').click()

driver.implicitly_wait(10)

# for holding the resultant list
element_list = []
for page in range(1, 3, 1):

    page_url = "https://www.aia.org/member-directory?page%5Bnumber%5D=" + str(page)
    driver.get(page_url)
    driver.implicitly_wait(10)
    # collect name, chapter, firm and location columns (not working, needs a loop)
    v1 = driver.find_elements(By.CLASS_NAME, "data-table")
    # collect email addresses (working)
    v2 = driver.find_elements(By.XPATH, '//a [contains(@href,"mailto")][@href]')
    for i in v2:
        email = i.get_attribute("href")
# loop across pages of directory
    for i in range(len(v1)):
        element_list.append([v1[i].text, v2[i].text])
# export to csv
import csv
with open('AIAMemberSearch.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_ALL,delimiter=';')
    writer.writerows(element_list)

Body:
1st DONT SHARE YOUR CREDENTIALS AT ALL

2nd Share AS Much HTML as possible without sharing credentials

and this should work I tested that

v1 = driver.find_elements(By.XPATH, '//a [contains(@href,"mailto")][@href]')
for i in v1:
    email = i.get_attribute("href")
    print (email)


问:
The model item passed into the ViewDataDictionary is of type '...', but this ViewDataDictionary instance requires a model item of type '...'
What am I doing?

I am trying using two modal in one view.

What's the problem?

When run give this error:

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ProgramaEstagio.Models.Person', but this ViewDataDictionary instance requires a model item of type 'ProgramaEstagio.Models.RegisterViewModel'.

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)
</code>```

Part of "PersonController.cs":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ProgramaEstagio.Data;
using ProgramaEstagio.Models;

namespace ProgramaEstagio.Controllers
{
    public class PersonController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PersonController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Person
        public async Task<IActionResult> Index()
        {
            return View(await _context.Person.ToListAsync());
        }
        // GET: Person/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,BirthDate,sex")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }
```
<p><strong>RegisterViewModel.cs:</strong></p>
<pre class="lang-cs prettyprint-override"><code>namespace ProgramaEstagio.Models
{
    public class RegisterViewModel
    {
        public Person Person { get; set; }
        public Address Address { get; set; }
    }
}
</code>```

Edit.cshtml:

@model ProgramaEstagio.Models.RegisterViewModel

@{
    ViewData["Title"] = "Edit";
}

Edit

Person

        <form asp-action="Edit">

            <input type="hidden" asp-for="Person.ID" />

                <input asp-for="Person.FullName" class="form-control" />

                <input asp-for="Person.BirthDate" class="form-control" />

                <input asp-for="Person.sex" class="form-control" />

Address

            <input type="hidden" asp-for="Address.ID" />

                <input asp-for="Address.Country" class="form-control" />

                <input asp-for="Address.Complement" class="form-control" />

                <input asp-for="Address.Distric" class="form-control" />

                <input asp-for="Address.City" class="form-control" />

                <input asp-for="Address.State" class="form-control" />

                <select asp-for="Address.PersonID" class="form-control" asp-items="ViewBag.PersonID"></select>

                <input type="submit" value="Save" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
```
<p>What I have to do? please help me. If need more information, ask please. And sorry for any error orthography and grammar I am studing English.
Project Link: https://github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress</p>
<p>Edit:
<strong>AddressController.cs:</strong></p>
<pre class="lang-cs prettyprint-override"><code>        // GET: Addresse/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }

            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            register.Address = address;
            return View(register);
        }

        // POST: Addresse/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Country,Complement,Distric,City,State,PersonID")] Address address)
        {
            if (id != address.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(address);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AddressExists(address.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            return View(address);
        }
</code>```

答:
You essentially made a promise to C# that you would send a model of type RegisterViewModel, when you wrote this:

```<code>@model ProgramaEstagio.Models.RegisterViewModel
</code>```

But then you actually sent a Person instead:

```<code>var person = await _context.Person.FindAsync(id);
...
return View(person);
</code>```

It doesn't really matter what these two things are, so long as they agree; if you upgrade/change the type in one place (like the cshtml), you have to change it everywhere else (like the controller View(..) calls) to ensure they remain in agreement with each other

Body:
What am I doing?

I am trying using two modal in one view.

What's the problem?

When run give this error:

An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ProgramaEstagio.Models.Person', but this ViewDataDictionary instance requires a model item of type 'ProgramaEstagio.Models.RegisterViewModel'.

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)

Part of "PersonController.cs":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ProgramaEstagio.Data;
using ProgramaEstagio.Models;

namespace ProgramaEstagio.Controllers
{
    public class PersonController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PersonController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Person
        public async Task<IActionResult> Index()
        {
            return View(await _context.Person.ToListAsync());
        }
        // GET: Person/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,BirthDate,sex")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }

RegisterViewModel.cs:

namespace ProgramaEstagio.Models
{
    public class RegisterViewModel
    {
        public Person Person { get; set; }
        public Address Address { get; set; }
    }
}

Edit.cshtml:

@model ProgramaEstagio.Models.RegisterViewModel

@{
    ViewData["Title"] = "Edit";
}

Edit

Person

        <form asp-action="Edit">

            <input type="hidden" asp-for="Person.ID" />

                <input asp-for="Person.FullName" class="form-control" />

                <input asp-for="Person.BirthDate" class="form-control" />

                <input asp-for="Person.sex" class="form-control" />

Address

            <input type="hidden" asp-for="Address.ID" />

                <input asp-for="Address.Country" class="form-control" />

                <input asp-for="Address.Complement" class="form-control" />

                <input asp-for="Address.Distric" class="form-control" />

                <input asp-for="Address.City" class="form-control" />

                <input asp-for="Address.State" class="form-control" />

                <select asp-for="Address.PersonID" class="form-control" asp-items="ViewBag.PersonID"></select>

                <input type="submit" value="Save" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

What I have to do? please help me. If need more information, ask please. And sorry for any error orthography and grammar I am studing English.
Project Link: https://github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress

Edit:
AddressController.cs:

        // GET: Addresse/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }

            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            register.Address = address;
            return View(register);
        }

        // POST: Addresse/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Country,Complement,Distric,City,State,PersonID")] Address address)
        {
            if (id != address.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(address);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AddressExists(address.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            return View(address);
        }

Body:
You essentially made a promise to C# that you would send a model of type RegisterViewModel, when you wrote this:

@model ProgramaEstagio.Models.RegisterViewModel

But then you actually sent a Person instead:

var person = await _context.Person.FindAsync(id);
...
return View(person);

It doesn't really matter what these two things are, so long as they agree; if you upgrade/change the type in one place (like the cshtml), you have to change it everywhere else (like the controller View(..) calls) to ensure they remain in agreement with each other


问:
Rearrange txt content Script
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

</code>```

But combining them is the problem. I have tried something close to this:

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1
</code>```

答:
You could process it a line at a time and write the output as follows:

```<code>with open('test.txt') as f_input, open('output.txt', 'w') as f_output:
    for line in f_input:
        predator, prey = line.split(':')

        for p in prey.split(','):
            f_output.write(f'{predator} {p.strip()}\n')
</code>```

Giving you:

Wolf Sheep
Wolf Chicken
Wolf Rabbit
Lion Zebra
Lion Giraffe
Lion Gazelle
```

Title: Rearrange txt content Script

Body:
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

But combining them is the problem. I have tried something close to this:

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1

Body:
You could process it a line at a time and write the output as follows:

with open('test.txt') as f_input, open('output.txt', 'w') as f_output:
    for line in f_input:
        predator, prey = line.split(':')

        for p in prey.split(','):
            f_output.write(f'{predator} {p.strip()}\n')

Giving you:

Wolf Sheep
Wolf Chicken
Wolf Rabbit
Lion Zebra
Lion Giraffe
Lion Gazelle


问:
How can I let anonymous users to use onEdit()?
I have an Google Sheet that have 2 accessible columns for anonymous users. They will write a value on one column and they will select the "YES" as a confirmation of their input and that row will be hidden afterwards. I could achieve this but only for me. I know that simple onEdit function only works for admin but I couldn't change it to installable onEdit function. How can I do this or work around this?

/**
* TITLE:
*     Hide a row if a value is inputted.
*/

//**GLOBALS**
// Sheet the data is on.
var SHEET1 = "Oxford";
var SHEET2 = "Debrecen";
var SHEET3 = "Cluj-Napoca";
var SHEET4 = "UMH";
var SHEET5 = "RU";
var SHEET6 = "KI";
var SHEET7 = "BONN";
// The value that will cause the row to hide.
var VALUE = "YES";
// The column we will be using
var COLUMN_NUMBER = 8

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();

  //Ensure on correct sheet.
  if(SHEET1 == activeSheet.getName() || SHEET2 == activeSheet.getName() || SHEET3 == activeSheet.getName() || SHEET4 == activeSheet.getName() || SHEET5 == activeSheet.getName() || SHEET6 == activeSheet.getName() || SHEET7 == activeSheet.getName()){
    var cell = ss.getActiveCell()
    var cellValue = cell.getValue();

    //Ensure we are looking at the correct column.
    if(cell.getColumn() == COLUMN_NUMBER){
      //If the cell matched the value we require,hide the row.
      if(cellValue == VALUE){
        activeSheet.hideRow(cell);
      };
    };
  };
}
```

答:
This is wrong: "I know that simple onEdit function only works for admin ", the simple edit trigger works for any spreadsheet editor.

Share your spreadsheet to "anyone with the link" and set it to "Editor". Please bear in mind that anonymous users might need to use a Google Account to be able to edit the spreadsheet.

NOTE: The "anonymous" user should have signed in their Google account and should see the Share button

P.S. The cell edit history will show "All anonymous users" instead of the editor "anonymous" user.

References

Can't edit a file

https://developers.google.com/apps-script/guides/triggers


问:
XPath multiple, duplicate anonymous namespaces
I need to process the data in an XML file similar to this:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <bpr:release xmlns:bpr="http://www.bp.co.uk/product/release">
        <bpr:contents>
            <process id="1" name="Process 1" xmlns="http://www.bp.co.uk/product/process">
                <process name="Process 1"></process>
            </process>
            <process id="2" name="Process 2" xmlns="http://www.bp.co.uk/product/process">
                <process name="Process 1"></process>
            </process>
            <object id="1" name="Object 1" xmlns="http://www.bp.co.uk/product/process">
                <process name="Object 1" ></process>
            </object>
            <work-queue id="1" name="Queue1" xmlns="http://www.bp.co.uk/product/work-queue"/>
            <process-group id="1" xmlns="http://www.bp.co.uk/product/process-group">
                <members>
                    <process id="1"/>
                    <process id="2"/>
                </members>
            </process-group>
            <object-group id="1" xmlns="http://www.bp.co.uk/product/object-group">
                <members>
                    <object id="1"/>
                    <object id="2"/>
                </members>
            </object-group>
        </bpr:contents>
    </bpr:release>
</code>```

For example, I need to extract the /bpr:release/bpr:contents/process/process nodes for analysis, but I get nulls or this error:

```<code>System.Xml.XPath.XPathException
  HResult=0x80131943
  Message=Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
  Source=System.Xml
</code>```

I see that the file has multiple anonymous namespaces, and there is the same namespace used twice.    I've tried various combinations, for example:

```<code>XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlPath);
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("bpr", "http://www.bp.co.uk/product/release");
nsmgr.AddNamespace("bpp", "http://www.bp.co.uk/product/process");
nsmgr.AddNamespace("bpo", "http://www.bp.co.uk/product/process");
nsmgr.AddNamespace("bpwq", "http://www.bp.co.uk/product/work-queue");
nsmgr.AddNamespace("bppg", "http://www.bp.co.uk/product/process-group");
nsmgr.AddNamespace("bpog", "http://www.bp.co.uk/product/object-group");
XmlNodeList p;
XmlNodeList r;
try { r = xmlDoc.SelectNodes("/bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("//bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("/release"); } catch { }
try { r = xmlDoc.SelectNodes("//release"); } catch { }
try { r = xmlDoc.SelectNodes("release"); } catch { }
try { p = xmlDoc.SelectNodes("process"); } catch { }
try { p = xmlDoc.SelectNodes("bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("/process"); } catch { }
try { p = xmlDoc.SelectNodes("/bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("//process"); } catch { }
try { p = xmlDoc.SelectNodes("//bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("/bpr:release/bpr:contents/process/process"); } catch { }
</code>```

What is the correct XPath to get each of the child nodes of bpr:release, bpr:contents, process/process, object/process, etc.? How to use the XMLNamespaceManager for this?

答:
You're adding namespace prefix declarations to your XmlNamespaceManager, but you're not using nsmgr in your calls to SelectNodes().

```<code>try { r = xmlDoc.SelectNodes("/bpr:release", nsmgr); } catch { }
                                           ^^^^^^^
</code>```

Fix up the other calls accordingly.

Note also that your first example XPath,

```<code>/bpr:release/bpr:contents/process/process
</code>```

should be

```<code>/bpr:release/bpr:contents/bpp:process/bpp:process
</code>```

given your declaration:

```<code>nsmgr.AddNamespace("bpp", "http://www.bp.co.uk/product/process");
</code>```

Finally, you should remove duplicate prefix declarations (e.g. bpp/bpo) in some of the AddNamespace() calls.

See also

How does XPath deal with XML namespaces?

Difference between "//" and "/" in XPath?

Body:
I need to process the data in an XML file similar to this:

 <?xml version="1.0" encoding="utf-8"?>
    <bpr:release xmlns:bpr="http://www.bp.co.uk/product/release">
        <bpr:contents>
            <process id="1" name="Process 1" xmlns="http://www.bp.co.uk/product/process">
                <process name="Process 1"></process>
            </process>
            <process id="2" name="Process 2" xmlns="http://www.bp.co.uk/product/process">
                <process name="Process 1"></process>
            </process>
            <object id="1" name="Object 1" xmlns="http://www.bp.co.uk/product/process">
                <process name="Object 1" ></process>
            </object>
            <work-queue id="1" name="Queue1" xmlns="http://www.bp.co.uk/product/work-queue"/>
            <process-group id="1" xmlns="http://www.bp.co.uk/product/process-group">
                <members>
                    <process id="1"/>
                    <process id="2"/>
                </members>
            </process-group>
            <object-group id="1" xmlns="http://www.bp.co.uk/product/object-group">
                <members>
                    <object id="1"/>
                    <object id="2"/>
                </members>
            </object-group>
        </bpr:contents>
    </bpr:release>

For example, I need to extract the /bpr:release/bpr:contents/process/process nodes for analysis, but I get nulls or this error:

System.Xml.XPath.XPathException
  HResult=0x80131943
  Message=Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.
  Source=System.Xml

I see that the file has multiple anonymous namespaces, and there is the same namespace used twice.    I've tried various combinations, for example:

XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlPath);
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("bpr", "http://www.bp.co.uk/product/release");
nsmgr.AddNamespace("bpp", "http://www.bp.co.uk/product/process");
nsmgr.AddNamespace("bpo", "http://www.bp.co.uk/product/process");
nsmgr.AddNamespace("bpwq", "http://www.bp.co.uk/product/work-queue");
nsmgr.AddNamespace("bppg", "http://www.bp.co.uk/product/process-group");
nsmgr.AddNamespace("bpog", "http://www.bp.co.uk/product/object-group");
XmlNodeList p;
XmlNodeList r;
try { r = xmlDoc.SelectNodes("/bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("//bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("bpr:release"); } catch { }
try { r = xmlDoc.SelectNodes("/release"); } catch { }
try { r = xmlDoc.SelectNodes("//release"); } catch { }
try { r = xmlDoc.SelectNodes("release"); } catch { }
try { p = xmlDoc.SelectNodes("process"); } catch { }
try { p = xmlDoc.SelectNodes("bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("/process"); } catch { }
try { p = xmlDoc.SelectNodes("/bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("//process"); } catch { }
try { p = xmlDoc.SelectNodes("//bpp:process"); } catch { }
try { p = xmlDoc.SelectNodes("/bpr:release/bpr:contents/process/process"); } catch { }

What is the correct XPath to get each of the child nodes of bpr:release, bpr:contents, process/process, object/process, etc.? How to use the XMLNamespaceManager for this?

Body:
You're adding namespace prefix declarations to your XmlNamespaceManager, but you're not using nsmgr in your calls to SelectNodes().

try { r = xmlDoc.SelectNodes("/bpr:release", nsmgr); } catch { }
                                           ^^^^^^^

Fix up the other calls accordingly.

Note also that your first example XPath,

/bpr:release/bpr:contents/process/process

should be

/bpr:release/bpr:contents/bpp:process/bpp:process

given your declaration:

nsmgr.AddNamespace("bpp", "http://www.bp.co.uk/product/process");

Finally, you should remove duplicate prefix declarations (e.g. bpp/bpo) in some of the AddNamespace() calls.

See also

How does XPath deal with XML namespaces?

Difference between "//" and "/" in XPath?


问:
Field 'id' expected a number but got <User: ben>
I created a population script for a django website however, after running the script and making migrations, I logged in to the django admin page for my site to access the objects created using the script and could not do it for my Business model. It works fine for my other models.

I get this error when I try to access the registered Businesses in my database from the Django admin page. It does not seem to trace back to any of my code but rather to a template in the admin folder of my python environment. Here's the error message:

error message

Here are my models:

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_pic = models.ImageField(upload_to="profile_images", blank=True, default="profile_images/default.png")
    description = models.TextField(max_length=1024, default="")

    # boolean flag for identifying business owners
    is_business_owner = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

class Business(models.Model):

    owner_fk = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    address = models.CharField(max_length=128)
    img = models.ImageField(upload_to="business_images", blank=True)

    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name_plural = 'Businesses'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Business, self).save(*args, **kwargs)

    def __str__(self):
        return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"
</code>```

Here is how I created the objects through the population script:

```<code>def add_user(username, firstname, lastname, password, profile_pic, description,
              is_business_owner):
    new_user = User.objects.get_or_create(username=username, password=password,
              first_name=firstname, last_name=lastname)
    if new_user[1]:
        new_profile = UserProfile(user=User.objects.get(username=username))
        new_profile.profile_pic = profile_pic
        new_profile.description = description
        new_profile.is_business_owner = is_business_owner
        new_profile.save()

def add_business(owner, name, address, img):
    new_business = Business(name=name, owner_fk=User.objects.get(username=owner))
    new_business.address = address
    new_business.img = img
    new_business.save()
</code>```

Any help would be appreciated, thanks.

答:
Your Business class has got __str__ method. You are trying to pass User object to pk (id) key.

```<code>class Business(models.Model):

    def __str__(self):
        return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"
</code>```

Instead of searching User object in database Change it to:

```<code>return f"{self.name} owned by {self.owner_fk.username}"
</code>```

because you don't have to search database for related object, just address it directly.

Body:
I created a population script for a django website however, after running the script and making migrations, I logged in to the django admin page for my site to access the objects created using the script and could not do it for my Business model. It works fine for my other models.

I get this error when I try to access the registered Businesses in my database from the Django admin page. It does not seem to trace back to any of my code but rather to a template in the admin folder of my python environment. Here's the error message:

error message

Here are my models:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_pic = models.ImageField(upload_to="profile_images", blank=True, default="profile_images/default.png")
    description = models.TextField(max_length=1024, default="")

    # boolean flag for identifying business owners
    is_business_owner = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

class Business(models.Model):

    owner_fk = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    address = models.CharField(max_length=128)
    img = models.ImageField(upload_to="business_images", blank=True)

    slug = models.SlugField(unique=True)

    class Meta:
        verbose_name_plural = 'Businesses'

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Business, self).save(*args, **kwargs)

    def __str__(self):
        return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"

Here is how I created the objects through the population script:

def add_user(username, firstname, lastname, password, profile_pic, description,
              is_business_owner):
    new_user = User.objects.get_or_create(username=username, password=password,
              first_name=firstname, last_name=lastname)
    if new_user[1]:
        new_profile = UserProfile(user=User.objects.get(username=username))
        new_profile.profile_pic = profile_pic
        new_profile.description = description
        new_profile.is_business_owner = is_business_owner
        new_profile.save()

def add_business(owner, name, address, img):
    new_business = Business(name=name, owner_fk=User.objects.get(username=owner))
    new_business.address = address
    new_business.img = img
    new_business.save()

Any help would be appreciated, thanks.

Body:
Your Business class has got __str__ method. You are trying to pass User object to pk (id) key.

class Business(models.Model):

    def __str__(self):
        return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"

Instead of searching User object in database Change it to:

return f"{self.name} owned by {self.owner_fk.username}"

because you don't have to search database for related object, just address it directly.


问:
Heroku postgres connection: "Is the server running locally and accepting connections on Unix domain socket"
I am setting up a new dev environment, followed the django setup tutorial and am having issues.  Here is what I get when I try to run syncdb

```<code>Running `python doccal/manage.py syncdb` attached to terminal... up, run.1
Traceback (most recent call last):
  File "doccal/manage.py", line 14, in <module>
    execute_manager(settings)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__i
nit__.py", line 459, in execute_manager
    utility.execute()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__i
nit__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 371, in handle
    return self.handle_noargs(**options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/com
mands/syncdb.py", line 57, in handle_noargs
    cursor = connection.cursor()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/__init_
_.py", line 306, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgre
sql_psycopg2/base.py", line 177, in _cursor
    self.connection = Database.connect(**conn_params)
  File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", lin
e 179, in connect
    connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: No such file or director
y
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

I have setup this same project before using the same steps and have never had a problem.  I did, a few weeks ago, get an email that Heroku was migrating away from shared databases and assume this is somehow involved.

Also, I did notice two NEW steps in the tutorial, namely, installing dj-database-url and adding these lines to settings.py

```<code>import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
</code>```

I have tried to run this both with and without these lines and get the same issue regardless.

Another post suggested the fix was to do this

```<code>heroku addons:add shared-database
</code>```

Tried, get a message that shared-database is deprecated and to use heroku-postgresql, but that had no effect.

Thanks for any help

答:
The simplest(not comprehensive but one to get you up and running as quick as possible) solution to this error is, in your settings.py file , in the part where you have set up database settings revert the settings to

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
</code>```

make migrations (i.e python manage.py makemigrations and then python manage.py migrate)
push your changes to GitHub, in your Heroku account, create a new app then move to the setting portion of your new app, connect to GitHub and deploy from GitHub, the database resources will then be provisioned for you (i.e a PostgreSQL database will be created with the same schema and data as your local SQLite database).

Body:
I am setting up a new dev environment, followed the django setup tutorial and am having issues.  Here is what I get when I try to run syncdb

Running `python doccal/manage.py syncdb` attached to terminal... up, run.1
Traceback (most recent call last):
  File "doccal/manage.py", line 14, in <module>
    execute_manager(settings)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__i
nit__.py", line 459, in execute_manager
    utility.execute()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__i
nit__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/bas
e.py", line 371, in handle
    return self.handle_noargs(**options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/com
mands/syncdb.py", line 57, in handle_noargs
    cursor = connection.cursor()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/__init_
_.py", line 306, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgre
sql_psycopg2/base.py", line 177, in _cursor
    self.connection = Database.connect(**conn_params)
  File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", lin
e 179, in connect
    connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: No such file or director
y
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I have setup this same project before using the same steps and have never had a problem.  I did, a few weeks ago, get an email that Heroku was migrating away from shared databases and assume this is somehow involved.

Also, I did notice two NEW steps in the tutorial, namely, installing dj-database-url and adding these lines to settings.py

import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}

I have tried to run this both with and without these lines and get the same issue regardless.

Another post suggested the fix was to do this

heroku addons:add shared-database

Tried, get a message that shared-database is deprecated and to use heroku-postgresql, but that had no effect.

Thanks for any help

Body:
The simplest(not comprehensive but one to get you up and running as quick as possible) solution to this error is, in your settings.py file , in the part where you have set up database settings revert the settings to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

make migrations (i.e python manage.py makemigrations and then python manage.py migrate)
push your changes to GitHub, in your Heroku account, create a new app then move to the setting portion of your new app, connect to GitHub and deploy from GitHub, the database resources will then be provisioned for you (i.e a PostgreSQL database will be created with the same schema and data as your local SQLite database).


问:
VBA Excel vlookup in loop problem
I have a problem with my VBA code in an excel spreadsheet containing orders. Each row contains a customer number, which I use to look up the customer email address, contained in a different sheet in the workbook.

The vlookup code works fine for a single cell, but the problem is when I try to loop through all of the rows of the spreadsheet. The Excel formula for a single cell is, e.g.,

```<code>=VLOOKUP(B2,Customers!A2:D1000,4,FALSE)
</code>```

The VBA code generated for this is:

```<code>    Range("M2").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-11],Customers!RC[-12]:R[999]C[-9],4,FALSE)"
</code>```

Incorporating this into a loop, after selecting the starting cell, I have the following:

```<code>Cells(2, 13).Select
Do
  ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-11],Customers!RC[-12]:R[999]C[-9],4,FALSE)"
  ActiveCell.Offset(1, 0).Select
Loop Until IsEmpty(ActiveCell.Offset(0, -10))
</code>```

The problem is that I want the "table array" to be fixed, not relative to the cell whose value is being looked up. But I absolutely can't figure out how to do it. If I change the code as follows, I get a run-time error:

```<code>ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-11],Customers!A2:D1000,4,FALSE)"
</code>```

I have tried quoting, unquoting, setting a range variable, using the range variable with .address... can someone please help?

Thank you so much.

答:
I'm pretty sure the brackets in your R1C1 formula indicate that you are specifying a relative range (especially with the negatives in them). If you want to specify an absolute range, you need to specify the R1C1 cells without brackets; e.g. R2C2:R4C4.

As a simple example:

```<code>Sub test()
  Sheet1.Range("C5").FormulaR1C1 = "=VLOOKUP(1,R1C1:R3C3,2,FALSE)"
End Sub
</code>```

Running this gives you an absolute "A1"-style formula in cell C5.

I think your problem might be:

```<code>Customers!RC[-12]:R[999]C[-9]
</code>```

Because it is a relative range. You have to explicitly specify where your data table is; e.g. Customers!RC12:R999C9 (you need to figure out where it is on your sheet).

An easy way of figuring this out is highlighting your data table on your worksheet, then switch to the Visual Basic Editor and manually run this (put your cursor inside of the Sub, and press the 'Play' button or go to Run->Run).

```<code>Sub test2()
    Dim r As Range
    Set r = Application.Selection
    InputBox "your r1c1 range:", , r.Address(True, True, xlR1C1)
End Sub
</code>```

Title: VBA Excel vlookup in loop problem

Body:
I have a problem with my VBA code in an excel spreadsheet containing orders. Each row contains a customer number, which I use to look up the customer email address, contained in a different sheet in the workbook.

The vlookup code works fine for a single cell, but the problem is when I try to loop through all of the rows of the spreadsheet. The Excel formula for a single cell is, e.g.,

=VLOOKUP(B2,Customers!A2:D1000,4,FALSE)

The VBA code generated for this is:

    Range("M2").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-11],Customers!RC[-12]:R[999]C[-9],4,FALSE)"

Incorporating this into a loop, after selecting the starting cell, I have the following:

Cells(2, 13).Select
Do
  ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-11],Customers!RC[-12]:R[999]C[-9],4,FALSE)"
  ActiveCell.Offset(1, 0).Select
Loop Until IsEmpty(ActiveCell.Offset(0, -10))

The problem is that I want the "table array" to be fixed, not relative to the cell whose value is being looked up. But I absolutely can't figure out how to do it. If I change the code as follows, I get a run-time error:

ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-11],Customers!A2:D1000,4,FALSE)"

I have tried quoting, unquoting, setting a range variable, using the range variable with .address... can someone please help?

Thank you so much.

Body:
I'm pretty sure the brackets in your R1C1 formula indicate that you are specifying a relative range (especially with the negatives in them). If you want to specify an absolute range, you need to specify the R1C1 cells without brackets; e.g. R2C2:R4C4.

As a simple example:

Sub test()
  Sheet1.Range("C5").FormulaR1C1 = "=VLOOKUP(1,R1C1:R3C3,2,FALSE)"
End Sub

Running this gives you an absolute "A1"-style formula in cell C5.

I think your problem might be:

Customers!RC[-12]:R[999]C[-9]

Because it is a relative range. You have to explicitly specify where your data table is; e.g. Customers!RC12:R999C9 (you need to figure out where it is on your sheet).

An easy way of figuring this out is highlighting your data table on your worksheet, then switch to the Visual Basic Editor and manually run this (put your cursor inside of the Sub, and press the 'Play' button or go to Run->Run).

Sub test2()
    Dim r As Range
    Set r = Application.Selection
    InputBox "your r1c1 range:", , r.Address(True, True, xlR1C1)
End Sub


问:
I set android:exported but I am still getting error: android:exported needs to be explicitly specified for <receiver>
I am moving from SDK version 30 to 31 and I add android:exported in intent-filter but still I am getting this error:

Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

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

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

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>

        <activity android:name="com.mycompany.webviewapp.SplashActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.mycompany.webviewapp.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.VIEW"></action>
            </intent-filter>

        </activity>

        <service android:name="com.mycompany.webviewapp.FCM.MyFirebaseMessagingService">

        </service>

        <meta-data android:name="applovin.sdk.key"
            android:value="sdk api here"/>

    </application>

</manifest>
</code>```

答: I resolve my issue. I just check the merged manifest and look for reciver. In onesignal, I found out reciver with intent filter defined without android:exported. I just add android:exported="false".</p>

Body:
I am moving from SDK version 30 to 31 and I add android:exported in intent-filter but still I am getting this error:

Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

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

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

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>

        <activity android:name="com.mycompany.webviewapp.SplashActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.mycompany.webviewapp.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.VIEW"></action>
            </intent-filter>

        </activity>

        <service android:name="com.mycompany.webviewapp.FCM.MyFirebaseMessagingService">

        </service>

        <meta-data android:name="applovin.sdk.key"
            android:value="sdk api here"/>

    </application>

</manifest>


问:
Movement of character animation in java libgdx
currently I am faced with a difficulty that my character animation doesn't seem to be fluid as when I move left or right my codes seems to be rushing through the movement of the left and right animations

```<code>public Mario(World world, PlayScreen screen, int score, int lives){
        super(screen.getAtlas().findRegion("Pink_Monster"));
        this.world = world;
        currentState = State.STANDING;
        previousState = State.STANDING;
        stateTimer = 0;
        movingRight = true;

        Array<TextureRegion> frames = new Array<TextureRegion>();

//For moving left and right animations
        for (int i = 8; i < 13; i++)
            frames.add(new TextureRegion(getTexture(), i * 32, 0, 37, 40));
        PlayerRun = new Animation<TextureRegion>(0.1f,frames);
        frames.clear();
//For jumping animations
        for (int i = 1; i < 6; i++)
            frames.add(new TextureRegion(getTexture(), i * 32, 0, 37, 40));
        PlayerJump = new Animation<TextureRegion>(0.1f, frames);

        PlayerStand = new TextureRegion(getTexture(), 583, 1, 40, 40);

        controls = new Controls();
</code>```

Can't seem to figure out why my jumping animation is fine no issues with that but when it moving left and right the character seems to be glitching through the sprite images that I have like lagging of sorts

This is the png I used for my character:

答:
If you open your image with gimp and configure the grid to be 32x40 pixels (the area that you crop) you can see that the images are not placed correctly:

If you created this image with a texture packing tool, there should be a .atlas file (or something similar, depending on which tool you used) that contains the correct positioning information. If you use the atlas to load the animation, you don't need to find the texture regions yourself. That makes it much easier to find the correct textures.

Body:
currently I am faced with a difficulty that my character animation doesn't seem to be fluid as when I move left or right my codes seems to be rushing through the movement of the left and right animations

public Mario(World world, PlayScreen screen, int score, int lives){
        super(screen.getAtlas().findRegion("Pink_Monster"));
        this.world = world;
        currentState = State.STANDING;
        previousState = State.STANDING;
        stateTimer = 0;
        movingRight = true;

        Array<TextureRegion> frames = new Array<TextureRegion>();

//For moving left and right animations
        for (int i = 8; i < 13; i++)
            frames.add(new TextureRegion(getTexture(), i * 32, 0, 37, 40));
        PlayerRun = new Animation<TextureRegion>(0.1f,frames);
        frames.clear();
//For jumping animations
        for (int i = 1; i < 6; i++)
            frames.add(new TextureRegion(getTexture(), i * 32, 0, 37, 40));
        PlayerJump = new Animation<TextureRegion>(0.1f, frames);

        PlayerStand = new TextureRegion(getTexture(), 583, 1, 40, 40);

        controls = new Controls();

Can't seem to figure out why my jumping animation is fine no issues with that but when it moving left and right the character seems to be glitching through the sprite images that I have like lagging of sorts

This is the png I used for my character:


答:
I think this is the simplest code to do this. Initiate the output_string with the first number that is cast to be a string. Then, iterate on other elements of the list and do concatenation of +x^index to the output_string:

```<code>tab = [12, 23, 13, 4, 2]
output_string = str(tab[0])
for each_index in range(1, len(tab)):
    output_string += " + " + str(tab[each_index]) + "x^" + str(each_index)
print(output_string)
</code>```

The output:

```<code>12 + 23x^1 + 13x^2 + 4x^3 + 2x^4
</code>```

Title: String manipulation based on lists

Body:
Hello I need to write a function that will automatically make a specific string

For example I have a List of elements:

tab = [12, 23, 13, 4, 2]

I want the function to take each element and add it to a string like so:

string:

12 + 23x + 13x^2 + 4x^3 + 2x^4

Basically, rewrite 1st element then add 'x' to the 2nd and every other but every element after 2nd must be raised to the power (starting with 2 on the third element and increasing by 1 for each next element)

The list can be infinitely long and it can contain floats so the function has to be universal

I tried this:

tab = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

string = ""
num = 0
for x in tab:

    if num < 1:
        string = string + str(x) + ' ' + '+' + ' '
    elif num < 2:
        string = string + str(x) + 'x' + ' ' + '+' + ' '
    else:
        string = string + str(x) + 'x' + f'^{num}' + '+' + ' '
    num = num + 1

print(string)

output:

'1 + 2x + 3x^2+ 4x^3+ 5x^4+ 6x^5+ 7x^6+ 8x^7+ 9x^8+ 10x^9+'

Body:
I think this is the simplest code to do this. Initiate the output_string with the first number that is cast to be a string. Then, iterate on other elements of the list and do concatenation of +x^index to the output_string:

tab = [12, 23, 13, 4, 2]
output_string = str(tab[0])
for each_index in range(1, len(tab)):
    output_string += " + " + str(tab[each_index]) + "x^" + str(each_index)
print(output_string)

The output:

12 + 23x^1 + 13x^2 + 4x^3 + 2x^4


问:
Select records with max date in datatables Uipath
Could you please help me with this?

I have a data table (Uipath) with the following fields: id, account, reg date, exp date. Each id might have more than one account. I need to select one record by id with max reg date.

In order to do this I am using:

(From row In data_dt
Group By id = row(0)  Into grp = Group
Let md = grp.Max(Function (d) d(3))
Select data_dt_max.Rows.Add({id, CDate(md.ToString).ToString("dd/MM/yyyy")})).CopyToDataTable.

This instruction works but does not give me all the fields.  I'm very rusty in programming, so I'm really not sure how to modify it or if I need a different approach.

Thanks very much for your help!

答:
Try:

```<code>var selectedRows = data_dt
    .GroupBy(row => row.id)
    .Select(grp => grp
        .OrderByDescending(row => row.expDate)
        .First()
    );
</code>```

This first groups by ID and then, within each group, selects the record with the latest expDate. The result should be just the rows with the max expDate in each group.

The above is uses LINQ method syntax. Perhaps someone else could suggest the LINQ query syntax equivalent.

Body:
Try:

var selectedRows = data_dt
    .GroupBy(row => row.id)
    .Select(grp => grp
        .OrderByDescending(row => row.expDate)
        .First()
    );

This first groups by ID and then, within each group, selects the record with the latest expDate. The result should be just the rows with the max expDate in each group.

The above is uses LINQ method syntax. Perhaps someone else could suggest the LINQ query syntax equivalent.


问:
Is there any way that you can make JWT in your own custom view?
So I've been trying to learn about JWT and I've used both rest_framework_simplejwt and djoser, and in both of them they provide a view for creating JWT(logging in), and that makes me wonder if there's a way to create JWT in your own custom view?

答:
Yes you can.

For the library - djangorestframework-simplejwt

If you go through their documentation, you will see that you can create token in custom views as shown below.

```<code>from rest_framework_simplejwt.tokens import RefreshToken

def some_function(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }
</code>```

Here

refresh is the refresh token and refresh.access_token will give you your access token. You can implement this in any view you want. By the way, user here is the User object of from the database.

Body:
Yes you can.

For the library - djangorestframework-simplejwt

If you go through their documentation, you will see that you can create token in custom views as shown below.

from rest_framework_simplejwt.tokens import RefreshToken

def some_function(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

Here

refresh is the refresh token and refresh.access_token will give you your access token. You can implement this in any view you want. By the way, user here is the User object of from the database.