问:
Append from txt to worksheet - Powershell
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

```<code>Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

</code>```

How I want it to be

```<code>Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3
</code>```

I'm using the following code:

```<code>$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()
</code>```

答:
If I can understand you Dutch comment Flexibility is essential, because it involves different outputs with different target files (and columns) under excellent Theo's answer: here's my old-school approach:

```<code>$fileContent = @'
Node: ABC
Name: PC
Cluster: HS1
FooBar: x11
Node: XZZ
Name: CC
Cluster: HS2
FooBar: x12
Node: XYZ
Name: DD
Cluster: HS3
FooBar: x13
'@
$Testbestand = $fileContent.Split( [System.Environment]::NewLine,
          [System.StringSplitOptions]::RemoveEmptyEntries )
### all code above substitutes $Testbestand = Get-Content "Source Path"

# compute properties from given file
$linieIdLast = ''
$linieTemplate = [ordered]@{}
foreach ( $linie in $Testbestand ) {
    $linieId, $linieVal = $linie -split ":\s*",2
    if ( $linieId -in $linieTemplate.Keys ) {
        break
    } else {
        $linieIdLast = $linieId
        $linieTemplate.Add( $linieId, $Null )
    }
}

# apply computed properties to de-serialize given file
$linieComb = New-Object -TypeName PSCustomObject -Property $linieTemplate
$liniesAll = foreach ( $linie in $Testbestand ) {
    $linieId, $linieVal = $linie -split ":\s*",2
    $linieComb."$linieId" = $linieVal.Trim()
    if ( $linieId -eq $linieIdLast ) {
        $linieComb
        $linieComb = New-Object -TypeName PSCustomObject -Property $linieTemplate
    }
}

$liniesAll   # debugging output
''           # dtto

###########################################################
#                                                         #
# the following code snippet is stolen from Theo's answer #
#                                                         #
###########################################################
$row = 33        # an example instead of $row = $lastCell.row + 1

# now loop through the parsed $liniesAll array
$liniesAll | ForEach-Object {
    # and loop through the properties
    foreach ( $linieKey in $linieTemplate.Keys ) {
       # the next line is merely displayed;
       # remove all "Quotation Marks" and `Grave Accents` to make it operational
       "`$WorkSheet.cells.item($row, (`$Worksheet.Columns.Find($linieKey))).value = `$_.$linieKey"
    }
    $row++
}
# end of stolen code snippet
</code>```

Output: .\SO\60233929a.ps1

```<code>Node Name Cluster FooBar
---- ---- ------- ------
ABC  PC   HS1     x11
XZZ  CC   HS2     x12
XYZ  DD   HS3     x13

$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar
</code>```

Body:
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

How I want it to be

Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3

I'm using the following code:

$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()

Body:
If I can understand you Dutch comment Flexibility is essential, because it involves different outputs with different target files (and columns) under excellent Theo's answer: here's my old-school approach:

$fileContent = @'
Node: ABC
Name: PC
Cluster: HS1
FooBar: x11
Node: XZZ
Name: CC
Cluster: HS2
FooBar: x12
Node: XYZ
Name: DD
Cluster: HS3
FooBar: x13
'@
$Testbestand = $fileContent.Split( [System.Environment]::NewLine,
          [System.StringSplitOptions]::RemoveEmptyEntries )
### all code above substitutes $Testbestand = Get-Content "Source Path"

# compute properties from given file
$linieIdLast = ''
$linieTemplate = [ordered]@{}
foreach ( $linie in $Testbestand ) {
    $linieId, $linieVal = $linie -split ":\s*",2
    if ( $linieId -in $linieTemplate.Keys ) {
        break
    } else {
        $linieIdLast = $linieId
        $linieTemplate.Add( $linieId, $Null )
    }
}

# apply computed properties to de-serialize given file
$linieComb = New-Object -TypeName PSCustomObject -Property $linieTemplate
$liniesAll = foreach ( $linie in $Testbestand ) {
    $linieId, $linieVal = $linie -split ":\s*",2
    $linieComb."$linieId" = $linieVal.Trim()
    if ( $linieId -eq $linieIdLast ) {
        $linieComb
        $linieComb = New-Object -TypeName PSCustomObject -Property $linieTemplate
    }
}

$liniesAll   # debugging output
''           # dtto

###########################################################
#                                                         #
# the following code snippet is stolen from Theo's answer #
#                                                         #
###########################################################
$row = 33        # an example instead of $row = $lastCell.row + 1

# now loop through the parsed $liniesAll array
$liniesAll | ForEach-Object {
    # and loop through the properties
    foreach ( $linieKey in $linieTemplate.Keys ) {
       # the next line is merely displayed;
       # remove all "Quotation Marks" and `Grave Accents` to make it operational
       "`$WorkSheet.cells.item($row, (`$Worksheet.Columns.Find($linieKey))).value = `$_.$linieKey"
    }
    $row++
}
# end of stolen code snippet

Output: .\SO\60233929a.ps1

Node Name Cluster FooBar
---- ---- ------- ------
ABC  PC   HS1     x11
XZZ  CC   HS2     x12
XYZ  DD   HS3     x13

$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(33, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(34, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Node))).value = $_.Node
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Name))).value = $_.Name
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(Cluster))).value = $_.Cluster
$WorkSheet.cells.item(35, ($Worksheet.Columns.Find(FooBar))).value = $_.FooBar


来源: stackexchange

问:
LibGDX coordinates of intersection points between a Line Segment and a Circle
I'm working with LibGDX and I have a Line Segment (x1, y1, x2, y2) intersecting a circle with the center (cx, cy) and a radius R.

How can I determine the coordinates of the intersection points using LibGDX (or pure Java)?

I'm checked the Intersector.intersectSegmentCircle method, but this return only true or false without return the intersection points coordinates.

I thanks for any help.

答:
Here's my solution.

Basically a parametric equation of the line is found, then each coordinate is replaced in the equation of the circle, and we solve for t using the quadratic formula. The values obtained are used to get the points coordinates. See the answer here for a more in-depth explanation of the math. Additionally, since the line is not infinite in this case, a check is made to see if the intersection points obtained fit in the same rectangle that the line fits in.

I used the same symbols that you use in the figure.

public class Intersections {

    /**
     * Returns a list of intersection points between the edge of a circle and a line.
     * @param cx Circle center X coordinate.
     * @param cy Circle center Y coordinate.
     * @param r Circle radius.
     * @param x1 First line X coordinate.
     * @param y1 First line Y coordinate.
     * @param x2 Second line X coordinate.
     * @param y2 Second line Y coordinate.
     * @return A list of intersection points.
     */
    public static List<Vector2> getCircleLineIntersectionPoints(
            float cx, float cy, float r, float x1, float y1, float x2, float y2) {
        // Find values to use in quadratic formula
        float dx = x2 - x1;
        float dy = y2 - y1;
        float a = dx * dx + dy * dy;
        float b = 2 * dx * (x1 - cx) + 2 * dy * (y1 - cy);
        float c = (float) Math.pow((x1 - cx), 2) + (float) Math.pow((y1 - cy), 2) - r * r;
        float d = b * b - 4 * a * c;  // Discriminant

        ArrayList<Vector2> points = new ArrayList<>();
        if (d >= 0) {
            // Perform quadratic formula to get 2 points
            float root = (float) Math.sqrt(d);
            float t1 = 2 * c / (-b + root);
            float t2 = 2 * c / (-b - root);

            // Need the rectangle bounds that the line fits in to check
            // if intersection points are within the line bounds
            float xmin = Math.min(x1, x2);
            float ymin = Math.min(y1, y2);
            float xmax = Math.max(x1, x2);
            float ymax = Math.max(y1, y2);

            // Add first point
            float p1x = x1 + dx * t1;
            float p1y = y1 + dy * t1;
            if (isPointInRectangle(xmin, ymin, xmax, ymax, p1x, p1y)) {
                points.add(new Vector2(p1x, p1y));
            }

            // Add second point if there's one
            if (!MathUtils.isEqual(t1, t2)) {
                float p2x = x1 + dx * t2;
                float p2y = y1 + dy * t2;
                if (isPointInRectangle(xmin, ymin, xmax, ymax, p2x, p2y)) {
                    points.add(new Vector2(p2x, p2y));
                }
            }
        }
        return points;
    }

    private static boolean isPointInRectangle(
            float xmin, float ymin, float xmax, float ymax, float px, float py) {
        return px >= xmin && py >= ymin && px <= xmax && py <= ymax;
    }
}
```

Note that this fails and returns no points if both line points are the same but on the edge of the circle. I didn't test it much so make sure it works for all your cases.

EDIT: Instead of checking whether points are in the rectangle, it would be possible to check if the t values are between 0 and 1. However x1, y1, x2, y2 would need to be replaced with xmin, ymin, xmax, ymax everywhere.

ContentLicense: CC BY-SA 4.0

Body:
Here's my solution.

Basically a parametric equation of the line is found, then each coordinate is replaced in the equation of the circle, and we solve for t using the quadratic formula. The values obtained are used to get the points coordinates. See the answer here for a more in-depth explanation of the math. Additionally, since the line is not infinite in this case, a check is made to see if the intersection points obtained fit in the same rectangle that the line fits in.

I used the same symbols that you use in the figure.

public class Intersections {

    /**
     * Returns a list of intersection points between the edge of a circle and a line.
     * @param cx Circle center X coordinate.
     * @param cy Circle center Y coordinate.
     * @param r Circle radius.
     * @param x1 First line X coordinate.
     * @param y1 First line Y coordinate.
     * @param x2 Second line X coordinate.
     * @param y2 Second line Y coordinate.
     * @return A list of intersection points.
     */
    public static List<Vector2> getCircleLineIntersectionPoints(
            float cx, float cy, float r, float x1, float y1, float x2, float y2) {
        // Find values to use in quadratic formula
        float dx = x2 - x1;
        float dy = y2 - y1;
        float a = dx * dx + dy * dy;
        float b = 2 * dx * (x1 - cx) + 2 * dy * (y1 - cy);
        float c = (float) Math.pow((x1 - cx), 2) + (float) Math.pow((y1 - cy), 2) - r * r;
        float d = b * b - 4 * a * c;  // Discriminant

        ArrayList<Vector2> points = new ArrayList<>();
        if (d >= 0) {
            // Perform quadratic formula to get 2 points
            float root = (float) Math.sqrt(d);
            float t1 = 2 * c / (-b + root);
            float t2 = 2 * c / (-b - root);

            // Need the rectangle bounds that the line fits in to check
            // if intersection points are within the line bounds
            float xmin = Math.min(x1, x2);
            float ymin = Math.min(y1, y2);
            float xmax = Math.max(x1, x2);
            float ymax = Math.max(y1, y2);

            // Add first point
            float p1x = x1 + dx * t1;
            float p1y = y1 + dy * t1;
            if (isPointInRectangle(xmin, ymin, xmax, ymax, p1x, p1y)) {
                points.add(new Vector2(p1x, p1y));
            }

            // Add second point if there's one
            if (!MathUtils.isEqual(t1, t2)) {
                float p2x = x1 + dx * t2;
                float p2y = y1 + dy * t2;
                if (isPointInRectangle(xmin, ymin, xmax, ymax, p2x, p2y)) {
                    points.add(new Vector2(p2x, p2y));
                }
            }
        }
        return points;
    }

    private static boolean isPointInRectangle(
            float xmin, float ymin, float xmax, float ymax, float px, float py) {
        return px >= xmin && py >= ymin && px <= xmax && py <= ymax;
    }
}

Note that this fails and returns no points if both line points are the same but on the edge of the circle. I didn't test it much so make sure it works for all your cases.

EDIT: Instead of checking whether points are in the rectangle, it would be possible to check if the t values are between 0 and 1. However x1, y1, x2, y2 would need to be replaced with xmin, ymin, xmax, ymax everywhere.


问:
Compute cannot connect to ATP
EDIT - SOLUTION -

Looks like it was an issue with the Oracle Virtual Cloud Network Egress rules.

For some reason, my Egress rules only allowed 80/443 so either open it to all ports or add 1522/PORT as needed.

Currently that is located at
Networking -> Virtual Cloud Networks -> VirtualCloudNetwork-YOURID -> Security List Details -> Egress Rules

END OF EDIT

Thanks for reading.

I've tried about everything under the sun, and cannot for the life of me get my Oracle Cloud Free Tier Compute Instance to connect to my Oracle Cloud Free Tier ATP Database.

I've followed the Oracle instructions on how to connect (https://docs.oracle.com/en/cloud/paas/atp-cloud/atpug/connect-sqlcl.html#GUID-AC24404D-8D0B-4716-83F6-F0F501318011) and get what feels like a timeout, but SQLcl never did indicate it just hung. I've also installed the Oracle Instant Client and the required environment variables for it to work. I install the Instant Client at work on my servers, and have reinstalled three times so I'm quite sure the issues is not there.

Finally, I installed SQLPlus and it, within a reasonable amount of time, shows this error:

```<code>$ sqlplus admin/<password>@devdb_high

SQL*Plus: Release 18.0.0.0.0 - Production on Sun Feb 16 20:51:15 2020
Version 18.5.0.0.0

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

ERROR:
ORA-12170: TNS:Connect timeout occurred

Enter user-name:

</code>```

This lead me down the road of "can I even connect through the 1522 port" that Oracle Cloud is using.

Unziping the wallet file downloaded through the Oracle Cloud Portal, I grabbed the domain of my database adb.us-ashburn-1.oraclecloud.com. Using netcat, the following command gives me these results:

```<code>$ nc -zv adb.us-ashburn-1.oraclecloud.com 1522
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connection to 130.35.147.64 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 130.35.144.65 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.
</code>```

From what I can see, I can't even connect. Both firewalld has been stopped and SELinux set in permissive modes, and the issue still persists. I can issue that netcat command from my MacBook Pro and Fedora Workstation and connect with the same exact wallet on both of these machines as well.

Any troubleshooting is welcome!

EDIT:

Some versioning:

OS: Oracle Linux 7.7

Instant Client: 18.5 (installed through RPM)

SQLPlus: 18.5

SQLcl: 18.5

答: Can you check in Networking > Virtual Cloud Networks > VirtualCloudNetwork-20190915-1634 > Security List Details that you allow access with port 22 (ssh)?</p>

Title: Compute cannot connect to ATP

Body:
EDIT - SOLUTION -

Looks like it was an issue with the Oracle Virtual Cloud Network Egress rules.

For some reason, my Egress rules only allowed 80/443 so either open it to all ports or add 1522/PORT as needed.

Currently that is located at
Networking -> Virtual Cloud Networks -> VirtualCloudNetwork-YOURID -> Security List Details -> Egress Rules

END OF EDIT

Thanks for reading.

I've tried about everything under the sun, and cannot for the life of me get my Oracle Cloud Free Tier Compute Instance to connect to my Oracle Cloud Free Tier ATP Database.

I've followed the Oracle instructions on how to connect (https://docs.oracle.com/en/cloud/paas/atp-cloud/atpug/connect-sqlcl.html#GUID-AC24404D-8D0B-4716-83F6-F0F501318011) and get what feels like a timeout, but SQLcl never did indicate it just hung. I've also installed the Oracle Instant Client and the required environment variables for it to work. I install the Instant Client at work on my servers, and have reinstalled three times so I'm quite sure the issues is not there.

Finally, I installed SQLPlus and it, within a reasonable amount of time, shows this error:

$ sqlplus admin/<password>@devdb_high

SQL*Plus: Release 18.0.0.0.0 - Production on Sun Feb 16 20:51:15 2020
Version 18.5.0.0.0

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

ERROR:
ORA-12170: TNS:Connect timeout occurred

Enter user-name:

This lead me down the road of "can I even connect through the 1522 port" that Oracle Cloud is using.

Unziping the wallet file downloaded through the Oracle Cloud Portal, I grabbed the domain of my database adb.us-ashburn-1.oraclecloud.com. Using netcat, the following command gives me these results:

$ nc -zv adb.us-ashburn-1.oraclecloud.com 1522
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connection to 130.35.147.64 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 130.35.144.65 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.

From what I can see, I can't even connect. Both firewalld has been stopped and SELinux set in permissive modes, and the issue still persists. I can issue that netcat command from my MacBook Pro and Fedora Workstation and connect with the same exact wallet on both of these machines as well.

Any troubleshooting is welcome!

EDIT:

Some versioning:

OS: Oracle Linux 7.7

Instant Client: 18.5 (installed through RPM)

SQLPlus: 18.5

SQLcl: 18.5


问:
Import a json file, but only use the information one line at a time
I'm writing because I think what I'm asking would need multiple different functions to pull off and I'm not sure how that should be structured.

```<code>import json

filename = rs.OpenFileName("Open JSON File", filter)

#Read JSON data into the results variable
if filename:
with open(filename, 'r') as f:
    results = json.load(f)
</code>```

To import the data into the results variable, and say this is the data in the json file.

```<code>{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
</code>```

Now I'd like to have an if then statement use that and assign to a separate variable, but it goes line by line.

if "funny" >= 5 then "user_id" = variableName

do {

Then I'll contain a do command below that'll use that variable, the  Everything will restart with the next entry (next votes line) until there aren't any entries left.

Is this even possible?  If so how would that look?

答:
I hope I understand your problem correctly, you can iterate over the lines in your file and generate a json object with every line</p>

```<code>with open("file.txt", "r") as file:
    for line in file:
        current_json = json.loads(line)
        your_awesome_function(current_json["votes"]["funny"])
</code>```

Body:
I'm writing because I think what I'm asking would need multiple different functions to pull off and I'm not sure how that should be structured.

import json

filename = rs.OpenFileName("Open JSON File", filter)

#Read JSON data into the results variable
if filename:
with open(filename, 'r') as f:
    results = json.load(f)

To import the data into the results variable, and say this is the data in the json file.

{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}

Now I'd like to have an if then statement use that and assign to a separate variable, but it goes line by line.

if "funny" >= 5 then "user_id" = variableName

do {

Then I'll contain a do command below that'll use that variable, the  Everything will restart with the next entry (next votes line) until there aren't any entries left.

Is this even possible?  If so how would that look?

Body:
I hope I understand your problem correctly, you can iterate over the lines in your file and generate a json object with every line

with open("file.txt", "r") as file:
    for line in file:
        current_json = json.loads(line)
        your_awesome_function(current_json["votes"]["funny"])


问:
How to count IMG tags within DIV using Xpath
I want to count how many IMG tags there are under the surface div tag and echo the amount.

```<code><div id="surface" style="width: 4567px; height: 4137px; left: -1850px; top: -1152px; cursor: default;">

<img src="https://media.memories.png" data-seat="L:106|EE:5" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2221px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:6" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2237px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:7" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2253px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:8" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2269px; top: 1561px; display: block;">

</div>
</code>```

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

```<code>"//div[@surface='data-seat']/img"
</code>```

答:
To print the count of  tags within the
 tag, you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:

xpath:

```<code>System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@id='surface']//img"))).size());
</code>```

cssSelector:

```<code>System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div#surface img"))).size());
</code>```

Body:
I want to count how many IMG tags there are under the surface div tag and echo the amount.

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

"//div[@surface='data-seat']/img"

Body:
To print the count of <img> tags within the <div> tag, you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use either of the following Locator Strategies:

xpath:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@id='surface']//img"))).size());

cssSelector:

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div#surface img"))).size());


问:
Why the loop is not breaking?
My goal is to print out the given coordinates if they are in the valid format. I have a helper function isValid to check if the string is a coordinate or not, and the positionQuery asks for the users input, if isValid is false positionQuery gives an error and asks for the coordinates again, if it is true it prints out the coordinates. However, there is something wrong about my boolean values or loops because I am not getting any output.

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        String [] alphabet = new String[dimension];
        for(int i = 0; i < dimension; i++) {
            alphabet[i] = Character.toString((char)(65 + i));
        }
        List<String> list = Arrays.asList(alphabet);
        int [] numbers = new int [dimension];
        for(int i = 0; i < dimension; i++){
            numbers[i] = 1 + i;
        }
            if(list.contains(Character.toString(coordinate.charAt(0)))) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        return true;
                    }
                }
            }

        return false;
    }

    public static String[] positionQuery(int dim, Scanner test_in) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    System.out.println(coordinates);
                }
            }
            else {
                System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            }

        }
    }
</code>```

It would be amazing if I could see what I am doing wrong :)

答:
Your method is named validCoordinate (not isValid). And, that is far too much code for that method. Check that there are two characters, check that both are in their respective ranges. No loops, no collections, no arrays. Like,

```<code>public static boolean validCoordinate(String coordinate, int dim) {
    if (coordinate.length() == 2) {
        char a = coordinate.charAt(0);
        char b = coordinate.charAt(1);
        return a >= 'A' && a <= ('A' + dim) && b >= '1' && b <= ('1' + dim);
    }
    return false;
}
</code>```

And, System.out.println(coordinates); is not how you print an array. Try

```<code>System.out.println(Arrays.toString(coordinates));
</code>```

and please stop asking the same question. And read How to create a Minimal, Reproducible Example.

Title: Why the loop is not breaking?

Body:
My goal is to print out the given coordinates if they are in the valid format. I have a helper function isValid to check if the string is a coordinate or not, and the positionQuery asks for the users input, if isValid is false positionQuery gives an error and asks for the coordinates again, if it is true it prints out the coordinates. However, there is something wrong about my boolean values or loops because I am not getting any output.

public static boolean validCoordinate(String coordinate, int dimension) {
        String [] alphabet = new String[dimension];
        for(int i = 0; i < dimension; i++) {
            alphabet[i] = Character.toString((char)(65 + i));
        }
        List<String> list = Arrays.asList(alphabet);
        int [] numbers = new int [dimension];
        for(int i = 0; i < dimension; i++){
            numbers[i] = 1 + i;
        }
            if(list.contains(Character.toString(coordinate.charAt(0)))) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        return true;
                    }
                }
            }

        return false;
    }

    public static String[] positionQuery(int dim, Scanner test_in) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    System.out.println(coordinates);
                }
            }
            else {
                System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            }

        }
    }

It would be amazing if I could see what I am doing wrong :)

Body:
Your method is named validCoordinate (not isValid). And, that is far too much code for that method. Check that there are two characters, check that both are in their respective ranges. No loops, no collections, no arrays. Like,

public static boolean validCoordinate(String coordinate, int dim) {
    if (coordinate.length() == 2) {
        char a = coordinate.charAt(0);
        char b = coordinate.charAt(1);
        return a >= 'A' && a <= ('A' + dim) && b >= '1' && b <= ('1' + dim);
    }
    return false;
}

And, System.out.println(coordinates); is not how you print an array. Try

System.out.println(Arrays.toString(coordinates));

and please stop asking the same question. And read How to create a Minimal, Reproducible Example.


问:
In Java, how I count the size of the download of a webpage during the download?
I want to do this:

I have a max limit size for donwload(eg.: 10MB). I start the download of a webpage. If the download of the page does not finish until the limit was reached, I stop the download.

I done a similar question here: In Java, it's possible determine the size of a web page before download?, but it was to discover the size of the page before I start the download, but some servers don't send this information. Now I need to control during the donwload.

They told me to use CountInputStream. This is the way? I using HttpUrlConnection, so the download is not done with the getInputStream?

答: If you make sure HTTP 1.1 keep-alive is enabled (Connection: keep-alive) and the server agrees, the server is obliged to send a content-length.

ContentLicense: CC BY-SA 3.0


问:
onLoadChildren never gets called in MediaBrowserServiceCompat
I have implemented MediaBrowserServiceCompat in my application.

```<code>@Override
public BrowserRoot onGetRoot(@NonNull String s, int i, @Nullable Bundle bundle) {
    Log.e("testing","onGetRoot");
    return new BrowserRoot(MEDIA_ID_ROOT, null);
}
</code>```

App is entering onGetRoot method when I open Android auto app in my phone, but the method onLoadChildren never gets called. So I am not able to load my music folders.

答: You must call setSessionToken(...) in the overridden onCreate() method of the service.

Body:
I have implemented MediaBrowserServiceCompat in my application.

@Override
public BrowserRoot onGetRoot(@NonNull String s, int i, @Nullable Bundle bundle) {
    Log.e("testing","onGetRoot");
    return new BrowserRoot(MEDIA_ID_ROOT, null);
}

App is entering onGetRoot method when I open Android auto app in my phone, but the method onLoadChildren never gets called. So I am not able to load my music folders.


问:
All my apps crashing on launch on physical iPhones
I was working on a new app but when I tried it on a real device it crashed with a message of

dyld: Library not loaded: @rpath/CFAlertViewController.framework/CFAlertViewController

So, I tried to clean the build, clean project and delete DerivedData, but still crashing with the same message.
I decided to uninstall CFAlertViewController pod and tried again to run the app and it crashed again with no message.

in the end, I removed all pods and the app working successfully on my iPhone.

I tried all my previous apps that contain Cocoa pods but they all crashing on a real device.

I searched a lot for a solution but nothing works for me.

I'm using:

Xcode 11.3.1

iOS 13.3.1

Cocoapods 1.8.4

答:
In your podfile comment the use_framework! line and run your pod install again.
It is a problem in iOS 13.3.1 with dynamic frameworks


问:
Iteration over two vectors and deleting specific positions
I am build a game and I am trying to work out the collision detection. I got four classes for now. Game, Player, Projectile and Enemy. So if I shoot with the Player or the Enemy shoots I create a new projectile and emlace_back() it into a vector. All my Enemys are also stored inside a vector. All of theses Objects are created with new.
So my collision detections looks like this:

```<code>void Game::CheckHit() {

    auto enemy = m_Enemys.begin();
    auto projectile = m_Projectiles.begin();

    while(projectile != m_Projectiles.end()){

        if (//Hit Detected with player) {
            delete (*projectile);
            m_Projectiles.erase(projectile);
            m_Player->PlayerHit();
        }

        while (enemy != m_Enemys.end()) {
            if (//Hit Detected with enemy) {

                delete (*enemy);
                delete (*projectile);
                m_Projectiles.erase(projectile);
                m_Enemys.erase(enemy);
                m_Player->BulletHit();
            } else
                enemy++;
        }
    }
}
</code>```

The Problem I have is I dont actually know when I should increment the projectile iterator because I only need to do that if neither an Player nor and Enemys got it with that specific projectile. Any help is appreciated.

答:
If you do random deletion like that, it certainly doesn't look like std::vector is the right container for you. I would suggest std::list or std::forward_list.
You will find that std::list::erase() returns an iterator to the next element, so you can continue your loop with that one.

Body:
I am build a game and I am trying to work out the collision detection. I got four classes for now. Game, Player, Projectile and Enemy. So if I shoot with the Player or the Enemy shoots I create a new projectile and emlace_back() it into a vector. All my Enemys are also stored inside a vector. All of theses Objects are created with new.
So my collision detections looks like this:

void Game::CheckHit() {

    auto enemy = m_Enemys.begin();
    auto projectile = m_Projectiles.begin();

    while(projectile != m_Projectiles.end()){

        if (//Hit Detected with player) {
            delete (*projectile);
            m_Projectiles.erase(projectile);
            m_Player->PlayerHit();
        }

        while (enemy != m_Enemys.end()) {
            if (//Hit Detected with enemy) {

                delete (*enemy);
                delete (*projectile);
                m_Projectiles.erase(projectile);
                m_Enemys.erase(enemy);
                m_Player->BulletHit();
            } else
                enemy++;
        }
    }
}

The Problem I have is I dont actually know when I should increment the projectile iterator because I only need to do that if neither an Player nor and Enemys got it with that specific projectile. Any help is appreciated.


问:
How to make regex work on corner case email address

Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

```<code>private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
</code>```

Most other corner cases work well with this regex, all of the below are rejected,

```<code>        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));
</code>```

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com

Body:
Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

Most other corner cases work well with this regex, all of the below are rejected,

        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com

Body:
A fun fact is that (unlike in most languages), it is possible to write a 'regex' in C#/.NET which fully matches the RFC5322 spec for email addresses. Here is one I prepared earlier (link shows the construction):

^(?'localPart'((((\((((?'paren'\()|(?'-paren'\))|([\u0021-\u0027\u002a
-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|
([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n
\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]))*(?(paren)(?!)))\)
)|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+))*?(([a-zA-Z0-9!#$%&'*+/=?^_`
{|}~-]+)|("(([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?(([\u0021\u0023-\u
005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|\\(
[\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f
\u007f])))*([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?"))((\((((?'paren'\
()|(?'-paren'\))|([\u0021-\u0027\u002a-\u005b\u005d-\u007e]|[\u0001-\u
0008\u000b\u000c\u000e-\u001f\u007f])|([ \t]+((\r\n)[ \t]+)?|((\r\n)[
\t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u
000e-\u001f\u007f]))*(?(paren)(?!)))\))|([ \t]+((\r\n)[ \t]+)?|((\r\n)
[ \t]+)+))*?)(\.(((\((((?'paren'\()|(?'-paren'\))|([\u0021-\u0027\u002
a-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])
|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\
n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]))*(?(paren)(?!)))\
))|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+))*?(([a-zA-Z0-9!#$%&'*+/=?^_
`{|}~-]+)|("(([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?(([\u0021\u0023-\
u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|\\
([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001
f\u007f])))*([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?"))((\((((?'paren'
\()|(?'-paren'\))|([\u0021-\u0027\u002a-\u005b\u005d-\u007e]|[\u0001-\
u0008\u000b\u000c\u000e-\u001f\u007f])|([ \t]+((\r\n)[ \t]+)?|((\r\n)[
\t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u
000e-\u001f\u007f]))*(?(paren)(?!)))\))|([ \t]+((\r\n)[ \t]+)?|((\r\n)
[ \t]+)+))*?))*))@(?'domain'((((\((((?'paren'\()|(?'-paren'\))|([\u002
1-\u0027\u002a-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\
u001f\u007f])|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u007
e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]))*(?(
paren)(?!)))\))|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+))*?(([a-zA-Z0-9
!#$%&'*+/=?^_`{|}~-]+)|("(([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?(([\
u0021\u0023-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u00
1f\u007f])|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000
c\u000e-\u001f\u007f])))*([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?"))((
\((((?'paren'\()|(?'-paren'\))|([\u0021-\u0027\u002a-\u005b\u005d-\u00
7e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|([ \t]+((\r\n)[ \t
]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008
\u000b\u000c\u000e-\u001f\u007f]))*(?(paren)(?!)))\))|([ \t]+((\r\n)[
\t]+)?|((\r\n)[ \t]+)+))*?)(\.(((\((((?'paren'\()|(?'-paren'\))|([\u00
21-\u0027\u002a-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-
\u001f\u007f])|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u00
7e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]))*(?
(paren)(?!)))\))|([ \t]+((\r\n)[ \t]+)?|((\r\n)[\t]+)+))*?(([a-zA-Z0-9
!#$%&'*+/=?^_`{|}~-]+)|("(([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?(([\
u0021\u0023-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e-\u00
1f\u007f])|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000
c\u000e-\u001f\u007f])))*([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?"))((
\((((?'paren'\()|(?'-paren'\))|([\u0021-\u0027\u002a-\u005b\u005d-\u00
7e]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|([ \t]+((\r\n)[ \t
]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008
\u000b\u000c\u000e-\u001f\u007f]))*(?(paren)(?!)))\))|([ \t]+((\r\n)[
\t]+)?|((\r\n)[ \t]+)+))*?))*)|(((\((((?'paren'\()|(?'-paren'\))|([\u0
021-\u0027\u002a-\u005b\u005d-\u007e]|[\u0001-\u0008\u000b\u000c\u000e
-\u001f\u007f])|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)|\\([\u0021-\u0
07e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]))*(
?(paren)(?!)))\))|([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+))*?\[(([ \t]+
((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?([!-Z^-~]|[\u0001-\u0008\u000b\u000c\
u000e-\u001f\u007f]))*([ \t]+((\r\n)[ \t]+)?|((\r\n)[ \t]+)+)?\]((\(((
(?'paren'\()|(?'-paren'\))|([\u0021-\u0027\u002a-\u005b\u005d-\u007e]|
[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f])|([ \t]+((\r\n)[ \t]+)?
|((\r\n)[ \t]+)+)|\\([\u0021-\u007e]|[ \t]|[\r\n\0]|[\u0001-\u0008\u00
0b\u000c\u000e-\u001f\u007f]))*(?(paren)(?!)))\))|([ \t]+((\r\n)[ \t]+
)?|((\r\n)[ \t]+)+))*?))$

However, note that RFC5322's handling of domain names is more liberal than the actual domain name RFCs, and there are also additional restrictions which apply from various RFCs (e.g. SMTP enforces a maximum length). So things which RFC5322 considers email addresses can still be invalid by other measures.

The acid test is still just: send an email to it with a verification code.


问:
SQLSTATE[42S22]: Column not found, laravel relationship error?
in my app I have Product and ProductCategory models, a ProductCategory has many Products and a Product belongs to one ProductCategory, in my seed file I succesfully created categories and their products.

Now the issue is in my controller I'm trying to use eager loading method with to load all product categories along with their respective products, like this:

```<code>$productCategories = ProductCategory::with('products')->get();
</code>```

However I'm getting the following error message:

```<code>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.product_category_id' in 'where clause' (SQL: select * from `products` where `products`.`product_category_id` in (1, 2, 3, 4))
</code>```

These are my models:

Product:

```<code><?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

    protected $table = 'products';

    public function productcategory()
    {
        return $this->belongsTo('App\Models\ProductCategory', 'productcategory_id');
    }
}
</code>```

ProductCategory:

```<code><?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ProductCategory extends Model
{

    protected $table = 'productcategories';

    public function products()
    {
        return $this->HasMany('App\Models\Product');
    }

}
</code>```

And now my migrations:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{

    public function up()
    {

        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title');
            $table->timestamps();
        });

    }

    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('products');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

}
</code>```

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductCategoriesTable extends Migration
{

    public function up()
    {

        Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->timestamps();
        });

    }

    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('productcategories');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

}

</code>```

答:
*** Here  Category HasMany  Products where Foreign Key Is  productcategory_id.

class Category extends Model

{

        public function products(){

        return $this->hasMany(Product::class,'productcategory_id');

    }

}

***** Every Product belongsTo A Category..**

class Product extends Model

{

        public function category(){

        return $this->belongsTo(Category::class);

    }

}

Think Like this.

Body:
in my app I have Product and ProductCategory models, a ProductCategory has many Products and a Product belongs to one ProductCategory, in my seed file I succesfully created categories and their products.

Now the issue is in my controller I'm trying to use eager loading method with to load all product categories along with their respective products, like this:

$productCategories = ProductCategory::with('products')->get();

However I'm getting the following error message:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.product_category_id' in 'where clause' (SQL: select * from `products` where `products`.`product_category_id` in (1, 2, 3, 4))

These are my models:

Product:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

    protected $table = 'products';

    public function productcategory()
    {
        return $this->belongsTo('App\Models\ProductCategory', 'productcategory_id');
    }
}

ProductCategory:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ProductCategory extends Model
{

    protected $table = 'productcategories';

    public function products()
    {
        return $this->HasMany('App\Models\Product');
    }

}

And now my migrations:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{

    public function up()
    {

        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('productcategory_id')->index();
            $table->foreign('productcategory_id')->references('id')->on('productcategories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title');
            $table->timestamps();
        });

    }

    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('products');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

}

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductCategoriesTable extends Migration
{

    public function up()
    {

        Schema::create('productcategories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->timestamps();
        });

    }

    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::dropIfExists('productcategories');
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

}


问:
Walrus operator example in PEP572
One of the examples given in PEP572 is

```<code># Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]
</code>```

currently in python, you'd have to do one of the following:

```<code># option 1
y = f(x)
[y, y**2, y**3]
</code>```

or

```<code># option 2
[f(x), f(x)**2, f(x)**3]
</code>```

the example implies that option 2 here could be improved, but I have never seen that recommended over the first option. Is there ever a reason why option 2 (and therefore the walrus operator) would be better than option 1?

答:
A walrus with dynamic programming, it could be faster depend on f(x).

```<code>e = 1
[e := e * f(x) for i in range(1, 4)]
</code>```

Title: Walrus operator example in PEP572

Body:
One of the examples given in PEP572 is

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]

currently in python, you'd have to do one of the following:

# option 1
y = f(x)
[y, y**2, y**3]

or

# option 2
[f(x), f(x)**2, f(x)**3]

the example implies that option 2 here could be improved, but I have never seen that recommended over the first option. Is there ever a reason why option 2 (and therefore the walrus operator) would be better than option 1?

Body:
A walrus with dynamic programming, it could be faster depend on f(x).

e = 1
[e := e * f(x) for i in range(1, 4)]