问:
How to display all array elements in one column of table
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

```
</div>
</div>
</p>
<p>This is how my arrays look like.</p>
``` $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);
```
<p>This is how I tried to display but it did not work as expected.</p>
```foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}
```

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

答:
You can try like this</p>
```<code><?php

$array1 = ['elm11','elm12','elm12'];

$array2 = ['elm21','elm22','elm23'];

$array3 = ['elm31','elm32','elm33'];

?>
<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <tr>
        <?php
            foreach($array1 as $i => $elm){
        ?>
            <td><?php echo $elm ?></td>
            <td><?php echo (isset($array2[$i]) && !empty($array2[$i]) ) ? $array2[$i] : '' ?></td>
            <td><?php echo (isset($array3[$i]) && !empty($array3[$i]) ) ? $array3[$i] : '' ?></td>
        <?php
            }
        ?>
    </tr>
</table>
</code>```

Body:
I have three arrays and I want to display each of the array in a separate column of the table. My HTML table contains 3 columns.
I want to display these arrays like this.

        First Column
        Second Column
        Third Column

    Array 1 first value
        Array 2 first value
        Array 3 first value

     Array 1 second value
        Array 2 second value
        Array 3 second value

    Array 1 third value
        Array 2 third value
        Array 3 third value

This is how my arrays look like.

 $arr1 = array(1, 2, 3, 4);
 $arr2 = array(a, b, c, d);
 $arr3 = array(1, 2, 3, 4);
 $array = array($arr1, $arr2, $arr3);

This is how I tried to display but it did not work as expected.

foreach($array as $key => $arr){
echo '
';

?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
        <?php
        echo $arr[$key]->post_title;
        ?>
    <?php

echo '
';
}

It may be simple but I could not develop the logic to get this working. Any suggestion will be much appreciated.

Body:
You can try like this

<?php

$array1 = ['elm11','elm12','elm12'];

$array2 = ['elm21','elm22','elm23'];

$array3 = ['elm31','elm32','elm33'];

?>
<table>
    <tr>
        <th>First Column</th>
        <th>Second Column</th>
        <th>Third Column</th>
    </tr>
    <tr>
        <?php
            foreach($array1 as $i => $elm){
        ?>
            <td><?php echo $elm ?></td>
            <td><?php echo (isset($array2[$i]) && !empty($array2[$i]) ) ? $array2[$i] : '' ?></td>
            <td><?php echo (isset($array3[$i]) && !empty($array3[$i]) ) ? $array3[$i] : '' ?></td>
        <?php
            }
        ?>
    </tr>
</table>


来源: stackexchange

问:
ARP request without reply raw sockets python
I'm trying to get a arp reply after send ARP request but the reply is not comming.

I had a look to wireshark for the results and i think he does the broadcast to the network, but no reply show up...

In results of wireshark the MAC addr of sender and receiver is do not correspond to the real MAC addr, im bealive i'm not packing this right but i dont understand why.

need help...

```<code>#!/usr/bin/env python3

import struct
import socket

raw = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0806))
raw.bind(("wlp3s0", socket.htons(0x0806)))

mac_local = b"ff:ff:ff:ff:ff:ff"   # mac de quem envia request
ip_local = "192.168.1.7"           # ip de quem envia request
mac_dest = b"00:00:00:00:00:00"    # mac de quem recebe request
ip_dest = "192.168.1.2"            # ip de quem recebe request

# Ethernet Header
protocol = 0x0806             # 0x0806 protocol to ARP
ethernet_header = struct.pack("!6s6sH", mac_dest, mac_local, protocol)

# ARP header

type_hardware = 1
type_protocol = 0x0800       # IPV4
size_addr_hardware = 6   # Refere ao tamanho do endereço do MAC que é
48 bits  == 6 bytes
size_addr_protocol = 4  # Refere ao tamanho do endereço do ipv4 que é
32 bits == 4 bytes
operation = 1                  # 1 = request / 2 = Reply

source_ip = socket.inet_aton(ip_local)
dest_ip = socket.inet_aton(ip_dest)

arp_addr = struct.pack("!HHBBH6s4s6s4s", type_hardware, type_protocol,
                       size_addr_hardware, size_addr_protocol, operation,
                       mac_local, source_ip, mac_dest, dest_ip)
pkt = ethernet_header + arp_addr

cont = 0
while cont < 6:
    raw.send(pkt)
    cont +=1
</code>```

enter image description here

enter image description here

答:
I'm somehow confused about the accepted answer.

Is MAC 00:00:00: 00:00:00 not a valid MAC from XEROX?

https://hwaddress.com/company/xerox-corporation/

When I see ARP-request captured with e.g wireshark

then mac adresses in requests are always like

```<code>MAC_DST: FF:FF:FF:FF:FF:FF  //mac broadcast
MAC_SRC: MAC-address of requester
</code>```

the mac adresses in reply would then be

```<code>MAC_DST: MAC-adress of requester
MAC_SRC: MAC-address of replier
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get a arp reply after send ARP request but the reply is not comming.

I had a look to wireshark for the results and i think he does the broadcast to the network, but no reply show up...

In results of wireshark the MAC addr of sender and receiver is do not correspond to the real MAC addr, im bealive i'm not packing this right but i dont understand why.

need help...

#!/usr/bin/env python3

import struct
import socket

raw = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0806))
raw.bind(("wlp3s0", socket.htons(0x0806)))

mac_local = b"ff:ff:ff:ff:ff:ff"   # mac de quem envia request
ip_local = "192.168.1.7"           # ip de quem envia request
mac_dest = b"00:00:00:00:00:00"    # mac de quem recebe request
ip_dest = "192.168.1.2"            # ip de quem recebe request

# Ethernet Header
protocol = 0x0806             # 0x0806 protocol to ARP
ethernet_header = struct.pack("!6s6sH", mac_dest, mac_local, protocol)

# ARP header

type_hardware = 1
type_protocol = 0x0800       # IPV4
size_addr_hardware = 6   # Refere ao tamanho do endereço do MAC que é
48 bits  == 6 bytes
size_addr_protocol = 4  # Refere ao tamanho do endereço do ipv4 que é
32 bits == 4 bytes
operation = 1                  # 1 = request / 2 = Reply

source_ip = socket.inet_aton(ip_local)
dest_ip = socket.inet_aton(ip_dest)

arp_addr = struct.pack("!HHBBH6s4s6s4s", type_hardware, type_protocol,
                       size_addr_hardware, size_addr_protocol, operation,
                       mac_local, source_ip, mac_dest, dest_ip)
pkt = ethernet_header + arp_addr

cont = 0
while cont < 6:
    raw.send(pkt)
    cont +=1

enter image description here

enter image description here

Body:
I'm somehow confused about the accepted answer.

Is MAC 00:00:00: 00:00:00 not a valid MAC from XEROX?

https://hwaddress.com/company/xerox-corporation/

When I see ARP-request captured with e.g wireshark

then mac adresses in requests are always like

MAC_DST: FF:FF:FF:FF:FF:FF  //mac broadcast
MAC_SRC: MAC-address of requester

the mac adresses in reply would then be

MAC_DST: MAC-adress of requester
MAC_SRC: MAC-address of replier


问:
C# .NET StreamWriter: How to skip lines when writing file using StreamWriter?
I read in a text file using StreamReader.
I want to write out this same text file EXCEPT its first 4 lines and its last 6 lines.

How do I do this? Thanks.

答:
```<code>string[] fileLines = File.ReadAllLines(@"your file path");

var result = fileLines.Skip(4).Take(fileLines.Length - (4 + 6));

File.WriteAllLines(@"your output file path", result);
</code>```

ContentLicense: CC BY-SA 3.0


问:
Terraform in aws multi account env created by AWS Control Tower
I have just moved to a multi account set up using Control Tower and am having a 'mare using Terraform to deploy resources in different accounts.

My (simplified) account structure is:

```<code>|--Master
   |--management (backends etc)
   |--images     (s3, ecr)
   |--dev
   |--test
</code>```

As a simplified experiment I am trying to create an ecr in the images account. So I think I need to create a policy to enable role switching and provide permissions within the target account. For now I am being heavy handed and just trying to switch to Admin access. The AWSAdministratorAccess role is created by Control Tower on configuration.

```<code>provider "aws" {
   region  = "us-west-2"
   version = "~> 3.1"
}

data "aws_iam_group" "admins" { // want to attach policy to admins to switch role
   group_name = "administrators"
}

// Images account
resource "aws_iam_policy" "images-admin" {
  name        = "Assume-Role-Images_Admin"
  description = "Allow assuming AWSAdministratorAccess role on Images account"
  policy      = <<EOP
  {
     "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "sts:AssumeRole"
            ],
            "Resource": "arn:aws:iam::<Images_Account_ID>:role/AWSAdministratorAccess"
          }
        ]
      }
    EOP
   }

 resource "aws_iam_group_policy_attachment" "assume-role-images-admin" {
  group      = data.aws_iam_group.admins.group_name
  policy_arn = aws_iam_policy.images-admin.arn
 }
</code>```

Having deployed this stack I then attempt to deploy another stack which creates a resource in the images account.

```<code>provider "aws" {
  region  = var.region
  version = "~>3.1"
}

provider "aws" {
  alias   = "images"
  region  = var.region
  version = "~> 3.1"
  assume_role {
     role_arn = "arn:aws:iam::<Images_Account_ID>:role/AWSAdministratorAccess"
  }
}

resource "aws_ecr_repository" "boot-images" {
  provider             = aws.images
  name                 = "boot-images"
}
</code>```

On deployment I got:

```<code>> Error: error configuring Terraform AWS Provider: IAM Role (arn:aws:iam::*********:role/AWSAdministratorAccess) cannot be assumed.

There are a number of possible causes of this - the most common are:
  * The credentials used in order to assume the role are invalid
  * The credentials do not have appropriate permission to assume the role
  * The role ARN is not valid

Error: NoCredentialProviders: no valid providers in chain. Deprecated.
    For verbose messaging see aws.Config.CredentialsChainVerboseErrors
</code>```

First one: the creds provided are from the master account which always worked in a single account environment

Second: that's what I think has been achieved by attaching the policy

Third: less sure on this but AWSAdministratorAccess defo exists in the account, I think the arn format is correct and while AWS Single Sign On refers to it as a Permission Set the console also describes this as a role.

I found Deploying to multiple AWS accounts with Terraform? which was helpful but I am missing something here.

I am also at a loss of how to extend this idea to deploying an s3 remote backend into my "management" account.

Terraform version 0.12.29

答:
In my own experience and considering you already have a working AWS infrastructure, I'd rule out and move away from Control Tower and look into doing same things with CloudFormation StackSets. They let you target OUs or individual accounts.

Control Tower has been recommended to me several times, but having an AWS ecosystem of more >25 accounts with production workloads, I am very reluctant to event try. It's great to start from scratch I guess, but not when you already have a decent amount of workloads and accounts in AWS.

Body:
I have just moved to a multi account set up using Control Tower and am having a 'mare using Terraform to deploy resources in different accounts.

My (simplified) account structure is:

|--Master
   |--management (backends etc)
   |--images     (s3, ecr)
   |--dev
   |--test

As a simplified experiment I am trying to create an ecr in the images account. So I think I need to create a policy to enable role switching and provide permissions within the target account. For now I am being heavy handed and just trying to switch to Admin access. The AWSAdministratorAccess role is created by Control Tower on configuration.

provider "aws" {
   region  = "us-west-2"
   version = "~> 3.1"
}

data "aws_iam_group" "admins" { // want to attach policy to admins to switch role
   group_name = "administrators"
}

// Images account
resource "aws_iam_policy" "images-admin" {
  name        = "Assume-Role-Images_Admin"
  description = "Allow assuming AWSAdministratorAccess role on Images account"
  policy      = <<EOP
  {
     "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": [
              "sts:AssumeRole"
            ],
            "Resource": "arn:aws:iam::<Images_Account_ID>:role/AWSAdministratorAccess"
          }
        ]
      }
    EOP
   }

 resource "aws_iam_group_policy_attachment" "assume-role-images-admin" {
  group      = data.aws_iam_group.admins.group_name
  policy_arn = aws_iam_policy.images-admin.arn
 }

Having deployed this stack I then attempt to deploy another stack which creates a resource in the images account.

provider "aws" {
  region  = var.region
  version = "~>3.1"
}

provider "aws" {
  alias   = "images"
  region  = var.region
  version = "~> 3.1"
  assume_role {
     role_arn = "arn:aws:iam::<Images_Account_ID>:role/AWSAdministratorAccess"
  }
}

resource "aws_ecr_repository" "boot-images" {
  provider             = aws.images
  name                 = "boot-images"
}

On deployment I got:

> Error: error configuring Terraform AWS Provider: IAM Role (arn:aws:iam::*********:role/AWSAdministratorAccess) cannot be assumed.

There are a number of possible causes of this - the most common are:
  * The credentials used in order to assume the role are invalid
  * The credentials do not have appropriate permission to assume the role
  * The role ARN is not valid

Error: NoCredentialProviders: no valid providers in chain. Deprecated.
    For verbose messaging see aws.Config.CredentialsChainVerboseErrors

First one: the creds provided are from the master account which always worked in a single account environment

Second: that's what I think has been achieved by attaching the policy

Third: less sure on this but AWSAdministratorAccess defo exists in the account, I think the arn format is correct and while AWS Single Sign On refers to it as a Permission Set the console also describes this as a role.

I found Deploying to multiple AWS accounts with Terraform? which was helpful but I am missing something here.

I am also at a loss of how to extend this idea to deploying an s3 remote backend into my "management" account.

Terraform version 0.12.29


问:
Cross comparison of duplicates in multiple columns using COUNTIF / SUMPRODUCT
I am currently attempting to cross-compare two different columns in Excel, where I only want a flag to occur when duplicates are found in both column A and Column B.

Summary: Column A contains ID numbers. Column B contains birthdays. I want to make sure that if there are multiple rows containing the ID number, that the birthday column also matches. If only 1 of the conditions match, it is ignored.

Example:

ID number
Date of Birth
Duplicate?

ABC123
01/01/2000
No

DEF987
01/01/2000
No

DEF987
04/06/1966
No

GHI456
03/03/2001
Yes

GHI456
03/03/2001
Yes

JLK654
08/07/1996
No

I've tried the following example formula: =SUMPRODUCT(ISNUMBER(FIND(A3,A:A))*ISNUMBER(FIND(B3,B:B))), where it will count 1 for no match, and 2 for a match, although it still returns a match if only the birthday is duplicated, not both.

Is there any alternative way to facilitate such a functionality, please? Thanks!

答:
You need to use this formula for the column header named Duplicate?

This gives you the count where it is more than once, and wrapping it up within an IF Logic to check if its TRUE to return Yes otherwise No

Formula used in cell C2 & Fill Down

```<code>=IF(COUNTIFS($A:$A,$A:$A,$B:$B,$B:$B)>1,"Yes","No")
</code>```

Body:
You need to use this formula for the column header named Duplicate?

This gives you the count where it is more than once, and wrapping it up within an IF Logic to check if its TRUE to return Yes otherwise No

Formula used in cell C2 & Fill Down

=IF(COUNTIFS($A:$A,$A:$A,$B:$B,$B:$B)>1,"Yes","No")


问:
How to create a column in Pandas with distance from coordinates using GeoPy
I have this df:

```<code>    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844
</code>```

And the following coordinates:

```<code>coords_2 = (-25.236632,  -56.835262)
</code>```

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

```<code>import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)
</code>```

Output:

```<code>4691.07078306837
</code>```

So I want to apply this same logic to a Dataframe.

Thanks

答:
If you want to compare your df coordinates with some external coordinates tuple, try this:

```<code>import pandas as pd
import geopy.distance

df = pd.DataFrame(data={'latitude_1': [-25.294871, -24.946374], 'longitude_1': [-56.992654, -57.384543]})
coords_2 = (-25.236632,  -56.835262)
df['distance'] = df.apply(lambda x: geopy.distance.distance((x.latitude_1, x. longitude_1), coords_2).km, axis=1)
</code>```
```<code>   latitude_1  longitude_1   distance
0  -25.294871   -56.992654  17.116773
1  -24.946374   -57.384543  64.062048
</code>```

Or with to_numpy():

```<code>def distance(l1, l2, coords_2):
  return [geopy.distance.distance((lat, lng), coords_2).km for lat, lng in zip(l1, l2)]

df['distance'] = distance(df["latitude_1"].to_numpy(),df["longitude_1"].to_numpy(), coords_2)
</code>```

Body:
I have this df:

    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844

And the following coordinates:

coords_2 = (-25.236632,  -56.835262)

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)

Output:

4691.07078306837

So I want to apply this same logic to a Dataframe.

Thanks

Body:
If you want to compare your df coordinates with some external coordinates tuple, try this:

import pandas as pd
import geopy.distance

df = pd.DataFrame(data={'latitude_1': [-25.294871, -24.946374], 'longitude_1': [-56.992654, -57.384543]})
coords_2 = (-25.236632,  -56.835262)
df['distance'] = df.apply(lambda x: geopy.distance.distance((x.latitude_1, x. longitude_1), coords_2).km, axis=1)

   latitude_1  longitude_1   distance
0  -25.294871   -56.992654  17.116773
1  -24.946374   -57.384543  64.062048

Or with to_numpy():

def distance(l1, l2, coords_2):
  return [geopy.distance.distance((lat, lng), coords_2).km for lat, lng in zip(l1, l2)]

df['distance'] = distance(df["latitude_1"].to_numpy(),df["longitude_1"].to_numpy(), coords_2)


问:
Get Chrome to open Google Cloud Storage links
I would like to be able to open a tab in Chrome and enter something like gs://bucket-name/path/to/file and have it open the corresponding page in the GCP Web Console https://console.cloud.google.com/storage/browser/bucket-name/path/to/file. I saw there are external protocol handlers in Chrome, but I don't want to open an external application. I just want it to open another page based on the URI. I also don't want to put up any of my own servers for this simple purpose. Perhaps a Chrome Extension that can do some simple JS on the URI after I enter it into the address bar?

答:
I think it is possible now with link you gave (works for me).

@shiv turned my attention on fact that this is question about automated link replacement under the hood in address bar when you write "gs://bucket-...". So such handler just collects address and modifies it and uses modified version to go further.

Well then looks like you need something like this Set custom protocol handler in Firefox? (in case of Firefox) but unfortunately I cannot help more.


问:
saving file with format
Hi guys I am trying to save my file in python...
I dont know how to do it.. It came out the save file to be like this :
506882122734561843241851186242872

What I am trying to do is
["50688", "212273", "4561843", "241851", "18624", "2872"]

```<code>with open("output_data.txt", "w") as out_file:
    for user in users:
        out_string = ""
        out_string += str(user)
        out_file.write(out_string)
</code>```

答:
The loop you're using is stitching together each of the elements in your users list so you end up with one long string in out_string. You probably introduced this loop after you got an error message when trying to save the list straight to a file.

Instead, and as suggested in the comments, you could save the data as JSON:

import json

users = ["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
    out_file.write(json.dumps(users))
```
<p><code>output_data.txt</code> will then contain:</p>
<pre class="lang-json prettyprint-override"><code>["50688", "212273", "4561843", "241851", "18624", "2872"]
</code>```

Note: this assumes that your original list is a list of strings, not integers (it wasn't clear from your question).

Title: saving file with format

Body:
Hi guys I am trying to save my file in python...
I dont know how to do it.. It came out the save file to be like this :
506882122734561843241851186242872

What I am trying to do is
["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
    for user in users:
        out_string = ""
        out_string += str(user)
        out_file.write(out_string)

Body:
The loop you're using is stitching together each of the elements in your users list so you end up with one long string in out_string. You probably introduced this loop after you got an error message when trying to save the list straight to a file.

Instead, and as suggested in the comments, you could save the data as JSON:

import json

users = ["50688", "212273", "4561843", "241851", "18624", "2872"]

with open("output_data.txt", "w") as out_file:
    out_file.write(json.dumps(users))

output_data.txt will then contain:

["50688", "212273", "4561843", "241851", "18624", "2872"]

Note: this assumes that your original list is a list of strings, not integers (it wasn't clear from your question).


问:
Undefined reference error to function in other file
I have a game program and I am getting VERY frustrated. Everything was running fine, and I decided to clean up my program by making separate files for each set of functions. The code is very long with multiple files, but heres the basic idea:

Im on Windows XP using the Code::Blocks IDE

In my entity.h Ive declared all of my functions and variables for that class. In my entity.cpp Ive included it, as well as in all my other files. But Im still getting a huge list of errors that tell me I have an undefined reference to all of the methods in entity.h as well as all my other header files. For example, I have a function call print() to make it easier to print out things, and thats the first method I call from the entity.h file. I get this error:

Heres the code for print():

```<code>void print(string f) {
 cout<<f<<endl;
}
</code>```

How Im calling it:

```<code>void Player::win(){
entity e;
e.print("You have defeated the orc");
</code>```

}
The error:

In function 'ZN6Player3winEv':
   undefined reference to 'entity::print(std::string)'

And yes, I do have an object of entity.

答:
The problem is that originally you were defining a free function named print instead of a member function named print of class entity. You need to be in the scope of the class entity to define it as a member function which is what i did using scope resolution operator :: below.

```<code>/////vvvvvvvv
void entity::print(string f) {  //note the scope resolution operator:: used here
 cout<<f<<endl;
}
</code>```

Body:
I have a game program and I am getting VERY frustrated. Everything was running fine, and I decided to clean up my program by making separate files for each set of functions. The code is very long with multiple files, but heres the basic idea:

Im on Windows XP using the Code::Blocks IDE

In my entity.h Ive declared all of my functions and variables for that class. In my entity.cpp Ive included it, as well as in all my other files. But Im still getting a huge list of errors that tell me I have an undefined reference to all of the methods in entity.h as well as all my other header files. For example, I have a function call print() to make it easier to print out things, and thats the first method I call from the entity.h file. I get this error:

Heres the code for print():

void print(string f) {
 cout<<f<<endl;
}

How Im calling it:

void Player::win(){
entity e;
e.print("You have defeated the orc");

}
The error:

In function 'ZN6Player3winEv':
   undefined reference to 'entity::print(std::string)'

And yes, I do have an object of entity.

Body:
The problem is that originally you were defining a free function named print instead of a member function named print of class entity. You need to be in the scope of the class entity to define it as a member function which is what i did using scope resolution operator :: below.

/////vvvvvvvv
void entity::print(string f) {  //note the scope resolution operator:: used here
 cout<<f<<endl;
}


问:
Load sql file in database using php
I want to load data from sql file which is located on linux server to database.

I tried like this.

```<code>$query = "LOAD DATA INFILE '/home/technoho/public_html/gpstracking/system/application/controllers/backup/uploads/28_07_11_14_11_07.sql'
INTO TABLE `backup`
FIELDS TERMINATED BY '\', \''
LINES TERMINATED BY '\n'
STARTING BY 'INSERT'";
</code>```

This query works with local system file, but I want to load data from server file.
I think I am wrong in giving path for server file.

答:
MySqlDumper is the best tool to use for such a job
here is a link</p>

Title: Load sql file in database using php

Body:
I want to load data from sql file which is located on linux server to database.

I tried like this.

$query = "LOAD DATA INFILE '/home/technoho/public_html/gpstracking/system/application/controllers/backup/uploads/28_07_11_14_11_07.sql'
INTO TABLE `backup`
FIELDS TERMINATED BY '\', \''
LINES TERMINATED BY '\n'
STARTING BY 'INSERT'";

This query works with local system file, but I want to load data from server file.
I think I am wrong in giving path for server file.


问:
How this code is failing to give me an accurate answer?
this is my code which is working fine but it is not correct. I am unable to figure out the problem</p>
```<code>class MathUtils:

    @staticmethod
    def average(a, b):
        return a + b / 2

print(MathUtils.average(2, 1))

</code>```

答:
In your case you are dividing b by 2 and not a + b

you can try it like that

```<code>return (a + b) / 2
</code>```

Body:
this is my code which is working fine but it is not correct. I am unable to figure out the problem

class MathUtils:

    @staticmethod
    def average(a, b):
        return a + b / 2

print(MathUtils.average(2, 1))

Body:
In your case you are dividing b by 2 and not a + b

you can try it like that

return (a + b) / 2


问:
Use try-with-resources or close this 'Stream' in a "finally" clause
I am using Files.walk() to get some files from directory stuff but I am getting a warning about blocker bug from Sonarqube and Sonarlint code analysis that

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

Here is the code:

```<code>Files.walk(Paths.get(ifRecordsPath))
        .filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);

return ifRecordCollection;
</code>```

I read this post and almost got the problem but I do not know how exactly I stop the stream in correct place. When I add the finally block, it is still giving the same error

```<code>try {
    Files.walk(Paths.get(ifRecordsPath))
            .filter(Files::isDirectory)
            .map(ifRecordsCollector)
            .map(ifRecordStreamAccumulator)
            .forEach(ifRecordCollection::addAll);
} finally {
    Files.walk(Paths.get(ifRecordsPath)).close();
}
</code>```

How can I solve this?

答:
What it meant is that you need to save the stream to a variable and then use it in a try-with-resources or close it in a try-finally. So either this:

try (Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath))) {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
}
```
<p>Or this:</p>
<pre class="lang-java prettyprint-override"><code>Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath));
try {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
} finally {
    paths.close();
}
</code>```

Body:
I am using Files.walk() to get some files from directory stuff but I am getting a warning about blocker bug from Sonarqube and Sonarlint code analysis that

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made. Preferably, when class implements AutoCloseable, resource should be created using "try-with-resources" pattern and will be closed automatically.

Here is the code:

Files.walk(Paths.get(ifRecordsPath))
        .filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);

return ifRecordCollection;

I read this post and almost got the problem but I do not know how exactly I stop the stream in correct place. When I add the finally block, it is still giving the same error

try {
    Files.walk(Paths.get(ifRecordsPath))
            .filter(Files::isDirectory)
            .map(ifRecordsCollector)
            .map(ifRecordStreamAccumulator)
            .forEach(ifRecordCollection::addAll);
} finally {
    Files.walk(Paths.get(ifRecordsPath)).close();
}

How can I solve this?

Body:
What it meant is that you need to save the stream to a variable and then use it in a try-with-resources or close it in a try-finally. So either this:

try (Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath))) {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
}

Or this:

Stream<Path> paths = Files.walk(Paths.get(ifRecordsPath));
try {
    paths.filter(Files::isDirectory)
        .map(ifRecordsCollector)
        .map(ifRecordStreamAccumulator)
        .forEach(ifRecordCollection::addAll);
    return ifRecordCollection;
} finally {
    paths.close();
}


答:
StreamReader.ReadLine() reads file line by line and you can build an array of strings from the file. Then delete first four and last 6 lines from the array.
And with StreamWriter.WriteLine() you can populate new file line by line taking from your array. Should be quite simple.

Title: C# .NET StreamWriter: How to skip lines when writing file using StreamWriter?

Body:
I read in a text file using StreamReader.
I want to write out this same text file EXCEPT its first 4 lines and its last 6 lines.

How do I do this? Thanks.


问:
How to send arrays using XMLHttpRequest to server
As I know using ajax you can send data to the server but I'm confused about sending an array to post using XMLHttpRequest not any library like jQuery. My question is that, is that possible to send an array to php using XMLHttpRequest and how does jQuery send an array to php, I mean does jQuery do any additional work to send an array to server (php $_POST) ?

答:
An alternative way, if you want to use the x-www-form-urlencoded content type to send data through AJAX to PHP, you must do something like this:

```<code>var array = [1, 2, 3];

//variable to concat POST parameters
var params = "";

for(var i = 0; i < array.length; i++){

  params += "array[]=" + array[i] + "&";

}

//Remove the last char which is '&'
params = params.substring(0, params.length -1);

var http = new XMLHttpRequest();

http.open("POST", "http://localhost/your_script.php");

http.onload = function (){

    //if response status is OK
    if(http.status === 200){

        console.log(JSON.parse(http.response));

    }else{

        //handle response if status is not OK

    }

};

//set content type as x-www-form-urlencoded
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send the request with parameters
http.send(params);//params = "array[]=1&array[]=2&array[]=3"
</code>```

your_script.php:

```<code><?php
//check if index "array" on POST is defined
if(isset($_POST["array"])){

    //write a JSON body
    echo json_encode(["message" => "Received"], JSON_FORCE_OBJECT);

}
</code>```

Body:
An alternative way, if you want to use the x-www-form-urlencoded content type to send data through AJAX to PHP, you must do something like this:

var array = [1, 2, 3];

//variable to concat POST parameters
var params = "";

for(var i = 0; i < array.length; i++){

  params += "array[]=" + array[i] + "&";

}

//Remove the last char which is '&'
params = params.substring(0, params.length -1);

var http = new XMLHttpRequest();

http.open("POST", "http://localhost/your_script.php");

http.onload = function (){

    //if response status is OK
    if(http.status === 200){

        console.log(JSON.parse(http.response));

    }else{

        //handle response if status is not OK

    }

};

//set content type as x-www-form-urlencoded
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send the request with parameters
http.send(params);//params = "array[]=1&array[]=2&array[]=3"

your_script.php:

<?php
//check if index "array" on POST is defined
if(isset($_POST["array"])){

    //write a JSON body
    echo json_encode(["message" => "Received"], JSON_FORCE_OBJECT);

}


答:
You are saving user variables without any delimiters.

You can try to use str.join to add commas like

users = ["0", "1", "2"]
users = ",".join(users)
print(users)  # should print '0,1,2'
```
<p>You can also use <code>repr</code> to print string with quotes.</p>
<pre class="lang-py prettyprint-override"><code>user = "3"
print(repr(user))  # should print '"3"'
</code>```

Now you can combine both methods

with open("output_data.txt", "w") as file:
    users = map(repr, users)
    users = ", ".join(users)
    users = "[" + users + "]"
    file.write(users)
```

Title: saving file with format

Body:
You are saving user variables without any delimiters.

You can try to use str.join to add commas like

users = ["0", "1", "2"]
users = ",".join(users)
print(users)  # should print '0,1,2'

You can also use repr to print string with quotes.

user = "3"
print(repr(user))  # should print '"3"'

Now you can combine both methods

with open("output_data.txt", "w") as file:
    users = map(repr, users)
    users = ", ".join(users)
    users = "[" + users + "]"
    file.write(users)


问:
terminal command to launch kde connect indicator
What is the terminal command to launch kde-connect indicator on ubuntu 20.04?
Searched everywhere but couldn't find anything. Would really appreciate any help.</p>

答:
You should be able to launch it with kdeconnect-indicator.

In case that does not work, check if KDE Connect is correctly installed by running the KDE Connect CLI tool with kdeconnect-cli --help.


问:
compojure routes : How to call a function with dependencies from a route?
The idea is to call a certain function when a route matches. That function has dependencies . I'm new to clojure and compojure and this approach could be wrong.
But still, this is what I try to achieve.

```<code>(defroutes my-routes (GET "/user/list"
                      []
                   (list-users)) ; where list-users is for example (partial list-users user-service)
</code>```

Since I didn't find a way to do this with defroutes, I tried to setup the routes "dynamically".

```<code> (defn define-routes [services]
  (routes
    (GET "/user/:id"
         [id]
      ((:show-user services) id))
    (GET "/user/list"
         []
      ((:list-users services))))
</code>```

When I start jetty with the routes defined like this,

```<code> (defn app [services]
     (j/run-jetty (define-routes services) {:port 3000 :join? false}))
</code>```

every call leads to an exception:

```<code>java.lang.NullPointerException: Response map is nil
</code>```

Is there a way to use defroutes and call functions where dependecies are injected or is ok to do it the way I tried, but I'm doing it wrong?

答:
When you return the data that doesn't implement compojure.response/Renderable protocol, compojure doesn't know how to render it, so it expects that your result would be the whole response map.

More details can be found in the compojure documentation

So what you have to do is either implement Renderable for your data, or create the ring response yourself (presumably with some libraries), like they do in ring.util.response

Body:
The idea is to call a certain function when a route matches. That function has dependencies . I'm new to clojure and compojure and this approach could be wrong.
But still, this is what I try to achieve.

(defroutes my-routes (GET "/user/list"
                      []
                   (list-users)) ; where list-users is for example (partial list-users user-service)

Since I didn't find a way to do this with defroutes, I tried to setup the routes "dynamically".

 (defn define-routes [services]
  (routes
    (GET "/user/:id"
         [id]
      ((:show-user services) id))
    (GET "/user/list"
         []
      ((:list-users services))))

When I start jetty with the routes defined like this,

 (defn app [services]
     (j/run-jetty (define-routes services) {:port 3000 :join? false}))

every call leads to an exception:

java.lang.NullPointerException: Response map is nil

Is there a way to use defroutes and call functions where dependecies are injected or is ok to do it the way I tried, but I'm doing it wrong?


问:
How to category with properties array object into sub-array object recursively?
I have this map function parameterize with dataObj which is from database execution return.

```<code>function(dataObj){
   obj.gateways = dataObj.map((item) => ({
                    gw_name: item.gw_name.toUpperCase(),
                    pm_id: item.pm_uid,
                    pm_name: item.description.toUpperCase(),
                    pm_is_card: item.is_card_pmt ? true : false,
                    device_id: item.pd_uid,
                    device_name: item.pd_name,
                }));
   return obj;
}
</code>```

I need to transfer above function return arrayObject into something like this,

```<code>gateways: [
          {
            gw_name: "GATEWAY_1",
            gw_methods: [
               {
                pm_id: "234567",
                pm_name: "DEBIT CARD",
                pm_is_card: true
               },
               {
                pm_id: "123456",
                pm_name: "CREDIT CARD",
                pm_is_card: true
               },
            ],
            gw_devices:[
               {
                device_id: 1234,
                device_name: "Device_1"
               },
               {
                device_id: 56789,
                device_name: "Device_2"
               }
            ]
          },
          {
            gw_name: "GATEWAY_2",
            gw_methods: [
               {
                pm_id: "098763",
                pm_name: "WEB",
                pm_is_card: false
               },
               {
                pm_id: "123456",
                pm_name: "CREDIT CARD",
                pm_is_card: true
               },
            ],
            gw_devices:[
               {
                device_id: 56789,
                device_name: "Device_2"
               },
               {
                device_id: 8787,
                device_name: "Device_3"
               },
            ]
          },
        ]
</code>```

I tried many ways, but there is no luck, any suggestion would be really appreciate it.
Thanks!

答:
Given the data looks like:

const data = [
    {
        gw_name: "GATEWAY_1",
        pm_id: "234567",
        pm_name: "DEBIT CARD",
        pm_is_card: true,
    },
    {
        gw_name: "GATEWAY_1",
        pm_id: "123456",
        pm_name: "CREDIT CARD",
        pm_is_card: true,
    },
    {
        gw_name: "GATEWAY_2",
        pm_id: "098763",
        pm_name: "WEB",
        pm_is_card: false,
    },
    {
        gw_name: "GATEWAY_2",
        pm_id: "123456",
        pm_name: "CREDIT CARD",
        pm_is_card: true,
    },
];
```
<p>The following reduce will help you:</p>
<pre class="lang-js prettyprint-override"><code>const gateways = data.reduce((memo, item) => {
    let target = memo.find(({ gw_name }) => gw_name === item.gw_name);
    if (!target) {
        target = {
            gw_name: item.gw_name,
            gw_methods: [item],
        };
        return [...memo, target];
    }
    target.gw_methods = [...target.gw_methods, item];
    return memo;
}, []);

</code>```

Body:
I have this map function parameterize with dataObj which is from database execution return.

function(dataObj){
   obj.gateways = dataObj.map((item) => ({
                    gw_name: item.gw_name.toUpperCase(),
                    pm_id: item.pm_uid,
                    pm_name: item.description.toUpperCase(),
                    pm_is_card: item.is_card_pmt ? true : false,
                    device_id: item.pd_uid,
                    device_name: item.pd_name,
                }));
   return obj;
}

I need to transfer above function return arrayObject into something like this,

gateways: [
          {
            gw_name: "GATEWAY_1",
            gw_methods: [
               {
                pm_id: "234567",
                pm_name: "DEBIT CARD",
                pm_is_card: true
               },
               {
                pm_id: "123456",
                pm_name: "CREDIT CARD",
                pm_is_card: true
               },
            ],
            gw_devices:[
               {
                device_id: 1234,
                device_name: "Device_1"
               },
               {
                device_id: 56789,
                device_name: "Device_2"
               }
            ]
          },
          {
            gw_name: "GATEWAY_2",
            gw_methods: [
               {
                pm_id: "098763",
                pm_name: "WEB",
                pm_is_card: false
               },
               {
                pm_id: "123456",
                pm_name: "CREDIT CARD",
                pm_is_card: true
               },
            ],
            gw_devices:[
               {
                device_id: 56789,
                device_name: "Device_2"
               },
               {
                device_id: 8787,
                device_name: "Device_3"
               },
            ]
          },
        ]

I tried many ways, but there is no luck, any suggestion would be really appreciate it.
Thanks!

Body:
Given the data looks like:

const data = [
    {
        gw_name: "GATEWAY_1",
        pm_id: "234567",
        pm_name: "DEBIT CARD",
        pm_is_card: true,
    },
    {
        gw_name: "GATEWAY_1",
        pm_id: "123456",
        pm_name: "CREDIT CARD",
        pm_is_card: true,
    },
    {
        gw_name: "GATEWAY_2",
        pm_id: "098763",
        pm_name: "WEB",
        pm_is_card: false,
    },
    {
        gw_name: "GATEWAY_2",
        pm_id: "123456",
        pm_name: "CREDIT CARD",
        pm_is_card: true,
    },
];

The following reduce will help you:

const gateways = data.reduce((memo, item) => {
    let target = memo.find(({ gw_name }) => gw_name === item.gw_name);
    if (!target) {
        target = {
            gw_name: item.gw_name,
            gw_methods: [item],
        };
        return [...memo, target];
    }
    target.gw_methods = [...target.gw_methods, item];
    return memo;
}, []);


问:
User Authentication: Providing separate errors for invalid email/password entry
In my Rails app I'm trying to produce a separate flash.now[:alert] for invalid :email and :password, respectively. So if a user enters the correct email but wrong password, the :alert warns the user of an invalid password and vice versa. Here's what I have in my SessionsController:

```<code>def create
  if user = User.authenticate(params[:email], params[:password])
    session[:user_id] = user.id
    redirect_to user.profile, :notice => "Logged in successfully"
  elsif user.email != params[:email]
    session[:email] = @user.email
    flash.now[:alert] = "Invalid email. Try again!"
    render :action => 'new'
  else
    session[:password] = @user.password
    flash.now[:alert] = "Invalid password. Try again!"
    render :action => 'new'
  end
end
</code>```

Rendering this gives me an undefined method for email. Can anyone help me figure out what I'm doing wrong?

答:
DISCLAIMER: Obviously this is a really bad idea as an attacker could keep on trying emails until he found one that did match and then he could start trying passwords for this email he knows exists at your database, but you're asking, so it's up to you deciding to do this or not.

Your authenticate method obviously only returns the user if the email and password did match, change your authenticate method to return a boolean and a user if there is any available. It would look somewhat like this:

```<code>def authenticate(email, password)
  u = first(:conditions => {:email => email, :state => 'active'})
  u && u.authenticated?(password) ? [true, u] : [false, u]
end
</code>```

Then, at your controller:

```<code>def create
  result , user = User.authenticate(params[:email], params[:password])
  if result
    session[:user_id] = user.id
    redirect_to user.profile, :notice => "Logged in successfully"
  elsif user
    session[:email] = @user.email
    flash.now[:alert] = "Invalid email. Try again!"
    render :action => 'new'
  else
    session[:password] = @user.password
    flash.now[:alert] = "Invalid password. Try again!"
    render :action => 'new'
  end
end
</code>```

And this should work.

Body:
In my Rails app I'm trying to produce a separate flash.now[:alert] for invalid :email and :password, respectively. So if a user enters the correct email but wrong password, the :alert warns the user of an invalid password and vice versa. Here's what I have in my SessionsController:

def create
  if user = User.authenticate(params[:email], params[:password])
    session[:user_id] = user.id
    redirect_to user.profile, :notice => "Logged in successfully"
  elsif user.email != params[:email]
    session[:email] = @user.email
    flash.now[:alert] = "Invalid email. Try again!"
    render :action => 'new'
  else
    session[:password] = @user.password
    flash.now[:alert] = "Invalid password. Try again!"
    render :action => 'new'
  end
end

Rendering this gives me an undefined method for email. Can anyone help me figure out what I'm doing wrong?

Body:
DISCLAIMER: Obviously this is a really bad idea as an attacker could keep on trying emails until he found one that did match and then he could start trying passwords for this email he knows exists at your database, but you're asking, so it's up to you deciding to do this or not.

Your authenticate method obviously only returns the user if the email and password did match, change your authenticate method to return a boolean and a user if there is any available. It would look somewhat like this:

def authenticate(email, password)
  u = first(:conditions => {:email => email, :state => 'active'})
  u && u.authenticated?(password) ? [true, u] : [false, u]
end

Then, at your controller:

def create
  result , user = User.authenticate(params[:email], params[:password])
  if result
    session[:user_id] = user.id
    redirect_to user.profile, :notice => "Logged in successfully"
  elsif user
    session[:email] = @user.email
    flash.now[:alert] = "Invalid email. Try again!"
    render :action => 'new'
  else
    session[:password] = @user.password
    flash.now[:alert] = "Invalid password. Try again!"
    render :action => 'new'
  end
end

And this should work.


问:
laravel-lighthouse get unknown argument error when use @spread
im using laravel-lighthouse package.

please look the method 2:

when i use input and @spread for my login mutation i will get some errors that you can see below:

but if i use method 1 it works without problem and return the token.
why?
(im using latest package.)

method: 1 (will return token. work correctly)

```<code>type Mutation {
  login(
    email: String!
    password: String!
  ): String @field(resolver: "AuthMutator@resolve")
}
</code>```

method: 2 (return errors!)

```<code>input LoginInput {
    email: String!
    password: String!
}

type Mutation {
    login(input: LoginInput! @spread): String
        @field(resolver: "AuthMutator@resolve")

}
</code>```

答: The error message shown in your screenshot is perfectly clear and tells you exactly what is wrong. @spread only changes how the arguments are received internally, but for a client the schema appears exactly as defined. In method 2, the field login expects a single argument input.

Body:
im using laravel-lighthouse package.

please look the method 2:

when i use input and @spread for my login mutation i will get some errors that you can see below:

but if i use method 1 it works without problem and return the token.
why?
(im using latest package.)

method: 1 (will return token. work correctly)

type Mutation {
  login(
    email: String!
    password: String!
  ): String @field(resolver: "AuthMutator@resolve")
}

method: 2 (return errors!)

input LoginInput {
    email: String!
    password: String!
}

type Mutation {
    login(input: LoginInput! @spread): String
        @field(resolver: "AuthMutator@resolve")

}


问:
how to find AKS external ip using terraform data block
I am trying to get ingress EXTERNAL-IP in k8s. Is there any way to get the details from terraform data block. like using data "azurerm_kubernetes_cluster" or something?</p>

答:
you can create the Public IP in advance with terraform and assign this IP to your ingress service:

YAML:

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    service.beta.kubernetes.io/azure-load-balancer-resource-group: myResourceGroup # only needed if the LB is in another RG
  name: ingress-nginx-controller
spec:
  loadBalancerIP: <YOUR_STATIC_IP>
  type: LoadBalancer
</code>```

Same but Terraform code:

```<code>resource "kubernetes_service" "ingress_nginx" {
  metadata {
    name = "ingress-nginx-controller"

    annotations {
      "service.beta.kubernetes.io/azure-load-balancer-resource-group" = "${azurerm_resource_group.YOUR_RG.name}"
    }

  spec {
    selector = {
      app = <PLACEHOLDER>
    }
    port {
      port        = <PLACEHOLDER>
      target_port = <PLACEHOLDER>
    }

    type = "LoadBalancer"
    load_balancer_ip = "${azurerm_public_ip.YOUR_IP.ip_address}"
  }
}
</code>```

Body:
you can create the Public IP in advance with terraform and assign this IP to your ingress service:

YAML:

apiVersion: v1
kind: Service
metadata:
  annotations:
    service.beta.kubernetes.io/azure-load-balancer-resource-group: myResourceGroup # only needed if the LB is in another RG
  name: ingress-nginx-controller
spec:
  loadBalancerIP: <YOUR_STATIC_IP>
  type: LoadBalancer

Same but Terraform code:

resource "kubernetes_service" "ingress_nginx" {
  metadata {
    name = "ingress-nginx-controller"

    annotations {
      "service.beta.kubernetes.io/azure-load-balancer-resource-group" = "${azurerm_resource_group.YOUR_RG.name}"
    }

  spec {
    selector = {
      app = <PLACEHOLDER>
    }
    port {
      port        = <PLACEHOLDER>
      target_port = <PLACEHOLDER>
    }

    type = "LoadBalancer"
    load_balancer_ip = "${azurerm_public_ip.YOUR_IP.ip_address}"
  }
}


问:
How could I make this LINQ query more efficient?
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

```<code>    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }
</code>```

The customerOrder is a customer Order class.

```<code>public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}
</code>```

答:
first of all you can cat your execution time in almost half if you do not call database twice first you call it in the if:

```<code>customerOrder.OrderLines
            .SelectMany(ol => ol.OrderDates)
            .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null).Any())
</code>```

and than in true branch:

```<code>var date = customerOrder.OrderLines
                                .SelectMany(ol => ol.OrderDates)
                                .OrderBy(d => d.ActualDate)
                                .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null).ActualDate;
</code>```

if you look at those they are virtually identical you can achieve same result using this:

```<code>var date = customerOrder.OrderLines
                                .SelectMany(ol => ol.OrderDates)
                                .OrderBy(d => d.ActualDate)
                                .Where(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
.Select(x => x.ActualDate)
.FirstOrDefault();
</code>```

now null value in date will serve you as bases for the if statement

```<code>if(date != null) {

   // do your stuff
}
</code>```

Other than this you can create an index on the database that covers your query so containing DataTypeId and ActualDate.

Body:
Any suggestions on how to make this LINQ query more efficient? I recently created the formattedDate variable as previously I was calling the GetDateInFormat multiple times.

    if (customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null)
          .Any())
    {
        var date = customerOrder.OrderLines
          .SelectMany(ol => ol.OrderDates)
          .OrderBy(d => d.ActualDate)
          .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
          .ActualDate;

        if (date != null)
        {
            var formattedDate = _dateHelper.GetDateInFormat("DD/MM/YYYY", date);
            order.ArriveDate = formattedDate;
            order.EarliestShipDate = formattedDate;
            order.EarliestDeliveryDate = formattedDate;
            order.EarliestApptTime = _dateHelper.GetDateInFormat("HHMM", date);
        }
    }

The customerOrder is a customer Order class.

public class Order
{
    public Order();

    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public OrderLine();

    public List<OrderDate> OrderDates { get; set; }
}

public class OrderDate
{
    public OrderDate();

    public DateTimeOffset? ActualDate { get; set; }
    public string DateTypeId { get; set; }
}

Body:
first of all you can cat your execution time in almost half if you do not call database twice first you call it in the if:

customerOrder.OrderLines
            .SelectMany(ol => ol.OrderDates)
            .Where(ol => ol.DateTypeId == "OrderPickUpFrom" && ol.ActualDate != null).Any())

and than in true branch:

var date = customerOrder.OrderLines
                                .SelectMany(ol => ol.OrderDates)
                                .OrderBy(d => d.ActualDate)
                                .FirstOrDefault(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null).ActualDate;

if you look at those they are virtually identical you can achieve same result using this:

var date = customerOrder.OrderLines
                                .SelectMany(ol => ol.OrderDates)
                                .OrderBy(d => d.ActualDate)
                                .Where(d => d.DateTypeId == "OrderPickUpFrom" && d.ActualDate != null)
.Select(x => x.ActualDate)
.FirstOrDefault();

now null value in date will serve you as bases for the if statement

if(date != null) {

   // do your stuff
}

Other than this you can create an index on the database that covers your query so containing DataTypeId and ActualDate.


问:
How to set the limit for the dragging the div vise versa no more than minimum width which is 200
How can I set minimum width for not allowing drag left to no width in the following sample?

```<code>const App = () => {

    const [initialPos,   setInitialPos] = React.useState(null);
    const [initialSize, setInitialSize] = React.useState(null);

    const initial = (e) => {

        let resizable = document.getElementById('Resizable');

        setInitialPos(e.clientX);
        setInitialSize(resizable.offsetWidth);

    }

    const resize = (e) => {

        let resizable = document.getElementById('Resizable');

        resizable.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;

    }

    return(
        <div className = 'Block'>
            <div id = 'Resizable'/>
            <div id = 'Draggable'
                draggable   = 'true'
                onDragStart = {initial}
                onDrag      = {resize}
            />
        </div>
    );

}

ReactDOM.render(<App/>, document.getElementById('root'));
</code>```

https://codepen.io/erikmartinjordan/pen/dyMEXJb?editors=0110

答:
This will allow you to move the end to either left or right with maximum of 200 pixels.

```<code>const initial = (e) => {
  let resizable = document.getElementById("Resizable");

  // lock the start position
  if (initialPos == null) {
    setInitialPos(e.clientX);
    setInitialSize(resizable.offsetWidth);
  }
};

const resize = (e) => {
  let resizable = document.getElementById("Resizable");
  // check for the absolute distance from the start point
  if (Math.abs(e.clientX - initialPos) < 200) {
    resizable.style.width = `${
      parseInt(initialSize) + parseInt(e.clientX - initialPos)
    }px`;
  }
};
</code>```

CodePen

Body:
How can I set minimum width for not allowing drag left to no width in the following sample?

const App = () => {

    const [initialPos,   setInitialPos] = React.useState(null);
    const [initialSize, setInitialSize] = React.useState(null);

    const initial = (e) => {

        let resizable = document.getElementById('Resizable');

        setInitialPos(e.clientX);
        setInitialSize(resizable.offsetWidth);

    }

    const resize = (e) => {

        let resizable = document.getElementById('Resizable');

        resizable.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;

    }

    return(

    );

}

ReactDOM.render(<App/>, document.getElementById('root'));

https://codepen.io/erikmartinjordan/pen/dyMEXJb?editors=0110

Body:
This will allow you to move the end to either left or right with maximum of 200 pixels.

const initial = (e) => {
  let resizable = document.getElementById("Resizable");

  // lock the start position
  if (initialPos == null) {
    setInitialPos(e.clientX);
    setInitialSize(resizable.offsetWidth);
  }
};

const resize = (e) => {
  let resizable = document.getElementById("Resizable");
  // check for the absolute distance from the start point
  if (Math.abs(e.clientX - initialPos) < 200) {
    resizable.style.width = `${
      parseInt(initialSize) + parseInt(e.clientX - initialPos)
    }px`;
  }
};

CodePen


问:
Please do I interprete this ternary operator?
Please if this function was to be converted to a "normal" if else statement, how would it look like?

```<code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));
</code>```

I want to add another condition, but I'm finding it hard to read or digest the current flow.

答:
First lets expand the code to make it (slightly) easier to read.

Note that the ?: contains questionable logic, use of === seems to suggest it is trying to handle sorting an array of mixed types, but then using non-strict < and > comparisons. So for the purposes of the rest of this answer I am going to assume it is not trying to sort mixed typed arrays or that if it is, it will ignore strict type comparisons (ie the === should really be ==)

function orderArr (arr: any[], key: string) {
  function sorter(a, b) {
    return (
      (a[key] > b[key])
      ? 1
      : (a[key] === b[key])
        ? (
          (a[key] > b[key])
            ? 1
            : -1
        )
        : -1
    );
  }
  return arr.sort(sorter);
}

export orderArr;
```
<p>Now lets re-write the overcomplicated <code>?:</code> expression (overcomplicated not because of the <code>?:</code> syntax but because its doing more than it needs to) and rewrite as if then elses (note, this code is still wrong)</p>
<pre class="lang-js prettyprint-override"><code>function sorter(a, b) {
   if (a[key] > b[key]) {
     return 1;         // return 1 if a > b
   } else {
     if (a[key] === b[key]) {        // questionable logic
       if (a[key] > b[key]) {        // questionable logic
         return 1;
       } else {
         return -1;      // will always return -1 (wrong, a == b should return 0)
       }
     } else {
       return -1;     // return -1 if a < b
         // or if type of a does not equal type of b (questionable)
     }
   }
}
</code>```

Now lets simplify and fix the bug (ie remove the strict type comparison). Using a technique called early return (also called guard clauses), and avoiding using else as it adds unnecessary indentation and complication

function sorter(a, b) {
   if (a[key] > b[key]) return 1;
   if (a[key] < b[key]) return -1;
   return 0;
}
```
<p>Or if you prefer, using <code>?:</code> syntax</p>
<pre class="lang-js prettyprint-override"><code>function sorter(a, b) {
   return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}
</code>```

If you are sorting numbers, you can use a little trick to further simplify the code. Sort expects a 0 if a and b are equal, a negative value if a < b and a positive value if a > b, so for numeric sorting we can simply do

function sorter(a, b) {
   return a[key] - b[key];
}
```
<p>Now, lets put all the simplified code back together into a single line. First for any type of array.</p>
<pre class="lang-js prettyprint-override"><code>export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);
</code>```

and for a numerical only array

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);
```

Body:
Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.

Body:
First lets expand the code to make it (slightly) easier to read.

Note that the ?: contains questionable logic, use of === seems to suggest it is trying to handle sorting an array of mixed types, but then using non-strict < and > comparisons. So for the purposes of the rest of this answer I am going to assume it is not trying to sort mixed typed arrays or that if it is, it will ignore strict type comparisons (ie the === should really be ==)

function orderArr (arr: any[], key: string) {
  function sorter(a, b) {
    return (
      (a[key] > b[key])
      ? 1
      : (a[key] === b[key])
        ? (
          (a[key] > b[key])
            ? 1
            : -1
        )
        : -1
    );
  }
  return arr.sort(sorter);
}

export orderArr;

Now lets re-write the overcomplicated ?: expression (overcomplicated not because of the ?: syntax but because its doing more than it needs to) and rewrite as if then elses (note, this code is still wrong)

function sorter(a, b) {
   if (a[key] > b[key]) {
     return 1;         // return 1 if a > b
   } else {
     if (a[key] === b[key]) {        // questionable logic
       if (a[key] > b[key]) {        // questionable logic
         return 1;
       } else {
         return -1;      // will always return -1 (wrong, a == b should return 0)
       }
     } else {
       return -1;     // return -1 if a < b
         // or if type of a does not equal type of b (questionable)
     }
   }
}

Now lets simplify and fix the bug (ie remove the strict type comparison). Using a technique called early return (also called guard clauses), and avoiding using else as it adds unnecessary indentation and complication

function sorter(a, b) {
   if (a[key] > b[key]) return 1;
   if (a[key] < b[key]) return -1;
   return 0;
}

Or if you prefer, using ?: syntax

function sorter(a, b) {
   return a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0;
}

If you are sorting numbers, you can use a little trick to further simplify the code. Sort expects a 0 if a and b are equal, a negative value if a < b and a positive value if a > b, so for numeric sorting we can simply do

function sorter(a, b) {
   return a[key] - b[key];
}

Now, lets put all the simplified code back together into a single line. First for any type of array.

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0);

and for a numerical only array

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => a[key] - b[key]);


问:
Truncation error SQL server 2005 Delete/Insert
So I am trying to do a bulk insert with SSIS and continually get:

"Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "String or binary data would be truncated."

Even though I already have a data conversion for every column into the exact same type as the table that the rows are getting inserted into. I used a view and the data looks like it supposed to just before the DB insert step. Still get the error.

Next I went into sql server management studio and setup an insert query into that damned table and still get the same truncation error. I then did a set ANSI_WARNINGS  OFF and the insert works data looks good in the table. Now when I try to delete this row I get the Truncation error.

My question besides any basic input to the situation is how can I turn off the ANSI_WARNINGS within SSIS so that the bulk load can go though?

答: Sounds like you've got one row (possibly more, but it only takes one!) where your data value exceeds the length of the table columns. Doing a data conversion to the shorter type will MOVE the error to whatever transform does the conversion from the Destination. What I'd recommend is creating a Flat File Destination, and tying the error output of your transforms to it. Change the error result to 'Redirect Row'. This will allow all the valid rows to go through, and provide you with a copy of the row(s) that are getting truncated for you to manually handle.</p>

OwnerDisplayName: Andrew Jahn

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Harper Shelby


问:
sql trigger to stop duplicates across row
I have a table with multiple records:

User_Name     ( e.g. 'TOM')

Question_ID    (eg 'q002')

Answer         (e.g. 'D')

i want to create a trigger so that no one can submit an answer to the same question twice.
It has to be a trigger only.

```<code>CREATE TRIGGER trigger_Check_Duplicates

ON submit_Answer

FOR INSERT
AS

IF SELECT???

PRINT 'duplicate'

raiserror('cant submit answer to same question twice')

ROLLBACK

End
</code>```

答:
MySql does not support INSTEAD OF triggers, which is what you'd need to use here.  In SQL Server, you'd use an INSTEAD OF INSERT trigger that will fire before the insert occurs, where you can write a check for the duplicate.  However, if you can avoid a trigger, why not use a Stored Routine and just check for the duplicate before inserting?

This is, of course, if you really, really cannot use a constraint.

Edit: Updating answer for MSSQL.

Here's an example right from MSDN:

```<code>CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If there is no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log an attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no there is duplicate, do an INSERT.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If there is a duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END
</code>```

You'll obviously need to modify/simplify for your situation, but the basic context is there.

Body:
I have a table with multiple records:

User_Name     ( e.g. 'TOM')

Question_ID    (eg 'q002')

Answer         (e.g. 'D')

i want to create a trigger so that no one can submit an answer to the same question twice.
It has to be a trigger only.

CREATE TRIGGER trigger_Check_Duplicates

ON submit_Answer

FOR INSERT
AS

IF SELECT???

PRINT 'duplicate'

raiserror('cant submit answer to same question twice')

ROLLBACK

End

Body:
MySql does not support INSTEAD OF triggers, which is what you'd need to use here.  In SQL Server, you'd use an INSTEAD OF INSERT trigger that will fire before the insert occurs, where you can write a check for the duplicate.  However, if you can avoid a trigger, why not use a Stored Routine and just check for the duplicate before inserting?

This is, of course, if you really, really cannot use a constraint.

Edit: Updating answer for MSSQL.

Here's an example right from MSDN:

CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If there is no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log an attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no there is duplicate, do an INSERT.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If there is a duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END

You'll obviously need to modify/simplify for your situation, but the basic context is there.


问:
Flutter Inkwell does not update right away
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

```<code>class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }
</code>```

market_card.dart

```<code>class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
</code>```

答:
Try this</p>
```<code>@override
void initState() {
super.initState();
MarketList marketList = context.read<MarketList>();

 setState(() {
           displayedList = marketList.markets.keys.toList();
         });
    print(displayedList.length)
}
</code>```

Body:
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }

market_card.dart

class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Body:
Try this

@override
void initState() {
super.initState();
MarketList marketList = context.read<MarketList>();

 setState(() {
           displayedList = marketList.markets.keys.toList();
         });
    print(displayedList.length)
}


问:
How to get IP Address from url without gethostbyname in Winsock API
I want to get IP Address from URL. I find the answer in google, it only has gethostbyname() function solution, but MSDN said that this function is not used anymore.

I try to use getaddressinfo() or getnameinfo() (the example in MSDN), it only returns 255.255.255.255.

How can I do? Thank all!

答:
Addresses are obtained by domain name, not by URL.

Here are two functions to get an IPv6 and IPv4 address from a domain name.

Functions parameter is domain_name - domain name (eg dns.google).
The result is local_internet_name - a list of IPv6 or IPv4 addresses depending on the function used (e.g. {[8.8.8.8], [8.8.4.4]} for IPv4 addresses of the dns.google domain)
The return value is the attribute "Addresses found or not found" (true and false).

domain_name_to_internet_6_name

domain_name_to_internet_4_name

The functions use the MFC string classes, the C++ standard library, Windows DNS functions, and network functions.

An example of the output from a test console program:

2001:4860:4860::8888
2001:4860:4860::8844
8.8.8.8
8.8.4.4

D:\Projects\DNS_Test\Debug\DNS_Test.exe (process 14740) exited with code 0.
Press any key to close this window . . .

To create an executable for Windows, in Microsoft Visual Studio, you need to create a project from the "Console Application for Windows" template, and set the project properties to "Use MFC library" (as a shared library or as a static library)

Here's the code for a console program:

```<code>#include <afxwin.h>

#include <iostream>
#include <string>
#include <list>

#include <ws2tcpip.h>

#pragma comment(lib, "normaliz.lib")
#pragma comment(lib, "dnsapi.lib")

bool domain_name_to_internet_6_name(CStringW domain_name, std::list<CStringA>& local_internet_name)
{
  const size_t CONST_MESSAGE_LENGTH = 500;

  wchar_t local_domain_name_unicode[CONST_MESSAGE_LENGTH];

  ZeroMemory(local_domain_name_unicode, sizeof(wchar_t) * CONST_MESSAGE_LENGTH);

  if (IdnToAscii(0, domain_name, domain_name.GetLength(), local_domain_name_unicode, CONST_MESSAGE_LENGTH) == 0)
  {
    const int local_error_message_size = 500;
    wchar_t local_error_message[local_error_message_size];

    const int local_system_error_message_size = local_error_message_size - 250;
    wchar_t local_system_error_message[local_system_error_message_size];

    wcscpy_s(local_system_error_message, local_system_error_message_size, L"IdnToAscii finished with error");

    CString local_time_string = CTime::GetCurrentTime().FormatGmt("%d/%m/%y %H:%M:%S GMT");

    wsprintf((wchar_t*)local_error_message, L"Networking error -- %s -- %s\r\n", local_system_error_message, local_time_string.GetBuffer());

    //  В local_error_message находится текст с кодом сетевой ошибки при выполнении функции IdnToAscii

    return false;
  }

  PDNS_RECORD   ppQueryResults;

  ZeroMemory(&ppQueryResults, sizeof(ppQueryResults));

  if (DnsQuery_W(local_domain_name_unicode, DNS_TYPE_AAAA, 0, NULL, &ppQueryResults, NULL) == ERROR_SUCCESS)
  {
    for (PDNS_RECORD ptr = ppQueryResults; ptr != NULL; ptr = ptr->pNext)
    {
      if (ptr->wType == DNS_TYPE_AAAA)
      {
        if (ptr->wDataLength != 0)
        {
          char local_address_buffer[100];
          inet_ntop(AF_INET6, &ptr->Data.AAAA.Ip6Address.IP6Byte, local_address_buffer, 100);

          local_internet_name.push_back(local_address_buffer);
        }
      }
    }

    DnsFree(ppQueryResults, DnsFreeRecordList);

    if (local_internet_name.size() != 0)
    {
      return true;  //  Адреса найдены
    }
    else
    {
      return false; //  Адреса не найдены
    }

    return true;
  }

  return false;
}

bool domain_name_to_internet_4_name(CStringW domain_name, std::list<CStringA>& local_internet_name)
{
  const size_t CONST_MESSAGE_LENGTH = 500;

  wchar_t local_domain_name_unicode[CONST_MESSAGE_LENGTH];

  ZeroMemory(local_domain_name_unicode, sizeof(wchar_t) * CONST_MESSAGE_LENGTH);

  if (IdnToAscii(0, domain_name, domain_name.GetLength(), local_domain_name_unicode, CONST_MESSAGE_LENGTH) == 0)
  {
    const int local_error_message_size = 500;
    wchar_t local_error_message[local_error_message_size];

    const int local_system_error_message_size = local_error_message_size - 250;
    wchar_t local_system_error_message[local_system_error_message_size];

    wcscpy_s(local_system_error_message, local_system_error_message_size, L"IdnToAscii finished with error");

    CString local_time_string = CTime::GetCurrentTime().FormatGmt("%d/%m/%y %H:%M:%S GMT");

    wsprintf((wchar_t*)local_error_message, L"Networking error -- %s -- %s\r\n", local_system_error_message, local_time_string.GetBuffer());

    //  В local_error_message находится текст с кодом сетевой ошибки при выполнении функции IdnToAscii

    return false;
  }

  PDNS_RECORD   ppQueryResults;

  ZeroMemory(&ppQueryResults, sizeof(ppQueryResults));

  if (DnsQuery_W(local_domain_name_unicode, DNS_TYPE_A, 0, NULL, &ppQueryResults, NULL) == ERROR_SUCCESS)
  {
    for (PDNS_RECORD ptr = ppQueryResults; ptr != NULL; ptr = ptr->pNext)
    {
      if (ptr->wType == DNS_TYPE_A)
      {
        if (ptr->wDataLength != 0)
        {
          char local_address_buffer[100];
          inet_ntop(AF_INET, &ptr->Data.A.IpAddress, local_address_buffer, 100);

          local_internet_name.push_back(local_address_buffer);
        }
      }
    }

    DnsFree(ppQueryResults, DnsFreeRecordList);

    if (local_internet_name.size() != 0)
    {
      return true;  //  Адреса найдены
    }
    else
    {
      return false; //  Адреса не найдены
    }

    return true;
  }

  return false;
}

int main()
{
  std::list<CStringA> local_internet_name_6;
  if (domain_name_to_internet_6_name(CStringW(L"dns.google"), local_internet_name_6))
  {
    for (auto i = local_internet_name_6.begin(); i != local_internet_name_6.end(); i++)
    {
      std::cout << *i << std::endl;
    }
  }

  std::list<CStringA> local_internet_name_4;
  if (domain_name_to_internet_4_name(CStringW(L"dns.google"), local_internet_name_4))
  {
    for (auto i = local_internet_name_4.begin(); i != local_internet_name_4.end(); i++)
    {
      std::cout << *i << std::endl;
    }
  }
}
</code>```

Body:
Addresses are obtained by domain name, not by URL.

Here are two functions to get an IPv6 and IPv4 address from a domain name.

Functions parameter is domain_name - domain name (eg dns.google).
The result is local_internet_name - a list of IPv6 or IPv4 addresses depending on the function used (e.g. {[8.8.8.8], [8.8.4.4]} for IPv4 addresses of the dns.google domain)
The return value is the attribute "Addresses found or not found" (true and false).

domain_name_to_internet_6_name

domain_name_to_internet_4_name

The functions use the MFC string classes, the C++ standard library, Windows DNS functions, and network functions.

An example of the output from a test console program:

2001:4860:4860::8888
2001:4860:4860::8844
8.8.8.8
8.8.4.4

D:\Projects\DNS_Test\Debug\DNS_Test.exe (process 14740) exited with code 0.
Press any key to close this window . . .

To create an executable for Windows, in Microsoft Visual Studio, you need to create a project from the "Console Application for Windows" template, and set the project properties to "Use MFC library" (as a shared library or as a static library)

Here's the code for a console program:

#include <afxwin.h>

#include <iostream>
#include <string>
#include <list>

#include <ws2tcpip.h>

#pragma comment(lib, "normaliz.lib")
#pragma comment(lib, "dnsapi.lib")

bool domain_name_to_internet_6_name(CStringW domain_name, std::list<CStringA>& local_internet_name)
{
  const size_t CONST_MESSAGE_LENGTH = 500;

  wchar_t local_domain_name_unicode[CONST_MESSAGE_LENGTH];

  ZeroMemory(local_domain_name_unicode, sizeof(wchar_t) * CONST_MESSAGE_LENGTH);

  if (IdnToAscii(0, domain_name, domain_name.GetLength(), local_domain_name_unicode, CONST_MESSAGE_LENGTH) == 0)
  {
    const int local_error_message_size = 500;
    wchar_t local_error_message[local_error_message_size];

    const int local_system_error_message_size = local_error_message_size - 250;
    wchar_t local_system_error_message[local_system_error_message_size];

    wcscpy_s(local_system_error_message, local_system_error_message_size, L"IdnToAscii finished with error");

    CString local_time_string = CTime::GetCurrentTime().FormatGmt("%d/%m/%y %H:%M:%S GMT");

    wsprintf((wchar_t*)local_error_message, L"Networking error -- %s -- %s\r\n", local_system_error_message, local_time_string.GetBuffer());

    //  В local_error_message находится текст с кодом сетевой ошибки при выполнении функции IdnToAscii

    return false;
  }

  PDNS_RECORD   ppQueryResults;

  ZeroMemory(&ppQueryResults, sizeof(ppQueryResults));

  if (DnsQuery_W(local_domain_name_unicode, DNS_TYPE_AAAA, 0, NULL, &ppQueryResults, NULL) == ERROR_SUCCESS)
  {
    for (PDNS_RECORD ptr = ppQueryResults; ptr != NULL; ptr = ptr->pNext)
    {
      if (ptr->wType == DNS_TYPE_AAAA)
      {
        if (ptr->wDataLength != 0)
        {
          char local_address_buffer[100];
          inet_ntop(AF_INET6, &ptr->Data.AAAA.Ip6Address.IP6Byte, local_address_buffer, 100);

          local_internet_name.push_back(local_address_buffer);
        }
      }
    }

    DnsFree(ppQueryResults, DnsFreeRecordList);

    if (local_internet_name.size() != 0)
    {
      return true;  //  Адреса найдены
    }
    else
    {
      return false; //  Адреса не найдены
    }

    return true;
  }

  return false;
}

bool domain_name_to_internet_4_name(CStringW domain_name, std::list<CStringA>& local_internet_name)
{
  const size_t CONST_MESSAGE_LENGTH = 500;

  wchar_t local_domain_name_unicode[CONST_MESSAGE_LENGTH];

  ZeroMemory(local_domain_name_unicode, sizeof(wchar_t) * CONST_MESSAGE_LENGTH);

  if (IdnToAscii(0, domain_name, domain_name.GetLength(), local_domain_name_unicode, CONST_MESSAGE_LENGTH) == 0)
  {
    const int local_error_message_size = 500;
    wchar_t local_error_message[local_error_message_size];

    const int local_system_error_message_size = local_error_message_size - 250;
    wchar_t local_system_error_message[local_system_error_message_size];

    wcscpy_s(local_system_error_message, local_system_error_message_size, L"IdnToAscii finished with error");

    CString local_time_string = CTime::GetCurrentTime().FormatGmt("%d/%m/%y %H:%M:%S GMT");

    wsprintf((wchar_t*)local_error_message, L"Networking error -- %s -- %s\r\n", local_system_error_message, local_time_string.GetBuffer());

    //  В local_error_message находится текст с кодом сетевой ошибки при выполнении функции IdnToAscii

    return false;
  }

  PDNS_RECORD   ppQueryResults;

  ZeroMemory(&ppQueryResults, sizeof(ppQueryResults));

  if (DnsQuery_W(local_domain_name_unicode, DNS_TYPE_A, 0, NULL, &ppQueryResults, NULL) == ERROR_SUCCESS)
  {
    for (PDNS_RECORD ptr = ppQueryResults; ptr != NULL; ptr = ptr->pNext)
    {
      if (ptr->wType == DNS_TYPE_A)
      {
        if (ptr->wDataLength != 0)
        {
          char local_address_buffer[100];
          inet_ntop(AF_INET, &ptr->Data.A.IpAddress, local_address_buffer, 100);

          local_internet_name.push_back(local_address_buffer);
        }
      }
    }

    DnsFree(ppQueryResults, DnsFreeRecordList);

    if (local_internet_name.size() != 0)
    {
      return true;  //  Адреса найдены
    }
    else
    {
      return false; //  Адреса не найдены
    }

    return true;
  }

  return false;
}

int main()
{
  std::list<CStringA> local_internet_name_6;
  if (domain_name_to_internet_6_name(CStringW(L"dns.google"), local_internet_name_6))
  {
    for (auto i = local_internet_name_6.begin(); i != local_internet_name_6.end(); i++)
    {
      std::cout << *i << std::endl;
    }
  }

  std::list<CStringA> local_internet_name_4;
  if (domain_name_to_internet_4_name(CStringW(L"dns.google"), local_internet_name_4))
  {
    for (auto i = local_internet_name_4.begin(); i != local_internet_name_4.end(); i++)
    {
      std::cout << *i << std::endl;
    }
  }
}